From 2d8df712d8b00513563c1616f32198e82a773cc0 Mon Sep 17 00:00:00 2001 From: divyanshujethi Date: Wed, 25 Nov 2026 16:08:00 +0530 Subject: [PATCH] fix(billing): align Dodo checkout metadata, redirect_url & Standard Webhooks v1 HMAC --- src/routes/billing.ts | 83 +++++++++++++++++++++++++++++++++---------- tests/billing.test.ts | 72 +++++++++++++++++++++++++++++++++++-- 2 files changed, 135 insertions(+), 20 deletions(-) diff --git a/src/routes/billing.ts b/src/routes/billing.ts index 961265e..85cba47 100644 --- a/src/routes/billing.ts +++ b/src/routes/billing.ts @@ -62,11 +62,15 @@ export async function registerBillingRoutes( const tierConfig = TIER_CONFIGS[tier]; const callback = returnUrl || "https://poly.ritualdev.in/dashboard?upgrade=success"; - const checkoutUrl = `${tierConfig.checkoutUrl}?quantity=1&metadata.workspace=${encodeURIComponent( - workspaceSlug, - )}&metadata.tier=${tier}${email ? `&email=${encodeURIComponent(email)}` : ""}&return_url=${encodeURIComponent( - callback, - )}`; + const params = new URLSearchParams(); + params.set("quantity", "1"); + params.set("metadata_workspace", workspaceSlug); + params.set("metadata_tier", tier); + if (email) { + params.set("email", email); + } + params.set("redirect_url", callback); + const checkoutUrl = `${tierConfig.checkoutUrl}?${params.toString()}`; return reply.code(200).send({ success: true, @@ -121,7 +125,8 @@ export async function registerBillingRoutes( app.post("/api/v1/billing/webhooks/dodo", async (request, reply) => { const webhookSecret = options.dodoWebhookSecret || process.env.DODO_WEBHOOK_SECRET; - // Cryptographic signature check (Fail-closed) + const webhookId = (request.headers["webhook-id"] as string) || ""; + const webhookTimestamp = (request.headers["webhook-timestamp"] as string) || ""; const sigHeader = (request.headers["webhook-signature"] as string) || (request.headers["x-dodo-signature"] as string) || @@ -141,7 +146,6 @@ export async function registerBillingRoutes( }); } - // Raw body validation const rawBody = typeof request.body === "string" ? request.body @@ -149,19 +153,62 @@ export async function registerBillingRoutes( ? request.body.toString("utf-8") : JSON.stringify(request.body); - const sigParts = sigHeader.includes("v1=") ? sigHeader.split(",") : [sigHeader]; - let signatureToCompare = sigHeader.replace(/^sha256=/, "").trim(); - for (const part of sigParts) { - const [k, v] = part.trim().split("="); - if (k === "v1") signatureToCompare = v; - } - try { - const computedHex = crypto.createHmac("sha256", webhookSecret).update(rawBody).digest("hex"); - const sigBuf = Buffer.from(signatureToCompare, "hex"); - const compBuf = Buffer.from(computedHex, "hex"); + let verified = false; + + if (webhookId && webhookTimestamp) { + // Dodo Payments Standard Webhooks HMAC-SHA256 verification (v1,) + const tsSec = Number.parseInt(webhookTimestamp, 10); + if (!Number.isFinite(tsSec) || Math.abs(Date.now() / 1000 - tsSec) > 600) { + return reply.code(401).send({ + error: "Unauthorized", + message: "Webhook timestamp outside allowed tolerance window", + }); + } + const rawKey = webhookSecret.startsWith("whsec_") + ? webhookSecret.slice("whsec_".length) + : webhookSecret; + const keyBytes = Buffer.from(rawKey, "base64"); + const signedContent = `${webhookId}.${webhookTimestamp}.${rawBody}`; + const expectedB64 = crypto + .createHmac("sha256", keyBytes) + .update(signedContent) + .digest("base64"); + const expectedBuf = Buffer.from(expectedB64); + + for (const cand of sigHeader.trim().split(/\s+/)) { + const [ver, b64Sig] = cand.split(","); + if (ver === "v1" && b64Sig) { + const candBuf = Buffer.from(b64Sig); + if ( + candBuf.length === expectedBuf.length && + crypto.timingSafeEqual(candBuf, expectedBuf) + ) { + verified = true; + break; + } + } + } + } else { + // Legacy hex HMAC compatibility fallback when Standard Webhooks headers are omitted + const sigParts = sigHeader.includes("v1=") ? sigHeader.split(",") : [sigHeader]; + let signatureToCompare = sigHeader.replace(/^sha256=/, "").trim(); + for (const part of sigParts) { + const [k, v] = part.trim().split("="); + if (k === "v1") signatureToCompare = v; + } + const computedHex = crypto + .createHmac("sha256", webhookSecret) + .update(rawBody) + .digest("hex"); + const sigBuf = Buffer.from(signatureToCompare, "hex"); + const compBuf = Buffer.from(computedHex, "hex"); + if (sigBuf.length === compBuf.length && crypto.timingSafeEqual(sigBuf, compBuf)) { + verified = true; + } + } - if (sigBuf.length !== compBuf.length || !crypto.timingSafeEqual(sigBuf, compBuf)) { + if (!verified) { return reply.code(401).send({ error: "Unauthorized", message: "Invalid Dodo Payments signature", diff --git a/tests/billing.test.ts b/tests/billing.test.ts index 98c339a..ea71c22 100644 --- a/tests/billing.test.ts +++ b/tests/billing.test.ts @@ -60,8 +60,9 @@ test("Poly Remote Cloud Cache Tiering & Billing Suite", async (t) => { assert.equal(body.workspaceSlug, "startup-team"); assert.equal(body.tier, "pro"); assert.ok(body.checkoutUrl.includes("checkout.dodopayments.com")); - assert.ok(body.checkoutUrl.includes("metadata.workspace=startup-team")); - assert.ok(body.checkoutUrl.includes("metadata.tier=pro")); + assert.ok(body.checkoutUrl.includes("metadata_workspace=startup-team")); + assert.ok(body.checkoutUrl.includes("metadata_tier=pro")); + assert.ok(body.checkoutUrl.includes("redirect_url=")); assert.ok(body.checkoutUrl.includes("email=lead%40startup.io")); }); @@ -204,4 +205,71 @@ test("Poly Remote Cloud Cache Tiering & Billing Suite", async (t) => { assert.equal(ws?.subscriptionStatus, "cancelled"); }, ); + + await t.test( + "POST /api/v1/billing/webhooks/dodo verifies Dodo Standard Webhooks v1 HMAC-SHA256 & upgrades to enterprise", + async () => { + process.env.DODO_WEBHOOK_SECRET = webhookSecret; + + const payload = { + event_id: "evt_sub_ent_200", + type: "subscription.active", + data: { + subscription_id: "sub_dodo_ent_200", + customer: { + customer_id: "cus_dodo_ent_200", + email: "cto@startup.io", + }, + metadata: { + workspace: "startup-team", + tier: "enterprise", + }, + }, + }; + + const rawBody = JSON.stringify(payload); + const msgId = "msg_dodo_std_200"; + const msgTs = String(Math.floor(Date.now() / 1000)); + const keyBytes = Buffer.from(webhookSecret.slice("whsec_".length), "base64"); + const v1Sig = crypto + .createHmac("sha256", keyBytes) + .update(`${msgId}.${msgTs}.${rawBody}`) + .digest("base64"); + + const res = await app.inject({ + method: "POST", + url: "/api/v1/billing/webhooks/dodo", + headers: { + "webhook-id": msgId, + "webhook-timestamp": msgTs, + "webhook-signature": `v1,${v1Sig}`, + "content-type": "application/json", + }, + payload, + }); + + assert.equal(res.statusCode, 200); + const body = JSON.parse(res.body); + assert.equal(body.success, true); + assert.equal(body.tier, "enterprise"); + assert.equal(body.quotaBytes, 500 * 1024 * 1024 * 1024); + + const ws = await store.getWorkspaceBySlug("startup-team"); + assert.equal(ws?.tier, "enterprise"); + assert.equal(ws?.subscriptionStatus, "active"); + + const badRes = await app.inject({ + method: "POST", + url: "/api/v1/billing/webhooks/dodo", + headers: { + "webhook-id": msgId, + "webhook-timestamp": msgTs, + "webhook-signature": "v1,Zm9yZ2VkX3NpZ25hdHVyZV9ieXRlcw==", + "content-type": "application/json", + }, + payload, + }); + assert.equal(badRes.statusCode, 401); + }, + ); });