UNPKG

@transcend-io/typescript-webhook-example

Version:

Example of a webhook that can be integrated with Transcend.

54 lines 2.27 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.verifyWebhook = void 0; // Libraries const got_1 = __importDefault(require("got")); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); // Constants const constants_1 = require("../constants"); const logger_1 = require("../logger"); // Global to cache the webhook signing public key let cachedPublicKey; /** * Helper to verify incoming webhook requests * * Transcend developers: A design choice was made not to put webhook verification on an Express middleware. * It's a nice refactor, but it can be esoteric to readers. * * @param signedToken - the JSON Web Token asymmetrically signed with ES384. * @returns - the signed body */ async function verifyWebhook(signedToken) { // Get the public key and cache it for next time. if (!cachedPublicKey) { try { const publicKeyUrl = `${constants_1.SOMBRA_URL}/public-keys/sombra-general-signing-key`; logger_1.logger.info(`Fetching transcend public key: ${publicKeyUrl}`); const response = await got_1.default.get(publicKeyUrl, { headers: { authorization: `Bearer ${constants_1.TRANSCEND_API_KEY}`, 'x-sombra-authorization': constants_1.SOMBRA_API_KEY ? `Bearer ${constants_1.SOMBRA_API_KEY}` : undefined, }, }); cachedPublicKey = response.body; } catch (err) { logger_1.logger.error('Failed to get public key:', err); } } // Verify webhook signature with the public key (ensures that Transcend sent the request) const signedBody = jsonwebtoken_1.default.verify(Array.isArray(signedToken) ? signedToken.join() : signedToken || '', cachedPublicKey, { algorithms: ['ES384'], audience: constants_1.AUDIENCE, }); if (signedBody.scope !== 'coreIdentifier') { throw Error('Found JWT with incorrect scope for webhook requests'); } } exports.verifyWebhook = verifyWebhook; //# sourceMappingURL=verifyWebhook.js.map