|
| 1 | +/** |
| 2 | + * Checks that a webhook body really came from your Jira site. |
| 3 | + * |
| 4 | + * A webhook registered with a secret arrives signed: Jira computes HMAC-SHA256 over the exact bytes of the request |
| 5 | + * body and sends the digest as `X-Hub-Signature: sha256=<hex>`. Recomputing it with the same secret is the only thing |
| 6 | + * that distinguishes a delivery from Jira from a POST anyone on the internet can make to the same URL. |
| 7 | + * |
| 8 | + * ```ts |
| 9 | + * import { verifyWebhookSignature } from 'jira.js/webhooks'; |
| 10 | + * |
| 11 | + * app.post('/jira', express.raw({ type: 'application/json' }), async (request, response) => { |
| 12 | + * const trusted = await verifyWebhookSignature({ |
| 13 | + * body: request.body, |
| 14 | + * secret: process.env.JIRA_WEBHOOK_SECRET!, |
| 15 | + * signature: request.get('x-hub-signature'), |
| 16 | + * }); |
| 17 | + * |
| 18 | + * if (!trusted) return response.sendStatus(401); |
| 19 | + * |
| 20 | + * const payload = JSON.parse(request.body.toString()) as WebhookPayload; |
| 21 | + * }); |
| 22 | + * ``` |
| 23 | + * |
| 24 | + * The body must be the bytes that arrived. Re-serialising a parsed object — `JSON.stringify(request.body)` — produces |
| 25 | + * a different byte sequence for the same data, because key order, whitespace and number formatting are not preserved, |
| 26 | + * and the signature will not match. Every framework has a way to keep the raw body; use it. |
| 27 | + * |
| 28 | + * Nothing here is imported: `crypto.subtle` is a global in Node 18 and later and in every browser, so this subpath |
| 29 | + * stays free of Node built-ins and the browser bundle is unaffected. |
| 30 | + */ |
| 31 | + |
| 32 | +/** How a signature was computed. Jira sends `sha256`; nothing else is accepted. */ |
| 33 | +const ALGORITHM = 'sha256'; |
| 34 | + |
| 35 | +export interface VerifyWebhookSignatureOptions { |
| 36 | + /** |
| 37 | + * The raw request body, exactly as it arrived — not a parsed object re-serialised, whose bytes differ from what was |
| 38 | + * signed. |
| 39 | + */ |
| 40 | + body: string | ArrayBuffer | Uint8Array; |
| 41 | + |
| 42 | + /** The secret you gave Jira when you registered the webhook. */ |
| 43 | + secret: string; |
| 44 | + |
| 45 | + /** |
| 46 | + * The `X-Hub-Signature` header. Passing `undefined` is the ordinary case of an unsigned delivery and answers |
| 47 | + * `false`, so a missing header needs no separate branch of yours. |
| 48 | + */ |
| 49 | + signature: string | undefined; |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Copies into an array `crypto.subtle` accepts. |
| 54 | + * |
| 55 | + * `BufferSource` excludes a view onto a `SharedArrayBuffer`, which a plain `Uint8Array` may be; constructing a new one |
| 56 | + * both narrows the type and respects the offset and length of a view onto a larger buffer, which a webhook body read |
| 57 | + * out of a pooled buffer usually is. |
| 58 | + */ |
| 59 | +function toBytes(value: string | ArrayBuffer | Uint8Array): Uint8Array<ArrayBuffer> { |
| 60 | + if (typeof value === 'string') return new TextEncoder().encode(value); |
| 61 | + |
| 62 | + return new Uint8Array(value); |
| 63 | +} |
| 64 | + |
| 65 | +function fromHex(hex: string): Uint8Array | undefined { |
| 66 | + if (hex.length === 0 || hex.length % 2 !== 0 || !/^[0-9a-f]+$/i.test(hex)) return undefined; |
| 67 | + |
| 68 | + const bytes = new Uint8Array(hex.length / 2); |
| 69 | + |
| 70 | + for (let index = 0; index < bytes.length; index++) { |
| 71 | + bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16); |
| 72 | + } |
| 73 | + |
| 74 | + return bytes; |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * Compares two digests without letting the time taken reveal how far they matched. |
| 79 | + * |
| 80 | + * A `===` on hex strings stops at the first differing character, and an attacker who can send many deliveries and |
| 81 | + * measure the replies can recover a valid signature one character at a time. Differing lengths are answered at once |
| 82 | + * on purpose: the length of a digest is public, its contents are not. |
| 83 | + */ |
| 84 | +function equalInConstantTime(left: Uint8Array, right: Uint8Array): boolean { |
| 85 | + if (left.length !== right.length) return false; |
| 86 | + |
| 87 | + let difference = 0; |
| 88 | + |
| 89 | + for (let index = 0; index < left.length; index++) difference |= left[index]! ^ right[index]!; |
| 90 | + |
| 91 | + return difference === 0; |
| 92 | +} |
| 93 | + |
| 94 | +/** |
| 95 | + * Whether the body carries a signature this secret produces. |
| 96 | + * |
| 97 | + * Answers `false` for every way a delivery can fail to be trustworthy — no header, an algorithm other than `sha256`, |
| 98 | + * a digest that is not hexadecimal, a digest of the right shape and the wrong value — because a handler's response to |
| 99 | + * all four is the same, and telling them apart to the caller would tell them apart to whoever is probing the endpoint. |
| 100 | + * |
| 101 | + * Throws only on a mistake of yours: an empty secret would make every delivery verify against a value an attacker can |
| 102 | + * compute, so it is a programming error rather than a failed check. |
| 103 | + */ |
| 104 | +export async function verifyWebhookSignature(options: VerifyWebhookSignatureOptions): Promise<boolean> { |
| 105 | + const { body, secret, signature } = options; |
| 106 | + |
| 107 | + if (secret.length === 0) { |
| 108 | + throw new TypeError('verifyWebhookSignature: the secret is empty, which would verify every body ever sent'); |
| 109 | + } |
| 110 | + |
| 111 | + if (signature === undefined) return false; |
| 112 | + |
| 113 | + const separator = signature.indexOf('='); |
| 114 | + |
| 115 | + if (signature.slice(0, separator) !== ALGORITHM) return false; |
| 116 | + |
| 117 | + const sent = fromHex(signature.slice(separator + 1)); |
| 118 | + |
| 119 | + if (sent === undefined) return false; |
| 120 | + |
| 121 | + const key = await crypto.subtle.importKey( |
| 122 | + 'raw', |
| 123 | + toBytes(secret), |
| 124 | + { name: 'HMAC', hash: 'SHA-256' }, |
| 125 | + false, |
| 126 | + ['sign'], |
| 127 | + ); |
| 128 | + |
| 129 | + const computed = new Uint8Array(await crypto.subtle.sign('HMAC', key, toBytes(body))); |
| 130 | + |
| 131 | + return equalInConstantTime(computed, sent); |
| 132 | +} |
0 commit comments