|
| 1 | +/* eslint-disable turbo/no-undeclared-env-vars */ |
| 2 | +import { |
| 3 | + // @ts-ignore |
| 4 | + Scalars, |
| 5 | + // @ts-ignore |
| 6 | + // eslint-disable-next-line import/no-unresolved |
| 7 | +} from "../schema"; |
| 8 | +import crypto from "crypto"; |
| 9 | + |
| 10 | +/* ------------------------------------------------------------------------------------------------- |
| 11 | + * Client |
| 12 | + * -----------------------------------------------------------------------------------------------*/ |
| 13 | + |
| 14 | +type KeysStartingWith<Obj, Prefix extends string> = { |
| 15 | + [K in keyof Obj]: K extends `${Prefix}${string}` ? K : never; |
| 16 | +}[keyof Obj]; |
| 17 | + |
| 18 | +type ExtractWorkflowKey<T extends string> = T extends `${infer Base}:${string}` |
| 19 | + ? Base |
| 20 | + : T; |
| 21 | + |
| 22 | +// Get all event key types (bshb_event_*) |
| 23 | +export type WorkflowKeys = KeysStartingWith<Scalars, "bshb_workflow">; |
| 24 | + |
| 25 | +// Map from event key to its schema type |
| 26 | +type WorkflowSchemaMap = { |
| 27 | + // @ts-ignore |
| 28 | + [K in WorkflowKeys]: Scalars[`schema_${K}`]; |
| 29 | +}; |
| 30 | + |
| 31 | +export const authenticateWebhook = async < |
| 32 | + Key extends `${WorkflowKeys}:${string}`, |
| 33 | +>({ |
| 34 | + secret, |
| 35 | + body, |
| 36 | + signature, |
| 37 | +}: { |
| 38 | + /** |
| 39 | + * The body of the incoming webhook request |
| 40 | + * Can be: |
| 41 | + * - Parsed JSON from request.json() |
| 42 | + * - Raw string from request.text() |
| 43 | + * - ReadableStream from request.body |
| 44 | + */ |
| 45 | + body: unknown; |
| 46 | + /** |
| 47 | + * The signature of the incoming webhook request—you get this via request.headers["x-basehub-webhook-signature"] |
| 48 | + * This should be a hex-encoded HMAC SHA-256 hash of the request body |
| 49 | + */ |
| 50 | + signature: string; |
| 51 | + /** |
| 52 | + * The secret used for verifying the incoming webhook request—you get this via the BaseHub API |
| 53 | + * This secret should never be exposed in requests or responses |
| 54 | + */ |
| 55 | + secret: Key; |
| 56 | +}): Promise< |
| 57 | + | { success: true; payload: WorkflowSchemaMap[ExtractWorkflowKey<Key>] } |
| 58 | + | { success: false; error: string } |
| 59 | +> => { |
| 60 | + try { |
| 61 | + // Handle different body types |
| 62 | + let rawBody: string; |
| 63 | + let parsedBody: unknown; |
| 64 | + |
| 65 | + if (body instanceof ReadableStream) { |
| 66 | + // Convert stream to text |
| 67 | + const reader = body.getReader(); |
| 68 | + const chunks = []; |
| 69 | + while (true) { |
| 70 | + const { done, value } = await reader.read(); |
| 71 | + if (done) break; |
| 72 | + chunks.push(value); |
| 73 | + } |
| 74 | + const bodyText = new TextDecoder().decode( |
| 75 | + new Uint8Array(chunks.flatMap((chunk) => Array.from(chunk))) |
| 76 | + ); |
| 77 | + rawBody = bodyText; |
| 78 | + parsedBody = JSON.parse(bodyText); |
| 79 | + } else if (typeof body === "string") { |
| 80 | + rawBody = body; |
| 81 | + parsedBody = JSON.parse(body); |
| 82 | + } else { |
| 83 | + // Already parsed JSON |
| 84 | + rawBody = JSON.stringify(body); |
| 85 | + parsedBody = body; |
| 86 | + } |
| 87 | + |
| 88 | + if (typeof parsedBody !== "object" || parsedBody === null) { |
| 89 | + return { success: false, error: "Invalid body" }; |
| 90 | + } |
| 91 | + |
| 92 | + const encoder = new TextEncoder(); |
| 93 | + const bodyData = encoder.encode(rawBody); |
| 94 | + const secretData = encoder.encode(secret); |
| 95 | + |
| 96 | + const key = await crypto.subtle.importKey( |
| 97 | + "raw", |
| 98 | + secretData, |
| 99 | + { name: "HMAC", hash: "SHA-256" }, |
| 100 | + false, |
| 101 | + ["sign"] |
| 102 | + ); |
| 103 | + |
| 104 | + const signed = await crypto.subtle.sign("HMAC", key, bodyData); |
| 105 | + const calculatedSignature = Array.from(new Uint8Array(signed)) |
| 106 | + .map((b) => b.toString(16).padStart(2, "0")) |
| 107 | + .join(""); |
| 108 | + |
| 109 | + if (signature.length !== calculatedSignature.length) { |
| 110 | + return { success: false, error: "Invalid signature" }; |
| 111 | + } |
| 112 | + |
| 113 | + let mismatch = 0; |
| 114 | + for (let i = 0; i < signature.length; i++) { |
| 115 | + mismatch |= signature.charCodeAt(i) ^ calculatedSignature.charCodeAt(i); |
| 116 | + } |
| 117 | + |
| 118 | + if (mismatch !== 0) { |
| 119 | + return { success: false, error: "Invalid signature" }; |
| 120 | + } |
| 121 | + |
| 122 | + return { |
| 123 | + success: true, |
| 124 | + payload: parsedBody as WorkflowSchemaMap[ExtractWorkflowKey<Key>], |
| 125 | + }; |
| 126 | + } catch (error) { |
| 127 | + return { |
| 128 | + success: false, |
| 129 | + error: |
| 130 | + error instanceof Error |
| 131 | + ? error.message |
| 132 | + : "Signature verification failed", |
| 133 | + }; |
| 134 | + } |
| 135 | +}; |
0 commit comments