From 341ddea8cc713a1587392176eca55308ddf25e6b Mon Sep 17 00:00:00 2001 From: Anshuman Singh Date: Sat, 11 Apr 2026 05:40:30 +0530 Subject: [PATCH 1/9] fix: parse form-encoded body on OpenNode callback route --- src/routes/callbacks/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/routes/callbacks/index.ts b/src/routes/callbacks/index.ts index 5b86e0bf..cb23cd64 100644 --- a/src/routes/callbacks/index.ts +++ b/src/routes/callbacks/index.ts @@ -1,4 +1,4 @@ -import { json, Router } from 'express' +import { json, Router, urlencoded } from 'express' import { createLNbitsCallbackController } from '../../factories/controllers/lnbits-callback-controller-factory' import { createNodelessCallbackController } from '../../factories/controllers/nodeless-callback-controller-factory' @@ -16,6 +16,6 @@ router (req as any).rawBody = buf }, }), withController(createNodelessCallbackController)) - .post('/opennode', json(), withController(createOpenNodeCallbackController)) + .post('/opennode', urlencoded({ extended: false }), json(), withController(createOpenNodeCallbackController)) export default router From 6473ae561275558842c38ac2e4085dc1f9f2eb88 Mon Sep 17 00:00:00 2001 From: Anshuman Singh Date: Sat, 11 Apr 2026 05:40:37 +0530 Subject: [PATCH 2/9] fix: validate OpenNode webhook signature before processing --- .../callbacks/opennode-callback-controller.ts | 89 ++++++++++++++++--- 1 file changed, 78 insertions(+), 11 deletions(-) diff --git a/src/controllers/callbacks/opennode-callback-controller.ts b/src/controllers/callbacks/opennode-callback-controller.ts index f3755df0..32467c69 100644 --- a/src/controllers/callbacks/opennode-callback-controller.ts +++ b/src/controllers/callbacks/opennode-callback-controller.ts @@ -1,8 +1,12 @@ +import { timingSafeEqual } from 'crypto' + import { Request, Response } from 'express' import { Invoice, InvoiceStatus } from '../../@types/invoice' import { createLogger } from '../../factories/logger-factory' -import { fromOpenNodeInvoice } from '../../utils/transform' +import { createSettings } from '../../factories/settings-factory' +import { getRemoteAddress } from '../../utils/http' +import { hmacSha256 } from '../../utils/secret' import { IController } from '../../@types/controllers' import { IPaymentsService } from '../../@types/services' @@ -13,7 +17,6 @@ export class OpenNodeCallbackController implements IController { private readonly paymentsService: IPaymentsService, ) {} - // TODO: Validate public async handleRequest( request: Request, response: Response, @@ -21,7 +24,72 @@ export class OpenNodeCallbackController implements IController { debug('request headers: %o', request.headers) debug('request body: %O', request.body) - const invoice = fromOpenNodeInvoice(request.body) + const settings = createSettings() + const remoteAddress = getRemoteAddress(request, settings) + const paymentProcessor = settings.payments?.processor + + if (paymentProcessor !== 'opennode') { + debug('denied request from %s to /callbacks/opennode which is not the current payment processor', remoteAddress) + response + .status(403) + .send('Forbidden') + return + } + + const validStatuses = ['expired', 'refunded', 'unpaid', 'processing', 'underpaid', 'paid'] + + if ( + !request.body + || typeof request.body.id !== 'string' + || typeof request.body.hashed_order !== 'string' + || typeof request.body.status !== 'string' + || !validStatuses.includes(request.body.status) + ) { + response + .status(400) + .setHeader('content-type', 'text/plain; charset=utf8') + .send('Bad Request') + return + } + + const openNodeApiKey = process.env.OPENNODE_API_KEY + if (!openNodeApiKey) { + debug('OPENNODE_API_KEY is not configured; unable to verify OpenNode callback from %s', remoteAddress) + response + .status(500) + .setHeader('content-type', 'text/plain; charset=utf8') + .send('Internal Server Error') + return + } + + const expectedBuf = hmacSha256(openNodeApiKey, request.body.id) + const actualHex = request.body.hashed_order + const actualBuf = Buffer.from(actualHex, 'hex') + + if ( + expectedBuf.length !== actualBuf.length + || !timingSafeEqual(expectedBuf, actualBuf) + ) { + debug('unauthorized request from %s to /callbacks/opennode: hashed_order mismatch', remoteAddress) + response + .status(403) + .send('Forbidden') + return + } + + const statusMap: Record = { + expired: InvoiceStatus.EXPIRED, + refunded: InvoiceStatus.EXPIRED, + unpaid: InvoiceStatus.PENDING, + processing: InvoiceStatus.PENDING, + underpaid: InvoiceStatus.PENDING, + paid: InvoiceStatus.COMPLETED, + } + + const invoice: Pick = { + id: request.body.id, + status: statusMap[request.body.status], + } debug('invoice', invoice) @@ -34,10 +102,7 @@ export class OpenNodeCallbackController implements IController { throw error } - if ( - updatedInvoice.status !== InvoiceStatus.COMPLETED - && !updatedInvoice.confirmedAt - ) { + if (updatedInvoice.status !== InvoiceStatus.COMPLETED) { response .status(200) .send() @@ -45,13 +110,15 @@ export class OpenNodeCallbackController implements IController { return } - invoice.amountPaid = invoice.amountRequested - updatedInvoice.amountPaid = invoice.amountRequested + if (!updatedInvoice.confirmedAt) { + updatedInvoice.confirmedAt = new Date() + } + updatedInvoice.amountPaid = updatedInvoice.amountRequested try { await this.paymentsService.confirmInvoice({ - id: invoice.id, - pubkey: invoice.pubkey, + id: updatedInvoice.id, + pubkey: updatedInvoice.pubkey, status: updatedInvoice.status, amountPaid: updatedInvoice.amountRequested, confirmedAt: updatedInvoice.confirmedAt, From 5cc207cab6661ac728a51810bc827b2665d76919 Mon Sep 17 00:00:00 2001 From: Anshuman Singh Date: Sat, 11 Apr 2026 05:40:44 +0530 Subject: [PATCH 3/9] test: add unit tests for OpenNode callback controller and route --- .../opennode-callback-controller.spec.ts | 187 ++++++++++++++++++ test/unit/routes/callbacks.spec.ts | 80 ++++++++ 2 files changed, 267 insertions(+) create mode 100644 test/unit/controllers/callbacks/opennode-callback-controller.spec.ts create mode 100644 test/unit/routes/callbacks.spec.ts diff --git a/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts b/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts new file mode 100644 index 00000000..c20b5712 --- /dev/null +++ b/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts @@ -0,0 +1,187 @@ +import chai, { expect } from 'chai' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +import * as httpUtils from '../../../../src/utils/http' +import * as settingsFactory from '../../../../src/factories/settings-factory' + +import { hmacSha256 } from '../../../../src/utils/secret' +import { InvoiceStatus } from '../../../../src/@types/invoice' +import { OpenNodeCallbackController } from '../../../../src/controllers/callbacks/opennode-callback-controller' + +chai.use(sinonChai) + +describe('OpenNodeCallbackController', () => { + let createSettingsStub: Sinon.SinonStub + let getRemoteAddressStub: Sinon.SinonStub + let updateInvoiceStatusStub: Sinon.SinonStub + let confirmInvoiceStub: Sinon.SinonStub + let sendInvoiceUpdateNotificationStub: Sinon.SinonStub + let statusStub: Sinon.SinonStub + let setHeaderStub: Sinon.SinonStub + let sendStub: Sinon.SinonStub + let controller: OpenNodeCallbackController + let request: any + let response: any + let previousOpenNodeApiKey: string | undefined + + beforeEach(() => { + previousOpenNodeApiKey = process.env.OPENNODE_API_KEY + process.env.OPENNODE_API_KEY = 'test-api-key' + + createSettingsStub = Sinon.stub(settingsFactory, 'createSettings').returns({ + payments: { processor: 'opennode' }, + } as any) + getRemoteAddressStub = Sinon.stub(httpUtils, 'getRemoteAddress').returns('127.0.0.1') + + updateInvoiceStatusStub = Sinon.stub() + confirmInvoiceStub = Sinon.stub() + sendInvoiceUpdateNotificationStub = Sinon.stub() + + controller = new OpenNodeCallbackController({ + updateInvoiceStatus: updateInvoiceStatusStub, + confirmInvoice: confirmInvoiceStub, + sendInvoiceUpdateNotification: sendInvoiceUpdateNotificationStub, + } as any) + + statusStub = Sinon.stub() + setHeaderStub = Sinon.stub() + sendStub = Sinon.stub() + + response = { + send: sendStub, + setHeader: setHeaderStub, + status: statusStub, + } + + statusStub.returns(response) + setHeaderStub.returns(response) + sendStub.returns(response) + + request = { + body: {}, + headers: {}, + } + }) + + afterEach(() => { + getRemoteAddressStub.restore() + createSettingsStub.restore() + + if (typeof previousOpenNodeApiKey === 'undefined') { + delete process.env.OPENNODE_API_KEY + } else { + process.env.OPENNODE_API_KEY = previousOpenNodeApiKey + } + }) + + it('rejects requests when OpenNode is not the configured payment processor', async () => { + createSettingsStub.returns({ + payments: { processor: 'lnbits' }, + } as any) + + await controller.handleRequest(request, response) + + expect(statusStub).to.have.been.calledOnceWithExactly(403) + expect(sendStub).to.have.been.calledOnceWithExactly('Forbidden') + expect(updateInvoiceStatusStub).not.to.have.been.called + }) + + it('returns bad request for malformed callback bodies', async () => { + request.body = { + id: 'invoice-id', + } + + await controller.handleRequest(request, response) + + expect(statusStub).to.have.been.calledOnceWithExactly(400) + expect(setHeaderStub).to.have.been.calledOnceWithExactly('content-type', 'text/plain; charset=utf8') + expect(sendStub).to.have.been.calledOnceWithExactly('Bad Request') + expect(updateInvoiceStatusStub).not.to.have.been.called + }) + + it('returns bad request for unknown status values', async () => { + request.body = { + hashed_order: 'some-hash', + id: 'invoice-id', + status: 'totally_made_up', + } + + await controller.handleRequest(request, response) + + expect(statusStub).to.have.been.calledOnceWithExactly(400) + expect(sendStub).to.have.been.calledOnceWithExactly('Bad Request') + expect(updateInvoiceStatusStub).not.to.have.been.called + }) + + it('rejects callbacks with mismatched hashed_order', async () => { + request.body = { + hashed_order: 'invalid', + id: 'invoice-id', + status: 'paid', + } + + await controller.handleRequest(request, response) + + expect(statusStub).to.have.been.calledOnceWithExactly(403) + expect(sendStub).to.have.been.calledOnceWithExactly('Forbidden') + expect(updateInvoiceStatusStub).not.to.have.been.called + }) + + it('accepts valid signed callbacks and processes the invoice update', async () => { + request.body = { + amount: 21, + created_at: '2026-04-11T00:00:00.000Z', + description: 'Admission fee', + hashed_order: hmacSha256('test-api-key', 'invoice-id').toString('hex'), + id: 'invoice-id', + lightning: { + expires_at: '2026-04-11T01:00:00.000Z', + payreq: 'lnbc1test', + }, + order_id: 'pubkey', + status: 'unpaid', + } + + updateInvoiceStatusStub.resolves({ + confirmedAt: null, + status: InvoiceStatus.PENDING, + }) + + await controller.handleRequest(request, response) + + expect(updateInvoiceStatusStub).to.have.been.calledOnce + expect(confirmInvoiceStub).not.to.have.been.called + expect(sendInvoiceUpdateNotificationStub).not.to.have.been.called + expect(statusStub).to.have.been.calledOnceWithExactly(200) + expect(sendStub).to.have.been.calledOnceWithExactly() + }) + + it('confirms and notifies on paid callbacks, setting confirmedAt when absent', async () => { + request.body = { + hashed_order: hmacSha256('test-api-key', 'invoice-id').toString('hex'), + id: 'invoice-id', + status: 'paid', + } + + updateInvoiceStatusStub.resolves({ + amountRequested: 1000n, + confirmedAt: null, + id: 'invoice-id', + pubkey: 'somepubkey', + status: InvoiceStatus.COMPLETED, + }) + confirmInvoiceStub.resolves() + sendInvoiceUpdateNotificationStub.resolves() + + await controller.handleRequest(request, response) + + expect(updateInvoiceStatusStub).to.have.been.calledOnce + expect(confirmInvoiceStub).to.have.been.calledOnce + const confirmedAtArg = confirmInvoiceStub.firstCall.args[0].confirmedAt + expect(confirmedAtArg).to.be.instanceOf(Date) + expect(sendInvoiceUpdateNotificationStub).to.have.been.calledOnce + expect(statusStub).to.have.been.calledOnceWithExactly(200) + expect(sendStub).to.have.been.calledOnceWithExactly('OK') + }) +}) \ No newline at end of file diff --git a/test/unit/routes/callbacks.spec.ts b/test/unit/routes/callbacks.spec.ts new file mode 100644 index 00000000..4d5e867c --- /dev/null +++ b/test/unit/routes/callbacks.spec.ts @@ -0,0 +1,80 @@ +import axios from 'axios' +import { expect } from 'chai' +import express from 'express' +import Sinon from 'sinon' + +import * as openNodeControllerFactory from '../../../src/factories/controllers/opennode-callback-controller-factory' + +describe('callbacks router', () => { + let createOpenNodeCallbackControllerStub: Sinon.SinonStub + let receivedBody: unknown + let server: any + + beforeEach(async () => { + receivedBody = undefined + + createOpenNodeCallbackControllerStub = Sinon.stub(openNodeControllerFactory, 'createOpenNodeCallbackController').returns({ + handleRequest: async (request: any, response: any) => { + receivedBody = request.body + response.status(200).send('OK') + }, + } as any) + + // eslint-disable-next-line @typescript-eslint/no-var-requires + delete require.cache[require.resolve('../../../src/routes/callbacks')] + // eslint-disable-next-line @typescript-eslint/no-var-requires + const router = require('../../../src/routes/callbacks').default + + const app = express() + app.use(router) + + server = await new Promise((resolve) => { + const listeningServer = app.listen(0, () => resolve(listeningServer)) + }) + }) + + afterEach(async () => { + createOpenNodeCallbackControllerStub.restore() + delete require.cache[require.resolve('../../../src/routes/callbacks')] + + if (server) { + await new Promise((resolve, reject) => { + server.close((error: Error | undefined) => { + if (error) { + reject(error) + return + } + + resolve() + }) + }) + } + }) + + it('parses form-urlencoded OpenNode callbacks', async () => { + const { port } = server.address() + const response = await axios.post( + `http://127.0.0.1:${port}/opennode`, + new URLSearchParams({ + hashed_order: 'signature', + id: 'invoice-id', + order_id: 'pubkey', + status: 'paid', + }).toString(), + { + headers: { + 'content-type': 'application/x-www-form-urlencoded', + }, + validateStatus: () => true, + }, + ) + + expect(response.status).to.equal(200) + expect(receivedBody).to.deep.equal({ + hashed_order: 'signature', + id: 'invoice-id', + order_id: 'pubkey', + status: 'paid', + }) + }) +}) \ No newline at end of file From 42ae225ecdbaef97963cb423524644bde5f0c1c7 Mon Sep 17 00:00:00 2001 From: Anshuman Singh Date: Sat, 11 Apr 2026 17:01:13 +0530 Subject: [PATCH 4/9] fix: align amountPaid and test missing OPENNODE_API_KEY --- .../callbacks/opennode-callback-controller.ts | 2 +- .../opennode-callback-controller.spec.ts | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/controllers/callbacks/opennode-callback-controller.ts b/src/controllers/callbacks/opennode-callback-controller.ts index 32467c69..732e244a 100644 --- a/src/controllers/callbacks/opennode-callback-controller.ts +++ b/src/controllers/callbacks/opennode-callback-controller.ts @@ -120,7 +120,7 @@ export class OpenNodeCallbackController implements IController { id: updatedInvoice.id, pubkey: updatedInvoice.pubkey, status: updatedInvoice.status, - amountPaid: updatedInvoice.amountRequested, + amountPaid: updatedInvoice.amountPaid, confirmedAt: updatedInvoice.confirmedAt, }) await this.paymentsService.sendInvoiceUpdateNotification(updatedInvoice) diff --git a/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts b/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts index c20b5712..17acc743 100644 --- a/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts +++ b/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts @@ -114,6 +114,22 @@ describe('OpenNodeCallbackController', () => { expect(updateInvoiceStatusStub).not.to.have.been.called }) + it('returns internal server error when OPENNODE_API_KEY is missing', async () => { + delete process.env.OPENNODE_API_KEY + request.body = { + hashed_order: 'some-hash', + id: 'invoice-id', + status: 'paid', + } + + await controller.handleRequest(request, response) + + expect(statusStub).to.have.been.calledOnceWithExactly(500) + expect(setHeaderStub).to.have.been.calledOnceWithExactly('content-type', 'text/plain; charset=utf8') + expect(sendStub).to.have.been.calledOnceWithExactly('Internal Server Error') + expect(updateInvoiceStatusStub).not.to.have.been.called + }) + it('rejects callbacks with mismatched hashed_order', async () => { request.body = { hashed_order: 'invalid', From e99c0554591537532a58b70fc52e1ac4587675d1 Mon Sep 17 00:00:00 2001 From: Anshuman Singh Date: Sat, 11 Apr 2026 17:08:52 +0530 Subject: [PATCH 5/9] fix: reject malformed OpenNode hashed_order --- .../callbacks/opennode-callback-controller.ts | 17 +++++++++++++++-- .../opennode-callback-controller.spec.ts | 17 ++++++++++++++++- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/controllers/callbacks/opennode-callback-controller.ts b/src/controllers/callbacks/opennode-callback-controller.ts index 732e244a..a0375d0a 100644 --- a/src/controllers/callbacks/opennode-callback-controller.ts +++ b/src/controllers/callbacks/opennode-callback-controller.ts @@ -64,11 +64,24 @@ export class OpenNodeCallbackController implements IController { const expectedBuf = hmacSha256(openNodeApiKey, request.body.id) const actualHex = request.body.hashed_order + const expectedHexLength = expectedBuf.length * 2 + + if ( + actualHex.length !== expectedHexLength + || !/^[0-9a-f]+$/i.test(actualHex) + ) { + debug('invalid hashed_order format from %s to /callbacks/opennode', remoteAddress) + response + .status(400) + .setHeader('content-type', 'text/plain; charset=utf8') + .send('Bad Request') + return + } + const actualBuf = Buffer.from(actualHex, 'hex') if ( - expectedBuf.length !== actualBuf.length - || !timingSafeEqual(expectedBuf, actualBuf) + !timingSafeEqual(expectedBuf, actualBuf) ) { debug('unauthorized request from %s to /callbacks/opennode: hashed_order mismatch', remoteAddress) response diff --git a/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts b/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts index 17acc743..0c59eb48 100644 --- a/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts +++ b/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts @@ -130,7 +130,7 @@ describe('OpenNodeCallbackController', () => { expect(updateInvoiceStatusStub).not.to.have.been.called }) - it('rejects callbacks with mismatched hashed_order', async () => { + it('returns bad request for malformed hashed_order', async () => { request.body = { hashed_order: 'invalid', id: 'invoice-id', @@ -139,6 +139,21 @@ describe('OpenNodeCallbackController', () => { await controller.handleRequest(request, response) + expect(statusStub).to.have.been.calledOnceWithExactly(400) + expect(setHeaderStub).to.have.been.calledOnceWithExactly('content-type', 'text/plain; charset=utf8') + expect(sendStub).to.have.been.calledOnceWithExactly('Bad Request') + expect(updateInvoiceStatusStub).not.to.have.been.called + }) + + it('rejects callbacks with mismatched hashed_order', async () => { + request.body = { + hashed_order: '0'.repeat(64), + id: 'invoice-id', + status: 'paid', + } + + await controller.handleRequest(request, response) + expect(statusStub).to.have.been.calledOnceWithExactly(403) expect(sendStub).to.have.been.calledOnceWithExactly('Forbidden') expect(updateInvoiceStatusStub).not.to.have.been.called From 949b78ab1a6c30088e5229c9326313cc089cabe6 Mon Sep 17 00:00:00 2001 From: Anshuman Singh Date: Sat, 11 Apr 2026 17:44:52 +0530 Subject: [PATCH 6/9] fix: avoid logging sensitive OpenNode callback fields --- src/controllers/callbacks/opennode-callback-controller.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/controllers/callbacks/opennode-callback-controller.ts b/src/controllers/callbacks/opennode-callback-controller.ts index a0375d0a..4c3d5fd4 100644 --- a/src/controllers/callbacks/opennode-callback-controller.ts +++ b/src/controllers/callbacks/opennode-callback-controller.ts @@ -22,7 +22,12 @@ export class OpenNodeCallbackController implements IController { response: Response, ) { debug('request headers: %o', request.headers) - debug('request body: %O', request.body) + debug( + 'request body metadata: hasId=%s hasHashedOrder=%s status=%s', + typeof request.body?.id === 'string', + typeof request.body?.hashed_order === 'string', + typeof request.body?.status === 'string' ? request.body.status : 'missing', + ) const settings = createSettings() const remoteAddress = getRemoteAddress(request, settings) From 695c9c70b5b0ad337e09ac7358b39e01462794bf Mon Sep 17 00:00:00 2001 From: anshumancanrock Date: Sat, 18 Apr 2026 22:20:39 +0530 Subject: [PATCH 7/9] fix: validate opennode callback body with zod --- .../callbacks/opennode-callback-controller.ts | 38 +++++++++---------- src/schemas/opennode-callback-schema.ts | 8 ++++ .../opennode-callback-controller.spec.ts | 8 ++-- .../schemas/opennode-callback-schema.spec.ts | 33 +++++++++++++++- 4 files changed, 62 insertions(+), 25 deletions(-) diff --git a/src/controllers/callbacks/opennode-callback-controller.ts b/src/controllers/callbacks/opennode-callback-controller.ts index 4c3d5fd4..11101073 100644 --- a/src/controllers/callbacks/opennode-callback-controller.ts +++ b/src/controllers/callbacks/opennode-callback-controller.ts @@ -9,6 +9,8 @@ import { getRemoteAddress } from '../../utils/http' import { hmacSha256 } from '../../utils/secret' import { IController } from '../../@types/controllers' import { IPaymentsService } from '../../@types/services' +import { opennodeWebhookCallbackBodySchema } from '../../schemas/opennode-callback-schema' +import { validateSchema } from '../../utils/validation' const debug = createLogger('opennode-callback-controller') @@ -22,12 +24,6 @@ export class OpenNodeCallbackController implements IController { response: Response, ) { debug('request headers: %o', request.headers) - debug( - 'request body metadata: hasId=%s hasHashedOrder=%s status=%s', - typeof request.body?.id === 'string', - typeof request.body?.hashed_order === 'string', - typeof request.body?.status === 'string' ? request.body.status : 'missing', - ) const settings = createSettings() const remoteAddress = getRemoteAddress(request, settings) @@ -41,22 +37,24 @@ export class OpenNodeCallbackController implements IController { return } - const validStatuses = ['expired', 'refunded', 'unpaid', 'processing', 'underpaid', 'paid'] - - if ( - !request.body - || typeof request.body.id !== 'string' - || typeof request.body.hashed_order !== 'string' - || typeof request.body.status !== 'string' - || !validStatuses.includes(request.body.status) - ) { + const bodyValidation = validateSchema(opennodeWebhookCallbackBodySchema)(request.body) + if (bodyValidation.error) { + debug('opennode callback request rejected: invalid body %o', bodyValidation.error) response .status(400) .setHeader('content-type', 'text/plain; charset=utf8') - .send('Bad Request') + .send('Malformed body') return } + const body = bodyValidation.value + debug( + 'request body metadata: hasId=%s hasHashedOrder=%s status=%s', + typeof body.id === 'string', + typeof body.hashed_order === 'string', + body.status, + ) + const openNodeApiKey = process.env.OPENNODE_API_KEY if (!openNodeApiKey) { debug('OPENNODE_API_KEY is not configured; unable to verify OpenNode callback from %s', remoteAddress) @@ -67,8 +65,8 @@ export class OpenNodeCallbackController implements IController { return } - const expectedBuf = hmacSha256(openNodeApiKey, request.body.id) - const actualHex = request.body.hashed_order + const expectedBuf = hmacSha256(openNodeApiKey, body.id) + const actualHex = body.hashed_order const expectedHexLength = expectedBuf.length * 2 if ( @@ -105,8 +103,8 @@ export class OpenNodeCallbackController implements IController { } const invoice: Pick = { - id: request.body.id, - status: statusMap[request.body.status], + id: body.id, + status: statusMap[body.status], } debug('invoice', invoice) diff --git a/src/schemas/opennode-callback-schema.ts b/src/schemas/opennode-callback-schema.ts index e94585cc..35430aa1 100644 --- a/src/schemas/opennode-callback-schema.ts +++ b/src/schemas/opennode-callback-schema.ts @@ -1,6 +1,14 @@ import { pubkeySchema } from './base-schema' import { z } from 'zod' +const openNodeCallbackStatuses = ['expired', 'refunded', 'unpaid', 'processing', 'underpaid', 'paid'] as const + +export const opennodeWebhookCallbackBodySchema = z.object({ + id: z.string(), + hashed_order: z.string(), + status: z.enum(openNodeCallbackStatuses), +}).passthrough() + export const opennodeCallbackBodySchema = z.object({ id: z.string(), status: z.string(), diff --git a/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts b/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts index 0c59eb48..213a259a 100644 --- a/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts +++ b/test/unit/controllers/callbacks/opennode-callback-controller.spec.ts @@ -87,7 +87,7 @@ describe('OpenNodeCallbackController', () => { expect(updateInvoiceStatusStub).not.to.have.been.called }) - it('returns bad request for malformed callback bodies', async () => { + it('returns malformed body for invalid callback bodies', async () => { request.body = { id: 'invoice-id', } @@ -96,11 +96,11 @@ describe('OpenNodeCallbackController', () => { expect(statusStub).to.have.been.calledOnceWithExactly(400) expect(setHeaderStub).to.have.been.calledOnceWithExactly('content-type', 'text/plain; charset=utf8') - expect(sendStub).to.have.been.calledOnceWithExactly('Bad Request') + expect(sendStub).to.have.been.calledOnceWithExactly('Malformed body') expect(updateInvoiceStatusStub).not.to.have.been.called }) - it('returns bad request for unknown status values', async () => { + it('returns malformed body for unknown status values', async () => { request.body = { hashed_order: 'some-hash', id: 'invoice-id', @@ -110,7 +110,7 @@ describe('OpenNodeCallbackController', () => { await controller.handleRequest(request, response) expect(statusStub).to.have.been.calledOnceWithExactly(400) - expect(sendStub).to.have.been.calledOnceWithExactly('Bad Request') + expect(sendStub).to.have.been.calledOnceWithExactly('Malformed body') expect(updateInvoiceStatusStub).not.to.have.been.called }) diff --git a/test/unit/schemas/opennode-callback-schema.spec.ts b/test/unit/schemas/opennode-callback-schema.spec.ts index ca5b62de..ad36e019 100644 --- a/test/unit/schemas/opennode-callback-schema.spec.ts +++ b/test/unit/schemas/opennode-callback-schema.spec.ts @@ -1,8 +1,39 @@ +import { opennodeCallbackBodySchema, opennodeWebhookCallbackBodySchema } from '../../../src/schemas/opennode-callback-schema' import { expect } from 'chai' -import { opennodeCallbackBodySchema } from '../../../src/schemas/opennode-callback-schema' import { validateSchema } from '../../../src/utils/validation' describe('OpenNode Callback Schema', () => { + describe('opennodeWebhookCallbackBodySchema', () => { + const validWebhookBody = { + hashed_order: 'a'.repeat(64), + id: 'some-id', + status: 'paid', + } + + it('returns no error if webhook body is valid', () => { + const result = validateSchema(opennodeWebhookCallbackBodySchema)(validWebhookBody) + expect(result.error).to.be.undefined + }) + + it('returns error if hashed_order is missing', () => { + const body = { ...validWebhookBody } + delete (body as any).hashed_order + const result = validateSchema(opennodeWebhookCallbackBodySchema)(body) + expect(result.error).to.exist + expect(result.error?.issues[0].path).to.deep.equal(['hashed_order']) + }) + + it('returns error if status is not in accepted values', () => { + const body = { + ...validWebhookBody, + status: 'not-a-valid-status', + } + const result = validateSchema(opennodeWebhookCallbackBodySchema)(body) + expect(result.error).to.exist + expect(result.error?.issues[0].path).to.deep.equal(['status']) + }) + }) + describe('opennodeCallbackBodySchema', () => { const validBody = { id: 'some-id', From c337d7af3da2d911b5d89f90c450de652214966a Mon Sep 17 00:00:00 2001 From: anshumancanrock Date: Sat, 18 Apr 2026 22:52:59 +0530 Subject: [PATCH 8/9] test: add opennode callback integration scenarios --- .../callbacks/opennode-callback.feature | 20 +++ .../callbacks/opennode-callback.feature.ts | 133 ++++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100644 test/integration/features/callbacks/opennode-callback.feature create mode 100644 test/integration/features/callbacks/opennode-callback.feature.ts diff --git a/test/integration/features/callbacks/opennode-callback.feature b/test/integration/features/callbacks/opennode-callback.feature new file mode 100644 index 00000000..2fcd79d9 --- /dev/null +++ b/test/integration/features/callbacks/opennode-callback.feature @@ -0,0 +1,20 @@ +@opennode-callback +Feature: OpenNode callback endpoint + Scenario: rejects malformed callback body + Given OpenNode callback processing is enabled + When I post a malformed OpenNode callback + Then the OpenNode callback response status is 400 + And the OpenNode callback response body is "Malformed body" + + Scenario: rejects callback with invalid signature + Given OpenNode callback processing is enabled + When I post an OpenNode callback with an invalid signature + Then the OpenNode callback response status is 403 + And the OpenNode callback response body is "Forbidden" + + Scenario: accepts valid signed callback for pending invoice + Given OpenNode callback processing is enabled + And a pending OpenNode invoice exists + When I post a signed OpenNode callback with status "processing" + Then the OpenNode callback response status is 200 + And the OpenNode callback response body is empty diff --git a/test/integration/features/callbacks/opennode-callback.feature.ts b/test/integration/features/callbacks/opennode-callback.feature.ts new file mode 100644 index 00000000..94ac7b29 --- /dev/null +++ b/test/integration/features/callbacks/opennode-callback.feature.ts @@ -0,0 +1,133 @@ +import { After, Given, Then, When } from '@cucumber/cucumber' +import axios, { AxiosResponse } from 'axios' +import { expect } from 'chai' +import { randomUUID } from 'crypto' + +import { getMasterDbClient } from '../../../../src/database/client' +import { hmacSha256 } from '../../../../src/utils/secret' +import { SettingsStatic } from '../../../../src/utils/settings' + +const CALLBACK_URL = 'http://localhost:18808/callbacks/opennode' +const OPENNODE_TEST_API_KEY = 'integration-opennode-api-key' +const TEST_PUBKEY = 'a'.repeat(64) + +const postOpenNodeCallback = async (body: Record) => { + const encodedBody = new URLSearchParams(body).toString() + + return axios.post( + CALLBACK_URL, + encodedBody, + { + headers: { + 'content-type': 'application/x-www-form-urlencoded', + }, + validateStatus: () => true, + }, + ) +} + +Given('OpenNode callback processing is enabled', function () { + const settings = SettingsStatic._settings as any + + this.parameters.previousOpenNodeCallbackSettings = settings + this.parameters.previousOpenNodeApiKey = process.env.OPENNODE_API_KEY + + SettingsStatic._settings = { + ...settings, + payments: { + ...(settings?.payments ?? {}), + processor: 'opennode', + }, + } + + process.env.OPENNODE_API_KEY = OPENNODE_TEST_API_KEY +}) + +Given('a pending OpenNode invoice exists', async function () { + const dbClient = getMasterDbClient() + const invoiceId = `integration-opennode-${randomUUID()}` + + await dbClient('invoices').insert({ + id: invoiceId, + pubkey: Buffer.from(TEST_PUBKEY, 'hex'), + bolt11: 'lnbc210n1integration', + amount_requested: '21000', + unit: 'sats', + status: 'pending', + description: 'open node integration callback test', + expires_at: new Date(Date.now() + 15 * 60 * 1000), + updated_at: new Date(), + created_at: new Date(), + }) + + this.parameters.openNodeInvoiceId = invoiceId + this.parameters.openNodeInvoiceIds = [ + ...(this.parameters.openNodeInvoiceIds ?? []), + invoiceId, + ] +}) + +When('I post a malformed OpenNode callback', async function () { + this.parameters.openNodeResponse = await postOpenNodeCallback({ + id: 'missing-required-fields', + }) +}) + +When('I post an OpenNode callback with an invalid signature', async function () { + this.parameters.openNodeResponse = await postOpenNodeCallback({ + hashed_order: '0'.repeat(64), + id: `integration-opennode-${randomUUID()}`, + status: 'paid', + }) +}) + +When('I post a signed OpenNode callback with status {string}', async function (status: string) { + const id = this.parameters.openNodeInvoiceId + const hashedOrder = hmacSha256(OPENNODE_TEST_API_KEY, id).toString('hex') + + this.parameters.openNodeResponse = await postOpenNodeCallback({ + hashed_order: hashedOrder, + id, + status, + }) +}) + +Then('the OpenNode callback response status is {int}', function (statusCode: number) { + const response = this.parameters.openNodeResponse as AxiosResponse + + expect(response.status).to.equal(statusCode) +}) + +Then('the OpenNode callback response body is {string}', function (expectedBody: string) { + const response = this.parameters.openNodeResponse as AxiosResponse + + expect(response.data).to.equal(expectedBody) +}) + +Then('the OpenNode callback response body is empty', function () { + const response = this.parameters.openNodeResponse as AxiosResponse + + expect(['', undefined, null]).to.include(response.data) +}) + +After({ tags: '@opennode-callback' }, async function () { + SettingsStatic._settings = this.parameters.previousOpenNodeCallbackSettings + + if (typeof this.parameters.previousOpenNodeApiKey === 'undefined') { + delete process.env.OPENNODE_API_KEY + } else { + process.env.OPENNODE_API_KEY = this.parameters.previousOpenNodeApiKey + } + + const invoiceIds = this.parameters.openNodeInvoiceIds ?? [] + if (invoiceIds.length > 0) { + const dbClient = getMasterDbClient() + await dbClient('invoices').whereIn('id', invoiceIds).delete() + } + + this.parameters.openNodeInvoiceId = undefined + this.parameters.openNodeInvoiceIds = [] + this.parameters.openNodeResponse = undefined + this.parameters.previousOpenNodeApiKey = undefined + this.parameters.previousOpenNodeCallbackSettings = undefined +}) From cda190a874ff49588fd27f8a1c9c7a1d0a22b371 Mon Sep 17 00:00:00 2001 From: anshumancanrock Date: Sat, 18 Apr 2026 22:57:56 +0530 Subject: [PATCH 9/9] test: verify paid opennode callback completes invoice --- .../features/callbacks/opennode-callback.feature | 8 ++++++++ .../callbacks/opennode-callback.feature.ts | 14 ++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/test/integration/features/callbacks/opennode-callback.feature b/test/integration/features/callbacks/opennode-callback.feature index 2fcd79d9..2b6b3ffa 100644 --- a/test/integration/features/callbacks/opennode-callback.feature +++ b/test/integration/features/callbacks/opennode-callback.feature @@ -18,3 +18,11 @@ Feature: OpenNode callback endpoint When I post a signed OpenNode callback with status "processing" Then the OpenNode callback response status is 200 And the OpenNode callback response body is empty + + Scenario: completes a pending invoice on paid callback + Given OpenNode callback processing is enabled + And a pending OpenNode invoice exists + When I post a signed OpenNode callback with status "paid" + Then the OpenNode callback response status is 200 + And the OpenNode callback response body is "OK" + And the OpenNode invoice is marked completed diff --git a/test/integration/features/callbacks/opennode-callback.feature.ts b/test/integration/features/callbacks/opennode-callback.feature.ts index 94ac7b29..0678e580 100644 --- a/test/integration/features/callbacks/opennode-callback.feature.ts +++ b/test/integration/features/callbacks/opennode-callback.feature.ts @@ -110,6 +110,20 @@ Then('the OpenNode callback response body is empty', function () { expect(['', undefined, null]).to.include(response.data) }) +Then('the OpenNode invoice is marked completed', async function () { + const dbClient = getMasterDbClient() + const invoiceId = this.parameters.openNodeInvoiceId + + const invoice = await dbClient('invoices') + .where('id', invoiceId) + .first('status', 'confirmed_at', 'amount_paid') + + expect(invoice).to.exist + expect(invoice.status).to.equal('completed') + expect(invoice.confirmed_at).to.not.equal(null) + expect(invoice.amount_paid).to.equal('21000') +}) + After({ tags: '@opennode-callback' }, async function () { SettingsStatic._settings = this.parameters.previousOpenNodeCallbackSettings