( signingSecret: string, requestSignature: string, requestTimestamp: string, body: string )
| 21 | * @returns true if signature is valid |
| 22 | */ |
| 23 | export function verifySlackSignature( |
| 24 | signingSecret: string, |
| 25 | requestSignature: string, |
| 26 | requestTimestamp: string, |
| 27 | body: string |
| 28 | ): boolean { |
| 29 | // Check timestamp is recent (within 5 minutes) |
| 30 | const timestamp = parseInt(requestTimestamp, 10); |
| 31 | const now = Math.floor(Date.now() / 1000); |
| 32 | if (Math.abs(now - timestamp) > 60 * 5) { |
| 33 | logger.warn({ timestamp, now, diff: Math.abs(now - timestamp) }, 'Slack request timestamp too old'); |
| 34 | return false; |
| 35 | } |
| 36 | |
| 37 | // Create signature base string |
| 38 | const sigBasestring = `v0:${requestTimestamp}:${body}`; |
| 39 | |
| 40 | // Create HMAC signature |
| 41 | const mySignature = 'v0=' + crypto |
| 42 | .createHmac('sha256', signingSecret) |
| 43 | .update(sigBasestring) |
| 44 | .digest('hex'); |
| 45 | |
| 46 | // Compare signatures using timing-safe comparison |
| 47 | try { |
| 48 | return crypto.timingSafeEqual( |
| 49 | Buffer.from(mySignature, 'utf8'), |
| 50 | Buffer.from(requestSignature, 'utf8') |
| 51 | ); |
| 52 | } catch { |
| 53 | return false; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Express middleware to verify Slack request signatures |
no test coverage detected