Skip to content

Commit 8748958

Browse files
Perloverclaude
andcommitted
fix(payments): accept the webhook body LNbits >= 1.0 sends
LNbits >= 1.0 posts the payment webhook with `json=payment.json()` (`model_dump_json()` on current main): the payment is serialized and then JSON-encoded a second time, so the request body is a JSON string holding the payment object. The /callbacks/lnbits route used the default strict `json()` parser, which rejects a top-level string with 400 before the controller runs. Even an object body would have been rejected: the body schema was `.strict()` with only `payment_hash`, while LNbits always sends its whole payment object. Every webhook failed, and paid invoices were only confirmed by the maintenance worker on its next 60 s poll; users kept waiting on the invoice page after paying, and some paid a second invoice. Parse the body with `strict: false`, decode a JSON string body in the controller, and validate only `payment_hash`, stripping the other fields. The invoice state is still fetched from LNbits and the query hmac is still required, so nothing from the body is trusted beyond the hash. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 87bc6c8 commit 8748958

7 files changed

Lines changed: 182 additions & 14 deletions

File tree

‎.changeset/lnbits-webhook-body.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"nostream": patch
3+
---
4+
5+
fix(payments): accept the webhook body LNbits >= 1.0 sends, so paid invoices are confirmed right away instead of on the next 60 s maintenance poll

‎src/controllers/callbacks/lnbits-callback-controller.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,21 @@ import { validateSchema } from '../../utils/validation'
1313

1414
const logger = createLogger('lnbits-callback-controller')
1515

