#!/usr/bin/env node // BTCPay webhook recovery example: one synthetic settled invoice, many deliveries, // exactly one fulfillment record. // // node recovery_example.mjs # Node 18+, no dependencies, no network // // Everything runs locally. The "BTCPay" side is a stub that signs webhooks with a // throwaway test secret and serves a synthetic invoice. Nothing here touches a // wallet, a real store, or a payment. A locally generated signature proves only // this test path, not an original BTCPay delivery or settlement. // // Pattern follows https://loopxxi.com/journal/btcpay-webhook-recovery: // verify BTCPay-Sig over raw bytes -> durably accept -> 2xx // -> reread invoice via authenticated API -> enter ONE fulfillment guard // keyed by (store, invoice, action), shared by every event type, // redelivery and reconciliation job. import http from "node:http"; import crypto from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; const TEST_SECRET = crypto.randomBytes(32).toString("hex"); // throwaway, never a real secret const STORE_ID = "store_synthetic"; const INVOICE_ID = "inv_synthetic_0001"; const ORDER_ID = "order-42"; const ACTION = "deliver-order"; // Durable state lives in a temp dir so a rerun starts clean; pass KEEP=1 to inspect it. const DATA = fs.mkdtempSync(path.join(os.tmpdir(), "btcpay-recovery-")); const INBOX = path.join(DATA, "inbox"); // accepted events, one file per deliveryId const FULFILL = path.join(DATA, "fulfillments"); // one file per fulfillment key fs.mkdirSync(INBOX); fs.mkdirSync(FULFILL); // ---------- Stub BTCPay: synthetic invoice read (Greenfield-shaped subset) ---------- const invoices = { [INVOICE_ID]: { id: INVOICE_ID, storeId: STORE_ID, status: "Settled", additionalStatus: "None", amount: "1234", currency: "SATS", metadata: { orderId: ORDER_ID } }, inv_marked: { id: "inv_marked", storeId: STORE_ID, status: "Settled", additionalStatus: "Marked", amount: "1234", currency: "SATS", metadata: { orderId: "order-marked" } }, inv_unpaid: { id: "inv_unpaid", storeId: STORE_ID, status: "New", additionalStatus: "None", amount: "1234", currency: "SATS", metadata: { orderId: "order-unpaid" } }, inv_expired: { id: "inv_expired", storeId: STORE_ID, status: "Expired", additionalStatus: "None", amount: "1234", currency: "SATS", metadata: { orderId: "order-expired" } }, }; async function readInvoice(storeId, invoiceId) { // Real code: GET /api/v1/stores/{storeId}/invoices/{invoiceId} // with a key holding btcpay.store.canviewinvoices. const inv = invoices[invoiceId]; if (!inv || inv.storeId !== storeId) throw new Error(`invoice ${invoiceId} not found`); return structuredClone(inv); } // ---------- Downstream delivery system (counts real side effects) ---------- const downstreamCalls = []; async function deliverOrder(orderId, idempotencyKey) { downstreamCalls.push({ orderId, idempotencyKey }); return { delivered: true, orderId }; } // ---------- Handler: verify, accept, ack ---------- function verifySig(raw, header) { if (typeof header !== "string" || !/^sha256=[0-9a-f]{64}$/.test(header)) return false; const expected = Buffer.from(crypto.createHmac("sha256", TEST_SECRET).update(raw).digest("hex")); const got = Buffer.from(header.slice(7)); return got.length === expected.length && crypto.timingSafeEqual(got, expected); } const server = http.createServer((req, res) => { const chunks = []; req.on("data", (c) => chunks.push(c)); req.on("end", () => { const raw = Buffer.concat(chunks); // exact bytes; never reserialize before verifying if (!verifySig(raw, req.headers["btcpay-sig"])) { res.writeHead(401).end("bad signature"); return; } let evt; try { evt = JSON.parse(raw); } catch { res.writeHead(400).end("bad json"); return; } try { // Durable acceptance before 2xx. Same deliveryId twice is a no-op. fs.writeFileSync(path.join(INBOX, `${evt.deliveryId}.json`), raw, { flag: "wx" }); } catch (e) { if (e.code !== "EEXIST") { res.writeHead(500).end("not stored"); return; } // never a false 2xx } res.writeHead(200).end("accepted"); queueMicrotask(() => processEvent(evt).catch((e) => console.error("process error:", e.message))); }); }); // ---------- The one fulfillment guard ---------- const pending = []; function processEvent(evt) { const p = fulfill(evt.storeId, evt.invoiceId, `webhook:${evt.type}:${evt.deliveryId}`); pending.push(p); return p; } async function fulfill(storeId, invoiceId, source) { // The event is only a trigger: reread the invoice before deciding. const inv = await readInvoice(storeId, invoiceId); if (inv.status !== "Settled" || inv.additionalStatus === "Marked") { return { source, outcome: `skipped (status ${inv.status}/${inv.additionalStatus})` }; } const key = `${storeId}__${invoiceId}__${ACTION}`; const file = path.join(FULFILL, `${key}.json`); // Atomic claim: exclusive create. Concurrent workers lose with EEXIST. let fd; try { fd = fs.openSync(file, "wx"); } catch (e) { if (e.code === "EEXIST") return { source, outcome: "duplicate (already claimed)" }; throw e; } fs.writeSync(fd, JSON.stringify({ key, invoiceId, orderId: inv.metadata.orderId, state: "claimed", source })); fs.closeSync(fd); const result = await deliverOrder(inv.metadata.orderId, key); // stable idempotency key downstream fs.writeFileSync(file, JSON.stringify({ key, invoiceId, orderId: inv.metadata.orderId, state: "completed", source, result, completedAt: new Date().toISOString() })); return { source, outcome: "FULFILLED" }; } // ---------- Stub BTCPay sender ---------- let port; async function send(body, { sig } = {}) { const raw = Buffer.from(JSON.stringify(body)); const header = sig ?? `sha256=${crypto.createHmac("sha256", TEST_SECRET).update(raw).digest("hex")}`; const r = await fetch(`http://127.0.0.1:${port}/webhook`, { method: "POST", headers: { "content-type": "application/json", "btcpay-sig": header }, body: raw, }); return r.status; } const evt = (type, deliveryId, extra = {}) => ({ deliveryId, webhookId: "wh_synthetic", originalDeliveryId: extra.originalDeliveryId ?? deliveryId, isRedelivery: !!extra.isRedelivery, type, timestamp: 1795034911, storeId: STORE_ID, invoiceId: extra.invoiceId ?? INVOICE_ID, }); async function main() { await new Promise((r) => server.listen(0, "127.0.0.1", r)); port = server.address().port; console.log(`staging handler on 127.0.0.1:${port}, data in ${DATA}`); const steps = [ ["1. InvoicePaymentSettled", () => send(evt("InvoicePaymentSettled", "d1"))], ["2. InvoiceSettled, same invoice", () => send(evt("InvoiceSettled", "d2"))], ["3. same delivery d2 retried", () => send(evt("InvoiceSettled", "d2"))], ["4. redelivery (new id, isRedelivery)", () => send(evt("InvoiceSettled", "d3", { originalDeliveryId: "d2", isRedelivery: true }))], ["5. 5 concurrent redeliveries", () => Promise.all([4, 5, 6, 7, 8].map((n) => send(evt("InvoiceSettled", `d${n}`, { originalDeliveryId: "d2", isRedelivery: true })))).then((s) => s.join(","))], ["6. forged signature", () => send(evt("InvoiceSettled", "d9"), { sig: "sha256=" + "0".repeat(64) })], ["7. Marked invoice (not paid proof)", () => send(evt("InvoiceSettled", "d10", { invoiceId: "inv_marked" }))], ["7b. unpaid (New) invoice", () => send(evt("InvoiceReceivedPayment", "d11", { invoiceId: "inv_unpaid" }))], ["7c. unpaid Expired invoice" , () => send(evt("InvoiceExpired", "d12", { invoiceId: "inv_expired" }))], ]; for (const [label, fn] of steps) console.log(`${label}: HTTP ${await fn()}`); // 8. Reconciliation job enters the same guard without a signed webhook. pending.push(fulfill(STORE_ID, INVOICE_ID, "reconcile:scheduled")); const outcomes = await Promise.all(pending); console.log("8. reconciliation job: entered same guard"); for (const o of outcomes) console.log(` ${o.source} -> ${o.outcome}`); server.close(); // ---------- Acceptance check ---------- const records = fs.readdirSync(FULFILL).map((f) => JSON.parse(fs.readFileSync(path.join(FULFILL, f)))); const forInvoice = records.filter((r) => r.invoiceId === INVOICE_ID); const checks = [ ["exactly one fulfillment record for the invoice", forInvoice.length === 1], ["that record is completed", forInvoice[0]?.state === "completed"], ["downstream delivery called exactly once", downstreamCalls.filter((c) => c.orderId === ORDER_ID).length === 1], ["forged signature not accepted", !fs.existsSync(path.join(INBOX, "d9.json"))], ["Marked invoice not fulfilled", records.every((r) => r.invoiceId !== "inv_marked")], ["unsettled invoices (New, Expired) produce zero records", records.every((r) => !["inv_unpaid", "inv_expired"].includes(r.invoiceId))], ["unsettled orders get zero downstream calls", downstreamCalls.every((c) => !["order-unpaid", "order-expired"].includes(c.orderId))], ]; console.log("\nacceptance:"); for (const [name, ok] of checks) console.log(` ${ok ? "PASS" : "FAIL"} ${name}`); const pass = checks.every(([, ok]) => ok); console.log(`\nfulfillment record: ${JSON.stringify(forInvoice[0])}`); if (!process.env.KEEP) fs.rmSync(DATA, { recursive: true, force: true }); console.log(pass ? `done: ${checks.length}/${checks.length} checks passed` : "FAILED"); process.exit(pass ? 0 : 1); } main().catch((e) => { console.error(`FAILED: ${e.message}`); server.close(); process.exit(1); });