fix(billing): verify the signing scheme the secret actually says it is

Every delivery was refused as a signature mismatch, and nothing in the error
said why.

The provider signs one of two ways. A `whsec_` prefix means Standard Webhooks,
where the secret is a base64 key the verifier decodes; anything else is the
older scheme, where the secret is used as its own raw bytes. Which one a secret
belongs to is decided by when it was created, and every secret created now is
the new one.

The SDK's helper only implements the older scheme — it base64-encodes whatever
it is handed, so a Standard Webhooks secret becomes the literal bytes of the
string including its prefix, and every signature then fails against a key
derived quite differently.

The scheme is now read off the secret rather than configured, so rotating one
cannot put the two out of step. The verifier for the new scheme is the same
library the SDK uses underneath; nothing here hand-rolls crypto.

Tested with a real signature rather than only a rejection. A mismatch is easy to
assert by accident, and a test that only proved bad input is refused would have
passed against the broken version too.

Also teaches the product script to check shape and not just name: a one-time
product where a subscription is wanted cannot be subscribed to at all, and
reporting it as already-there hands back an id that fails at its first use.
This commit is contained in:
Wanjohi
2026-09-19 01:33:26 +03:00
parent 2dfb7f4007
commit 5b90bd0f0c
6 changed files with 146 additions and 41 deletions

View File

@@ -137,3 +137,53 @@ describe('Webhooks', () => {
expect(() => Polar.receive({ body: '{}', headers: {} })).toThrow(/not configured/);
});
});
describe('Both signing schemes', () => {
// A `whsec_` secret is Standard Webhooks, where the secret is a base64 key.
// The SDK helper only implements the older scheme and base64-encodes
// whatever it is handed, so a Standard Webhooks secret verified through it
// fails every time, for a reason no error message mentions. These assert the
// prefix is what picks, so rotating a secret cannot put the two out of step.
test('a Standard Webhooks secret is verified, and a real signature passes', async () => {
const { Webhook } = await import('standardwebhooks');
const key = Buffer.from('a'.repeat(32)).toString('base64');
const secret = `whsec_${key}`;
configure({ POLAR_WEBHOOK_SECRET: secret });
const body = JSON.stringify({
type: 'subscription.active',
data: { customer: { externalId: 'tem_x' }, productId: PAID }
});
const id = 'msg_1';
const timestamp = new Date();
const signature = new Webhook(secret).sign(id, timestamp, body);
const delivery = Polar.receive({
body,
headers: {
'webhook-id': id,
'webhook-timestamp': Math.floor(timestamp.getTime() / 1000).toString(),
'webhook-signature': signature
}
});
expect(delivery.type).toBe('subscription.active');
expect(delivery.teamId).toBe('tem_x');
expect(delivery.standing).toEqual({ plan: 'paid', status: 'active' });
});
test('a tampered body under a valid-looking signature is refused', () => {
const secret = `whsec_${Buffer.from('a'.repeat(32)).toString('base64')}`;
configure({ POLAR_WEBHOOK_SECRET: secret });
expect(() =>
Polar.receive({
body: '{"type":"subscription.revoked"}',
headers: {
'webhook-id': 'msg_1',
'webhook-timestamp': '1',
'webhook-signature': 'v1,AAAA'
}
})
).toThrow(/Signature/);
});
});

View File

@@ -1,5 +1,6 @@
import { Polar as PolarSdk } from '@polar-sh/sdk';
import { validateEvent, WebhookVerificationError } from '@polar-sh/sdk/webhooks';
import { Webhook as StandardWebhook } from 'standardwebhooks';
import z from 'zod';
import { Env } from '../env.js';
@@ -257,11 +258,31 @@ export namespace Polar {
);
}
let event;
// Two signing schemes, told apart by the secret itself.
//
// A `whsec_` prefix means Standard Webhooks, where the secret is a
// base64 key the library decodes. Anything else is the older scheme,
// where the secret is used as its own raw bytes. The SDK's helper
// only implements the older one — it base64-encodes whatever it is
// handed, which turns a Standard Webhooks secret into the literal
// bytes of the string including the prefix, and then every signature
// fails to match for a reason no error message mentions.
//
// Reading the prefix rather than configuring which scheme is in use
// means rotating a secret cannot put the two out of step.
let event: { type: string; data?: Record<string, unknown> };
try {
event = validateEvent(input.body, input.headers, webhookSecret);
if (webhookSecret.startsWith('whsec_')) {
const verified = new StandardWebhook(webhookSecret).verify(input.body, input.headers);
event = verified as { type: string; data?: Record<string, unknown> };
} else {
event = validateEvent(input.body, input.headers, webhookSecret) as {
type: string;
data?: Record<string, unknown>;
};
}
} catch (error) {
if (error instanceof WebhookVerificationError) {
if (error instanceof WebhookVerificationError || error instanceof Error) {
throw new VisibleError(
'authentication',
ErrorCodes.Authentication.INVALID_TOKEN,
@@ -271,7 +292,7 @@ export namespace Polar {
throw error;
}
const data = (event as { data?: Record<string, unknown> }).data ?? {};
const data = event.data ?? {};
const customer = data.customer as { externalId?: string | null } | undefined;
// `externalId` is the team id we put on the customer. A delivery
// without one is about a customer created some other way — by hand in