|
| 1 | +import crypto from 'node:crypto'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Core HMAC-SHA256 verification. Computes `v0=HMAC(secret, message)` and |
| 5 | + * performs a timing-safe comparison against the expected signature. |
| 6 | + */ |
| 7 | +export function verifyHmacSignature( |
| 8 | + secret: string, |
| 9 | + message: string, |
| 10 | + expectedSignature: string, |
| 11 | +): boolean { |
| 12 | + const computed = |
| 13 | + 'v0=' + |
| 14 | + crypto.createHmac('sha256', secret).update(message, 'utf8').digest('hex'); |
| 15 | + |
| 16 | + if (computed.length !== expectedSignature.length) { |
| 17 | + return false; |
| 18 | + } |
| 19 | + |
| 20 | + return crypto.timingSafeEqual( |
| 21 | + Buffer.from(computed, 'utf8'), |
| 22 | + Buffer.from(expectedSignature, 'utf8'), |
| 23 | + ); |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Verifies a Slack request signature. Checks timestamp staleness (>300s) |
| 28 | + * then validates the HMAC signature. |
| 29 | + */ |
| 30 | +export function verifySlackRequest( |
| 31 | + rawBody: string, |
| 32 | + headers: Headers, |
| 33 | + secret: string, |
| 34 | +): { valid: true } | { valid: false; reason: string } { |
| 35 | + const slackSignature = headers.get('x-slack-signature'); |
| 36 | + const timestamp = headers.get('x-slack-request-timestamp'); |
| 37 | + |
| 38 | + const time = Math.floor(Date.now() / 1000); |
| 39 | + if (!timestamp || Math.abs(time - Number(timestamp)) > 300) { |
| 40 | + return { valid: false, reason: 'Ignore this request.' }; |
| 41 | + } |
| 42 | + |
| 43 | + const message = `v0:${timestamp}:${rawBody}`; |
| 44 | + |
| 45 | + if (slackSignature && verifyHmacSignature(secret, message, slackSignature)) { |
| 46 | + return { valid: true }; |
| 47 | + } |
| 48 | + |
| 49 | + return { valid: false, reason: 'Verification Failed.' }; |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Verifies a Zoom webhook signature using the x-zm-signature header. |
| 54 | + */ |
| 55 | +export function verifyZoomSignature( |
| 56 | + rawBody: string, |
| 57 | + headers: Headers, |
| 58 | + secret: string, |
| 59 | +): boolean { |
| 60 | + const zmSignature = headers.get('x-zm-signature'); |
| 61 | + const zmTimestamp = headers.get('x-zm-request-timestamp'); |
| 62 | + |
| 63 | + if (!zmSignature || !zmTimestamp) { |
| 64 | + return false; |
| 65 | + } |
| 66 | + |
| 67 | + const message = `v0:${zmTimestamp}:${rawBody}`; |
| 68 | + return verifyHmacSignature(secret, message, zmSignature); |
| 69 | +} |
| 70 | + |
| 71 | +/** |
| 72 | + * Computes an HMAC-SHA256 hex digest. Used for Zoom's endpoint URL |
| 73 | + * validation challenge response. |
| 74 | + */ |
| 75 | +export function hmacSha256Hex(secret: string, data: string): string { |
| 76 | + return crypto.createHmac('sha256', secret).update(data).digest('hex'); |
| 77 | +} |
0 commit comments