@onfido/api
Version:
Node.js library for the Onfido API
37 lines (36 loc) • 1.45 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebhookEventVerifier = exports.OnfidoInvalidSignatureError = void 0;
// 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.
}
class OnfidoInvalidSignatureError extends Error {
}
exports.OnfidoInvalidSignatureError = OnfidoInvalidSignatureError;
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());
}
}
exports.WebhookEventVerifier = WebhookEventVerifier;