16+
// LNbits >= 1.0 sends the webhook with `json=payment.json()`, which JSON-encodes the
17+
// already serialized payment a second time: the body is a JSON string that holds the
18+
// payment object. Older LNbits sends the object itself. Accept both.
19+
const decodeLNbitsCallbackBody = (body: unknown): unknown => {
20+
if (typeof body !== 'string') {
21+
return body
22+
}
23+
24+
try {
25+
return JSON.parse(body)
26+
} catch {
27+
return undefined
28+
}
29+
}
30+
1631
export class LNbitsCallbackController implements IController {
1732
public constructor(
1833
private readonly paymentsService: IPaymentsService,
@@ -50,15 +65,15 @@ export class LNbitsCallbackController implements IController {
5065
return
5166
}
5267

53-
const bodyValidation = validateSchema(lnbitsCallbackBodySchema)(request.body)
68+
const bodyValidation = validateSchema(lnbitsCallbackBodySchema)(decodeLNbitsCallbackBody(request.body))
5469
if (bodyValidation.error) {
5570
response.status(400).setHeader('content-type', 'text/plain; charset=utf8').send('Malformed body')
5671
return
5772
}
5873

59-
const body = request.body
60-
const invoice = await this.paymentsService.getInvoiceFromPaymentsProcessor(body.payment_hash)
61-
const storedInvoice = await this.invoiceRepository.findById(body.payment_hash)
74+
const paymentHash: string = bodyValidation.value.payment_hash
75+
const invoice = await this.paymentsService.getInvoiceFromPaymentsProcessor(paymentHash)
76+
const storedInvoice = await this.invoiceRepository.findById(paymentHash)
6277

6378
if (!storedInvoice) {
6479
response.status(404).setHeader('content-type', 'text/plain; charset=utf8').send('No such invoice')

‎src/routes/callbacks/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ const requireProcessor = (name: string) =>
2121

2222
router
2323
.post('/zebedee', requireProcessor('zebedee'), json(), withController(createZebedeeCallbackController))
24-
.post('/lnbits', requireProcessor('lnbits'), json(), withController(createLNbitsCallbackController))
24+
// strict: false — LNbits >= 1.0 posts a JSON string (the payment JSON-encoded twice),
25+
// which the default strict parser rejects with 400 before the controller runs.
26+
.post('/lnbits', requireProcessor('lnbits'), json({ strict: false }), withController(createLNbitsCallbackController))
2527
.post('/opennode', requireProcessor('opennode'), urlencoded({ extended: false }), json(), withController(createOpenNodeCallbackController))
2628
.post(
2729
'/nodeless',

‎src/schemas/lnbits-callback-schema.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ export const lnbitsCallbackQuerySchema = z
77
})
88
.strict()
99

10-
export const lnbitsCallbackBodySchema = z
11-
.object({
12-
payment_hash: idSchema,
13-
})
14-
.strict()
10+
// LNbits posts its whole payment object (checking_id, amount, bolt11, status, ...).
11+
// Only payment_hash is used; the invoice state is fetched from LNbits itself, so the
12+
// other fields are stripped rather than rejected.
13+
export const lnbitsCallbackBodySchema = z.object({
14+
payment_hash: idSchema,
15+
})

‎test/unit/controllers/callbacks/lnbits-callback-controller.spec.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,32 @@ const makeValidQuery = (expiry = VALID_HMAC_EXPIRY) => {
6868
return { hmac: `${expiryString}:${signature}` }
6969
}
7070

71+
// The payment object LNbits >= 1.0 posts to the webhook (lnbits.core.models.Payment)
72+
const makeLNbitsPayment = () => ({
73+
checking_id: PAYMENT_HASH,
74+
payment_hash: PAYMENT_HASH,
75+
wallet_id: 'c'.repeat(32),
76+
amount: 21000,
77+
fee: 0,
78+
bolt11: 'lnbc210n1test',
79+
payment_request: 'lnbc210n1test',
80+
fiat_provider: null,
81+
status: 'success',
82+
memo: 'test invoice',
83+
expiry: '2030-01-02T00:00:00+00:00',
84+
webhook: 'https://relay.example.com/callbacks/lnbits?hmac=1:abc',
85+
webhook_status: null,
86+
preimage: 'd'.repeat(64),
87+
tag: null,
88+
extension: null,
89+
time: '2030-01-01T00:00:00+00:00',
90+
created_at: '2030-01-01T00:00:00+00:00',
91+
updated_at: '2030-01-01T00:00:05+00:00',
92+
labels: [],
93+
extra: {},
94+
external_id: null,
95+
})
96+
7197
const makeReq = (overrides: any = {}): any => ({
7298
headers: {},
7399
query: makeValidQuery(),
@@ -162,6 +188,55 @@ describe('LNbitsCallbackController', () => {
162188
expect(res.setHeader).to.have.been.calledWith('content-type', 'text/plain; charset=utf8')
163189
expect(res.send).to.have.been.calledWith('Malformed body')
164190
})
191+
192+
it('returns 400 for a string body that is not JSON', async () => {
193+
const { controller, paymentsService } = makeController()
194+
const res = makeRes()
195+
196+
await controller.handleRequest(makeReq({ body: 'not json' }), res)
197+
198+
expect(res.status).to.have.been.calledWith(400)
199+
expect(res.send).to.have.been.calledWith('Malformed body')
200+
expect(paymentsService.getInvoiceFromPaymentsProcessor).to.not.have.been.called
201+
})
202+
203+
it('returns 400 for a JSON string body without a valid payment_hash', async () => {
204+
const { controller, paymentsService } = makeController()
205+
const res = makeRes()
206+
207+
await controller.handleRequest(makeReq({ body: JSON.stringify({ payment_hash: 'abc' }) }), res)
208+
209+
expect(res.status).to.have.been.calledWith(400)
210+
expect(res.send).to.have.been.calledWith('Malformed body')
211+
expect(paymentsService.getInvoiceFromPaymentsProcessor).to.not.have.been.called
212+
})
213+
})
214+
215+
describe('LNbits payload formats', () => {
216+
it('confirms an invoice when LNbits >= 1.0 posts the payment as a JSON string', async () => {
217+
const { controller, paymentsService, invoiceRepository } = makeController()
218+
const res = makeRes()
219+
220+
await controller.handleRequest(makeReq({ body: JSON.stringify(makeLNbitsPayment()) }), res)
221+
222+
expect(paymentsService.getInvoiceFromPaymentsProcessor).to.have.been.calledOnceWithExactly(PAYMENT_HASH)
223+
expect(invoiceRepository.findById).to.have.been.calledOnceWithExactly(PAYMENT_HASH)
224+
expect(paymentsService.confirmInvoice).to.have.been.calledOnce
225+
expect(res.status).to.have.been.calledWith(200)
226+
expect(res.send).to.have.been.calledWith('OK')
227+
})
228+
229+
it('confirms an invoice when the whole payment object is posted', async () => {
230+
const { controller, paymentsService } = makeController()
231+
const res = makeRes()
232+
233+
await controller.handleRequest(makeReq({ body: makeLNbitsPayment() }), res)
234+
235+
expect(paymentsService.getInvoiceFromPaymentsProcessor).to.have.been.calledOnceWithExactly(PAYMENT_HASH)
236+
expect(paymentsService.confirmInvoice).to.have.been.calledOnce
237+
expect(res.status).to.have.been.calledWith(200)
238+
expect(res.send).to.have.been.calledWith('OK')
239+
})
165240
})
166241

167242
describe('invoice state handling', () => {

‎test/unit/routes/callbacks.spec.ts‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,28 @@ import { expect } from 'chai'
33
import express from 'express'
44
import Sinon from 'sinon'
55

6+
import * as lnbitsControllerFactory from '../../../src/factories/controllers/lnbits-callback-controller-factory'
67
import * as openNodeControllerFactory from '../../../src/factories/controllers/opennode-callback-controller-factory'
78
import * as settingsFactory from '../../../src/factories/settings-factory'
89

910
describe('callbacks router', () => {
11+
let createLNbitsCallbackControllerStub: Sinon.SinonStub
1012
let createOpenNodeCallbackControllerStub: Sinon.SinonStub
1113
let createSettingsStub: Sinon.SinonStub
1214
let receivedBody: unknown
15+
let processor: string
1316
let server: any
1417

1518
beforeEach(async () => {
1619
receivedBody = undefined
20+
processor = 'opennode'
1721

18-
createSettingsStub = Sinon.stub(settingsFactory, 'createSettings').returns({
19-
payments: { enabled: true, processor: 'opennode' },
20-
} as any)
22+
createSettingsStub = Sinon.stub(settingsFactory, 'createSettings').callsFake(
23+
() =>
24+
({
25+
payments: { enabled: true, processor },
26+
}) as any,
27+
)
2128

2229
createOpenNodeCallbackControllerStub = Sinon.stub(openNodeControllerFactory, 'createOpenNodeCallbackController').returns({
2330
handleRequest: async (request: any, response: any) => {
@@ -26,6 +33,13 @@ describe('callbacks router', () => {
2633
},
2734
} as any)
2835

36+
createLNbitsCallbackControllerStub = Sinon.stub(lnbitsControllerFactory, 'createLNbitsCallbackController').returns({
37+
handleRequest: async (request: any, response: any) => {
38+
receivedBody = request.body
39+
response.status(200).send('OK')
40+
},
41+
} as any)
42+
2943
// eslint-disable-next-line @typescript-eslint/no-var-requires
3044
delete require.cache[require.resolve('../../../src/routes/callbacks')]
3145
// eslint-disable-next-line @typescript-eslint/no-var-requires
@@ -40,6 +54,7 @@ describe('callbacks router', () => {
4054
})
4155

4256
afterEach(async () => {
57+
createLNbitsCallbackControllerStub.restore()
4358
createOpenNodeCallbackControllerStub.restore()
4459
createSettingsStub.restore()
4560
delete require.cache[require.resolve('../../../src/routes/callbacks')]
@@ -84,4 +99,35 @@ describe('callbacks router', () => {
8499
status: 'paid',
85100
})
86101
})
87-
})
102+
103+
it('passes the JSON string body LNbits >= 1.0 posts through to the controller', async () => {
104+
processor = 'lnbits'
105+
const { port } = server.address()
106+
const payment = JSON.stringify({ checking_id: 'a'.repeat(64), payment_hash: 'a'.repeat(64), amount: 21000 })
107+
108+
// LNbits >= 1.0 sends `json=payment.json()`: the serialized payment JSON-encoded again
109+
const response = await axios.post(`http://127.0.0.1:${port}/lnbits`, JSON.stringify(payment), {
110+
headers: {
111+
'content-type': 'application/json',
112+
},
113+
validateStatus: () => true,
114+
})
115+
116+
expect(response.status).to.equal(200)
117+
expect(receivedBody).to.equal(payment)
118+
})
119+
120+
it('parses the LNbits payment object as JSON', async () => {
121+
processor = 'lnbits'
122+
const { port } = server.address()
123+
124+
const response = await axios.post(
125+
`http://127.0.0.1:${port}/lnbits`,
126+
{ payment_hash: 'a'.repeat(64), amount: 21000 },
127+
{ validateStatus: () => true },
128+
)
129+
130+
expect(response.status).to.equal(200)
131+
expect(receivedBody).to.deep.equal({ payment_hash: 'a'.repeat(64), amount: 21000 })
132+
})
133+
})

‎test/unit/schemas/lnbits-callback-schema.spec.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,30 @@ describe('LNbits Callback Schema', () => {
3131
expect(result.error).to.be.undefined
3232
})
3333

34+
it('accepts the whole LNbits payment object and keeps only payment_hash', () => {
35+
const paymentHash = 'fa4dd948576fe182f5d0e3120b9df42c83dffa1c884754d5e4d3b0a2f98a01c5'
36+
const body = {
37+
checking_id: paymentHash,
38+
payment_hash: paymentHash,
39+
wallet_id: 'c'.repeat(32),
40+
amount: 21000,
41+
fee: 0,
42+
bolt11: 'lnbc210n1test',
43+
status: 'success',
44+
time: '2030-01-01T00:00:00+00:00',
45+
extra: {},
46+
}
47+
const result = validateSchema(lnbitsCallbackBodySchema)(body)
48+
expect(result.error).to.be.undefined
49+
expect(result.value).to.deep.equal({ payment_hash: paymentHash })
50+
})
51+
52+
it('returns error if payment_hash is missing', () => {
53+
const result = validateSchema(lnbitsCallbackBodySchema)({ checking_id: 'abc' })
54+
expect(result.error).to.exist
55+
expect(result.error?.issues[0].path).to.deep.equal(['payment_hash'])
56+
})
57+
3458
it('returns error if payment_hash is not 64 chars hex', () => {
3559
const result = validateSchema(lnbitsCallbackBodySchema)({ payment_hash: 'abc' })
3660
expect(result.error).to.exist

0 commit comments

Comments
 (0)