({
request,
headerName,
headerEncoding = "hex",
secret,
algorithm,
}: {
/** The web request that you want to verify. */
request: Request;
/** The name of the header that contains the signature. E.g. `X-Cal-Signature-256`. */
headerName: string;
/** The header encoding. Defaults to `hex`. */
headerEncoding?: BinaryToTextEncoding;
/** The secret that you use to hash the payload. For HttpEndpoints this will usually originally
come from the Trigger.dev dashboard and should be stored in an environment variable. */
secret: BinaryLike | KeyObject;
/** The hashing algorithm that was used to create the signature. Currently only `sha256` is
supported. */
algorithm: "sha256";
})
| 4 | |
| 5 | /** Easily verify webhook payloads when they're using common signing methods. */ |
| 6 | export async function verifyRequestSignature({ |
| 7 | request, |
| 8 | headerName, |
| 9 | headerEncoding = "hex", |
| 10 | secret, |
| 11 | algorithm, |
| 12 | }: { |
| 13 | /** The web request that you want to verify. */ |
| 14 | request: Request; |
| 15 | /** The name of the header that contains the signature. E.g. `X-Cal-Signature-256`. */ |
| 16 | headerName: string; |
| 17 | /** The header encoding. Defaults to `hex`. */ |
| 18 | headerEncoding?: BinaryToTextEncoding; |
| 19 | /** The secret that you use to hash the payload. For HttpEndpoints this will usually originally |
| 20 | come from the Trigger.dev dashboard and should be stored in an environment variable. */ |
| 21 | secret: BinaryLike | KeyObject; |
| 22 | /** The hashing algorithm that was used to create the signature. Currently only `sha256` is |
| 23 | supported. */ |
| 24 | algorithm: "sha256"; |
| 25 | }): Promise<VerifyResult> { |
| 26 | if (!secret) { |
| 27 | return { |
| 28 | success: false, |
| 29 | reason: "Missing secret – you've probably not set an environment variable.", |
| 30 | }; |
| 31 | } |
| 32 | |
| 33 | const headerValue = request.headers.get(headerName); |
| 34 | if (!headerValue) { |
| 35 | return { success: false, reason: "Missing header" }; |
| 36 | } |
| 37 | |
| 38 | switch (algorithm) { |
| 39 | case "sha256": |
| 40 | const success = verifyHmacSha256(headerValue, headerEncoding, secret, await request.text()); |
| 41 | |
| 42 | if (success) { |
| 43 | return { |
| 44 | success, |
| 45 | }; |
| 46 | } else { |
| 47 | return { success: false, reason: "Failed sha256 verification" }; |
| 48 | } |
| 49 | default: |
| 50 | throw new Error(`Unsupported algorithm: ${algorithm}`); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | export function verifyHmacSha256( |
| 55 | headerValue: string, |
no test coverage detected
searching dependent graphs…