Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 65 additions & 18 deletions src/routes/billing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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) ||
Expand All @@ -141,27 +146,69 @@ export async function registerBillingRoutes(
});
}

// Raw body validation
const rawBody =
typeof request.body === "string"
? request.body
: Buffer.isBuffer(request.body)
? 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,<base64>)
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",
Expand Down
72 changes: 70 additions & 2 deletions tests/billing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
});

Expand Down Expand Up @@ -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);
},
);
});