@onfido/api
Version:
Node.js library for the Onfido API
32 lines (31 loc) • 1.19 kB
JavaScript
// Require crypto instead of importing, because Node can be built without crypto support.
let crypto;
try {
// tslint:disable-next-line: no-var-requires
crypto = require("crypto");
}
catch (_a) {
// We throw an error when verifying webhooks instead.
}
export class OnfidoInvalidSignatureError extends Error {
}
export class WebhookEventVerifier {
constructor(webhookToken) {
this.webhookToken = webhookToken;
}
readPayload(rawEventBody, hexSignature) {
if (!crypto) {
throw new Error("Verifying webhook events requires crypto support");
}
const givenSignature = Buffer.from(hexSignature, "hex");
// Compute the the actual HMAC signature from the raw request body.
const hmac = crypto.createHmac("sha256", this.webhookToken);
hmac.update(rawEventBody);
const eventSignature = hmac.digest();
// Use timingSafeEqual to prevent against timing attacks.
if (!crypto.timingSafeEqual(givenSignature, eventSignature)) {
throw new OnfidoInvalidSignatureError("Invalid signature for webhook event");
}
return JSON.parse(rawEventBody.toString());
}
}