Skip to content
Open
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
8 changes: 4 additions & 4 deletions src/resources/webhooks/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import { InvalidWebhookSignatureError } from '../../error';
import { APIResource } from '../../core/resource';
import { buildHeaders, HeadersLike } from '../../internal/headers';
import { fromBase64 } from '../../internal/utils/base64';
import { encodeUTF8 } from '../../internal/utils/bytes';

export class Webhooks extends APIResource {
/**
Expand Down Expand Up @@ -75,9 +77,7 @@ export class Webhooks extends APIResource {

// Decode the secret if it starts with whsec_
const decodedSecret =
secret.startsWith('whsec_') ?
Buffer.from(secret.replace('whsec_', ''), 'base64')
: Buffer.from(secret, 'utf-8');
secret.startsWith('whsec_') ? fromBase64(secret.replace('whsec_', '')) : encodeUTF8(secret);

// Create the signed payload: {webhook_id}.{timestamp}.{payload}
const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`;
Expand All @@ -94,7 +94,7 @@ export class Webhooks extends APIResource {
// Check if any signature matches using timing-safe WebCrypto verify
for (const signature of signatures) {
try {
const signatureBytes = Buffer.from(signature, 'base64');
const signatureBytes = fromBase64(signature);
const isValid = await crypto.subtle.verify(
'HMAC',
key,
Expand Down
11 changes: 11 additions & 0 deletions tests/api-resources/webhooks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@ describe('resource webhooks', () => {
await client.webhooks.verifySignature(payload, headers, secret);
});

it('should pass for valid signature without Buffer if WebCrypto is available', async () => {
const originalBuffer = globalThis.Buffer;
try {
// @ts-expect-error Can't assign undefined to BufferConstructor
delete globalThis.Buffer;
await client.webhooks.verifySignature(payload, headers, secret);
} finally {
globalThis.Buffer = originalBuffer;
}
});

it('should throw an error for invalid secret format', async () => {
await expect(
client.webhooks.verifySignature(payload, headers, null as any),
Expand Down