|
| 1 | +import { type H3Event, getRequestHeader, getRequestIP } from 'h3' |
| 2 | +import { useRuntimeConfig } from '#imports' |
| 3 | + |
| 4 | +const ALLOWED_IP_RANGES = ['1.179.112.0/20', '172.246.240.0/20'] |
| 5 | + |
| 6 | +const ipToInt = (ip: string) => { |
| 7 | + return ip.split('.').reduce((acc, octet) => (acc << 8) + Number(octet), 0) |
| 8 | +} |
| 9 | + |
| 10 | +const isIpInRange = (ip: string, cidr: string) => { |
| 11 | + const [range, bits] = cidr.split('/') |
| 12 | + if (!range || !bits) return false |
| 13 | + |
| 14 | + const mask = ~(2 ** (32 - Number(bits)) - 1) |
| 15 | + return (ipToInt(ip) & mask) === (ipToInt(range) & mask) |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Validates Brevo webhooks on the Edge |
| 20 | + * @see {@link https://help.brevo.com/hc/en-us/articles/27824932835474} |
| 21 | + * @param event H3Event |
| 22 | + * @returns {boolean} `true` if the webhook is valid, `false` otherwise |
| 23 | + */ |
| 24 | +export const isValidBrevoWebhook = async (event: H3Event): Promise<boolean> => { |
| 25 | + const ip = getRequestIP(event, { xForwardedFor: true }) |
| 26 | + |
| 27 | + if (!ip || !ALLOWED_IP_RANGES.some(cidr => isIpInRange(ip, cidr))) return false |
| 28 | + |
| 29 | + // const config = ensureConfiguration('brevo', event) // No need to ensure brevo configuration |
| 30 | + const config = useRuntimeConfig(event).webhook.brevo |
| 31 | + |
| 32 | + if (config.token) { |
| 33 | + const authorization = getRequestHeader(event, 'authorization') || '' |
| 34 | + if (!authorization.toLowerCase().startsWith('bearer ')) return false |
| 35 | + const token = authorization.slice(7) |
| 36 | + if (token !== config.token) return false |
| 37 | + } |
| 38 | + |
| 39 | + return true |
| 40 | +} |
0 commit comments