|
| 1 | +/** |
| 2 | + * Verify batch-completion webhooks sent by the GetYouTubeTranscript API. |
| 3 | + * |
| 4 | + * Each delivery carries an `X-GYT-Signature: t=<unix seconds>,v1=<hex>` |
| 5 | + * header, where `v1` is the HMAC-SHA256 of `"<t>.<raw request body>"` keyed |
| 6 | + * with the `webhook_secret` that `createBatch` returned. |
| 7 | + * |
| 8 | + * Uses Web Crypto, so it also runs on edge runtimes; on Node 18, where the |
| 9 | + * global isn't enabled by default, it falls back to `node:crypto`'s copy. |
| 10 | + */ |
| 11 | + |
| 12 | +export interface VerifyWebhookOptions { |
| 13 | + /** Reject signatures older (or newer) than this many seconds, to limit replays. 0 skips the check. Defaults to 300. */ |
| 14 | + toleranceSeconds?: number; |
| 15 | + /** Current Unix time in seconds, for tests. Defaults to now. */ |
| 16 | + now?: number; |
| 17 | +} |
| 18 | + |
| 19 | +async function subtleCrypto(): Promise<SubtleCrypto> { |
| 20 | + if (globalThis.crypto?.subtle) return globalThis.crypto.subtle; |
| 21 | + // Node 18 without --experimental-global-webcrypto. The specifier is kept out of the |
| 22 | + // type graph so the package doesn't need @types/node to build. |
| 23 | + const nodeCryptoSpecifier = "node:crypto"; |
| 24 | + const nodeCrypto = (await import(/* @vite-ignore */ nodeCryptoSpecifier)) as { webcrypto: { subtle: SubtleCrypto } }; |
| 25 | + return nodeCrypto.webcrypto.subtle; |
| 26 | +} |
| 27 | + |
| 28 | +function toHex(buffer: ArrayBuffer): string { |
| 29 | + return Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, "0")).join(""); |
| 30 | +} |
| 31 | + |
| 32 | +/** Compares in time independent of where the strings first differ. */ |
| 33 | +function constantTimeEqual(a: string, b: string): boolean { |
| 34 | + if (a.length !== b.length) return false; |
| 35 | + let diff = 0; |
| 36 | + for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); |
| 37 | + return diff === 0; |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Resolves to `true` if a webhook delivery is genuine and recent. |
| 42 | + * |
| 43 | + * @param body The raw request body exactly as received (e.g. `await request.text()`). |
| 44 | + * Don't re-serialize parsed JSON: any whitespace change breaks the signature. |
| 45 | + * @param signatureHeader The `X-GYT-Signature` header value. |
| 46 | + * @param secret The batch's `webhook_secret` (`whsec_...`). |
| 47 | + */ |
| 48 | +export async function verifyWebhookSignature( |
| 49 | + body: string | Uint8Array, |
| 50 | + signatureHeader: string | null | undefined, |
| 51 | + secret: string, |
| 52 | + options: VerifyWebhookOptions = {}, |
| 53 | +): Promise<boolean> { |
| 54 | + if (!signatureHeader || !secret) return false; |
| 55 | + const parts = new Map( |
| 56 | + signatureHeader.split(",").map((part) => { |
| 57 | + const index = part.indexOf("="); |
| 58 | + return [part.slice(0, index), part.slice(index + 1)] as const; |
| 59 | + }), |
| 60 | + ); |
| 61 | + const timestamp = parts.get("t") ?? ""; |
| 62 | + const signature = parts.get("v1") ?? ""; |
| 63 | + if (!/^\d+$/.test(timestamp) || !signature) return false; |
| 64 | + |
| 65 | + const { toleranceSeconds = 300, now = Date.now() / 1000 } = options; |
| 66 | + if (toleranceSeconds && Math.abs(now - Number(timestamp)) > toleranceSeconds) return false; |
| 67 | + |
| 68 | + const encoder = new TextEncoder(); |
| 69 | + const rawBody = typeof body === "string" ? encoder.encode(body) : body; |
| 70 | + const signed = new Uint8Array(timestamp.length + 1 + rawBody.length); |
| 71 | + signed.set(encoder.encode(`${timestamp}.`)); |
| 72 | + signed.set(rawBody, timestamp.length + 1); |
| 73 | + |
| 74 | + const subtle = await subtleCrypto(); |
| 75 | + const key = await subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); |
| 76 | + const expected = toHex(await subtle.sign("HMAC", key, signed)); |
| 77 | + return constantTimeEqual(expected, signature); |
| 78 | +} |
0 commit comments