| 1 | /** |
| 2 | * Answering HBank's callback: right before charging a customer, HBank POSTs the payment to its `callback_url` and |
| 3 | * charges only if you answer 200 with `{"resume": true}` as application/json within 10 seconds. |
| 4 | * |
| 5 | * It's signed: check the `HBank-Signature` header with your business's signing secret (business settings → Callback |
| 6 | * URLs) before you approve: `verifySignature`, or pass `{ secret }` to the handlers below. Also check that `id` and |
| 7 | * `amount` match an order you created, and confirm with `getPayment` before handing out goods. |
| 8 | */ |
| 9 | import { HBankError } from "./errors.js"; |
| 10 | |
| 11 | export interface Callback { |
| 12 | /** The transaction id you got from createPayment: a random string like "tx_8fK2mQ7xRb4Tn9WcYz3LpH6v". */ |
| 13 | id: string; |
| 14 | amount: number; |
| 15 | currency: string; |
| 16 | status: string; |
| 17 | description: string; |
| 18 | } |
| 19 | |
| 20 | export type CallbackAnswer = { resume: true } | { resume: false; error?: string }; |
| 21 | |
| 22 | /** What your handler decides: `true` to charge, `false` or a string (shown to the customer) to refuse. */ |
| 23 | export type CallbackDecision = boolean | string | CallbackAnswer; |
| 24 | export type CallbackDecider = (callback: Callback) => CallbackDecision | Promise<CallbackDecision>; |
| 25 | |
| 26 | /** Reads a callback body (parsed JSON or the raw text). Throws HBankError("invalid_callback") if it isn't one. */ |
| 27 | export function parseCallback(body: unknown): Callback { |
| 28 | let data = body; |
| 29 | if (typeof data === "string") { |
| 30 | try { |
| 31 | data = JSON.parse(data); |
| 32 | } catch { |
| 33 | throw new HBankError("invalid_callback", undefined, "body is not JSON"); |
| 34 | } |
| 35 | } |
| 36 | const d = data as Record<string, unknown> | null; |
| 37 | const id = typeof d?.id === "string" || typeof d?.id === "number" ? String(d.id) : ""; |
| 38 | const amount = Number(d?.amount); |
| 39 | if (!d || typeof d !== "object" || id === "" || !Number.isFinite(amount) || typeof d.currency !== "string") |
| 40 | throw new HBankError("invalid_callback", undefined, "missing or invalid id, amount or currency"); |
| 41 | return { id, amount, currency: d.currency, status: String(d.status ?? ""), description: String(d.description ?? "") }; |
| 42 | } |
| 43 | |
| 44 | export interface VerifyOptions { |
| 45 | /** How old the signature may be, in seconds (default 300). */ |
| 46 | toleranceSeconds?: number; |
| 47 | /** "Now" in Unix seconds (for tests). */ |
| 48 | now?: number; |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Whether `header` (the request's `HBank-Signature`: `t=<unix time>,v1=<hex>`) signs `body` (the raw request body, |
| 53 | * exactly as received) with `secret`, and isn't older than the tolerance. Uses Web Crypto, so it works in Node 18+, |
| 54 | * Deno, Bun, Workers and browsers alike. |
| 55 | */ |
| 56 | export async function verifySignature(secret: string, header: string | null | undefined, body: string | Uint8Array, options: VerifyOptions = {}): Promise<boolean> { |
| 57 | if (!secret || !header) return false; |
| 58 | const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)).filter((p) => p.length === 2)); |
| 59 | const t = Number(parts.t); |
| 60 | if (!/^\d+$/.test(parts.t ?? "") || !Number.isSafeInteger(t)) return false; |
| 61 | const now = options.now ?? Math.floor(Date.now() / 1000); |
| 62 | if (Math.abs(now - t) > (options.toleranceSeconds ?? 300)) return false; |
| 63 | const encoder = new TextEncoder(); |
| 64 | const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); |
| 65 | const raw = typeof body === "string" ? encoder.encode(body) : body; |
| 66 | const signed = new Uint8Array(raw.length + String(t).length + 1); |
| 67 | signed.set(encoder.encode(`${t}.`)); |
| 68 | signed.set(raw, String(t).length + 1); |
| 69 | const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, signed)); |
| 70 | const expected = Array.from(mac, (b) => b.toString(16).padStart(2, "0")).join(""); |
| 71 | const given = String(parts.v1 ?? ""); |
| 72 | // Constant time: every character is compared. |
| 73 | let diff = given.length ^ expected.length; |
| 74 | for (let i = 0; i < expected.length; i++) diff |= expected.charCodeAt(i) ^ given.charCodeAt(i); |
| 75 | return diff === 0; |
| 76 | } |
| 77 | |
| 78 | /** Options for the ready-made handlers. */ |
| 79 | export interface HandlerOptions { |
| 80 | /** Your signing secret: callbacks without a valid HBank-Signature are refused ("Invalid callback"). */ |
| 81 | secret?: string; |
| 82 | } |
| 83 | |
| 84 | /** The answer that lets HBank charge the customer. */ |
| 85 | export const approve = (): CallbackAnswer => ({ resume: true }); |
| 86 | |
| 87 | /** The answer that refuses the payment; the customer sees `error`. */ |
| 88 | export const refuse = (error?: string): CallbackAnswer => (error ? { resume: false, error } : { resume: false }); |
| 89 | |
| 90 | function answerFor(decision: CallbackDecision): CallbackAnswer { |
| 91 | if (decision === true) return approve(); |
| 92 | if (decision === false) return refuse(); |
| 93 | if (typeof decision === "string") return refuse(decision); |
| 94 | return decision; |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * A callback endpoint for frameworks built on the Fetch API's Request/Response: Next.js route handlers, Hono, Remix, |
| 99 | * SvelteKit, Astro, Bun, Deno, Cloudflare Workers. |
| 100 | * |
| 101 | * ```ts |
| 102 | * // app/hbank/callback/route.ts (Next.js) |
| 103 | * export const POST = callbackHandler(async (cb) => { |
| 104 | * const order = await db.orders.findByTransaction(cb.id); |
| 105 | * return order && order.total === cb.amount ? true : "This order is no longer available"; |
| 106 | * }); |
| 107 | * ``` |
| 108 | */ |
| 109 | export function callbackHandler(decide: CallbackDecider, options: HandlerOptions = {}): (request: Request) => Promise<Response> { |
| 110 | return async (request) => { |
| 111 | let answer: CallbackAnswer; |
| 112 | try { |
| 113 | const raw = await request.text(); |
| 114 | if (options.secret !== undefined && !(await verifySignature(options.secret, request.headers.get("HBank-Signature"), raw))) |
| 115 | throw new HBankError("invalid_callback", undefined, "bad or missing HBank-Signature"); |
| 116 | answer = answerFor(await decide(parseCallback(raw))); |
| 117 | } catch (e) { |
| 118 | answer = refuse(e instanceof HBankError && e.code === "invalid_callback" ? "Invalid callback" : "The shop couldn't confirm this order"); |
| 119 | } |
| 120 | return new Response(JSON.stringify(answer), { status: 200, headers: { "Content-Type": "application/json" } }); |
| 121 | }; |
| 122 | } |
| 123 | |
| 124 | interface ExpressLikeRequest { body?: unknown; rawBody?: string | Uint8Array; get?(name: string): string | undefined; headers?: Record<string, unknown> } |
| 125 | interface ExpressLikeResponse { status(code: number): ExpressLikeResponse; json(body: unknown): unknown } |
| 126 | |
| 127 | /** |
| 128 | * A callback endpoint for Express (and Express-style frameworks: Fastify via `reply`, Koa adapters aside). |
| 129 | * Needs a JSON body parser, e.g. `app.use(express.json())`. With `{ secret }`, the signature is checked against the raw |
| 130 | * body, so keep it: `express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })`. |
| 131 | * |
| 132 | * ```ts |
| 133 | * const json = express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } }); |
| 134 | * app.post("/hbank/callback", json, expressCallback(async (cb) => orders.matches(cb.id, cb.amount), { secret: process.env.HBANK_CALLBACK_SECRET })); |
| 135 | * ``` |
| 136 | */ |
| 137 | export function expressCallback(decide: CallbackDecider, options: HandlerOptions = {}) { |
| 138 | return async (req: ExpressLikeRequest, res: ExpressLikeResponse): Promise<void> => { |
| 139 | let answer: CallbackAnswer; |
| 140 | try { |
| 141 | if (options.secret !== undefined) { |
| 142 | const header = req.get?.("HBank-Signature") ?? (req.headers?.["hbank-signature"] as string | undefined); |
| 143 | if (req.rawBody === undefined || !(await verifySignature(options.secret, header, req.rawBody))) |
| 144 | throw new HBankError("invalid_callback", undefined, "bad or missing HBank-Signature (is rawBody kept?)"); |
| 145 | } |
| 146 | answer = answerFor(await decide(parseCallback(req.body))); |
| 147 | } catch (e) { |
| 148 | answer = refuse(e instanceof HBankError && e.code === "invalid_callback" ? "Invalid callback" : "The shop couldn't confirm this order"); |
| 149 | } |
| 150 | res.status(200).json(answer); |
| 151 | }; |
| 152 | } |