Skip to content

Commit a75a3df

Browse files
authored
JavaScript: Fix verification function to allow Buffer (#981)
I missed that in the previous PR (#978) and this was brought up by a customer.
1 parent 487c8c7 commit a75a3df

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

javascript/src/index.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -762,16 +762,12 @@ export class Webhook {
762762
}
763763

764764
public verify(
765-
payload: string,
765+
payload: string | Buffer,
766766
headers_:
767767
| WebhookRequiredHeaders
768768
| WebhookUnbrandedRequiredHeaders
769769
| Record<string, string>
770770
): unknown {
771-
if (typeof payload !== "string") {
772-
throw new Error("Expected payload to be of type string. Please refer to https://docs.svix.com/receiving/verifying-payloads/how for more information.");
773-
}
774-
775771
const headers: Record<string, string> = {};
776772
for (const key of Object.keys(headers_)) {
777773
headers[key.toLowerCase()] = (headers_ as Record<string, string>)[key];
@@ -806,13 +802,21 @@ export class Webhook {
806802
}
807803

808804
if (timingSafeEqual(encoder.encode(signature), encoder.encode(expectedSignature))) {
809-
return JSON.parse(payload);
805+
return JSON.parse(payload.toString());
810806
}
811807
}
812808
throw new WebhookVerificationError("No matching signature found");
813809
}
814810

815-
public sign(msgId: string, timestamp: Date, payload: string): string {
811+
public sign(msgId: string, timestamp: Date, payload: string | Buffer): string {
812+
if (typeof payload === "string") {
813+
// Do nothing, already a string
814+
} else if (payload.constructor.name === "Buffer") {
815+
payload = payload.toString();
816+
} else {
817+
throw new Error("Expected payload to be of type string or Buffer. Please refer to https://docs.svix.com/receiving/verifying-payloads/how for more information.");
818+
}
819+
816820
const encoder = new TextEncoder();
817821
const timestampNumber = Math.floor(timestamp.getTime() / 1000);
818822
const toSign = encoder.encode(`${msgId}.${timestampNumber}.${payload}`);

0 commit comments

Comments
 (0)