|
| 1 | +import { type H3Event, getRequestHeaders, readRawBody } from 'h3' |
| 2 | +import { computeSignature, HMAC_SHA256, ensureConfiguration } from '../helpers' |
| 3 | + |
| 4 | +const SLACK_SIGNATURE = 'X-Slack-Signature'.toLowerCase() |
| 5 | +const SLACK_TIMESTAMP = 'X-Slack-Request-Timestamp'.toLowerCase() |
| 6 | +const DEFAULT_TOLERANCE = 300 // 5 minutes |
| 7 | + |
| 8 | +/** |
| 9 | + * Validates Slack webhooks on the Edge |
| 10 | + * @see {@link https://docs.slack.dev/authentication/verifying-requests-from-slack/} |
| 11 | + * @param event H3Event |
| 12 | + * @returns {boolean} `true` if the webhook is valid, `false` otherwise |
| 13 | + */ |
| 14 | +export const isValidSlackWebhook = async (event: H3Event): Promise<boolean> => { |
| 15 | + const config = ensureConfiguration('slack', event) |
| 16 | + |
| 17 | + const headers = getRequestHeaders(event) |
| 18 | + const body = await readRawBody(event) |
| 19 | + |
| 20 | + const fullSignature = headers[SLACK_SIGNATURE] |
| 21 | + const timestamp = headers[SLACK_TIMESTAMP] |
| 22 | + |
| 23 | + if (!body || !fullSignature || !timestamp) return false |
| 24 | + |
| 25 | + // Validate the timestamp to avoid replay attacks |
| 26 | + const now = Math.floor(Date.now() / 1000) |
| 27 | + if (now - Number.parseInt(timestamp) > DEFAULT_TOLERANCE) return false |
| 28 | + |
| 29 | + const [signatureVersion, webhookSignature] = fullSignature.split('=') |
| 30 | + const payload = `${signatureVersion}:${timestamp}:${body}` |
| 31 | + |
| 32 | + const computedHash = await computeSignature(config.secretKey, HMAC_SHA256, payload) |
| 33 | + return computedHash === webhookSignature |
| 34 | +} |
0 commit comments