"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isWebhookRequestAuthorized = exports.getSignatureFromHeaders = exports.METRIPORT_SIGNATURE_HEADER = void 0;
const lodash_1 = require("lodash");
const api_sdk_1 = require("@metriport/api-sdk");
/**
 * The header Metriport uses to deliver the webhook signature.
 * https://docs.metriport.com/medical-api/getting-started/webhooks#authentication
 */
exports.METRIPORT_SIGNATURE_HEADER = 'x-metriport-signature';
/**
 * Extracts the signature from the request headers, normalising the
 * `string | string[] | undefined` type that `IncomingHttpHeaders` allows.
 */
const getSignatureFromHeaders = (headers) => {
    const header = headers[exports.METRIPORT_SIGNATURE_HEADER];
    return Array.isArray(header) ? header[0] : header;
};
exports.getSignatureFromHeaders = getSignatureFromHeaders;
/**
 * Verifies a Metriport webhook request.
 *
 * Metriport signs each request with an HMAC-SHA256 of the raw request body
 * using the webhook key, delivered in the `x-metriport-signature` header. The
 * hash must be computed over the raw body (never the re-serialized payload),
 * which is why this takes the `rawBody` buffer.
 * https://docs.metriport.com/medical-api/getting-started/webhooks#authentication
 *
 * @returns `true` if the request is authorized: either no webhook key is
 * configured (verification disabled) or the signature is present and valid.
 * `false` when a key is configured but the signature is missing or invalid.
 */
const isWebhookRequestAuthorized = ({ webhookKey, rawBody, headers, }) => {
    // When no webhook key is configured, signature verification is disabled.
    if ((0, lodash_1.isNil)(webhookKey) || webhookKey.length === 0) {
        return true;
    }
    const signature = (0, exports.getSignatureFromHeaders)(headers);
    if ((0, lodash_1.isNil)(signature) || signature.length === 0) {
        return false;
    }
    return api_sdk_1.MetriportMedicalApi.verifyWebhookSignature(webhookKey, rawBody, signature);
};
exports.isWebhookRequestAuthorized = isWebhookRequestAuthorized;
//# sourceMappingURL=verifyWebhookSignature.js.map