Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

webhook.ts

68 lines4.0 KB

1import { lookup } from 'node:dns/promises'
2import { request as httpRequest } from 'node:http'
3import { request as httpsRequest } from 'node:https'
4import { isIP } from 'node:net'
5import type { LookupFunction } from 'node:net'
6import ipaddr from 'ipaddr.js'
7import { StreamError } from './errors.js'
8​
9export function publicWebhookAddress(address: string): boolean {
10 try {
11 let parsed = ipaddr.parse(address)
12 if (parsed.kind() === 'ipv6' && (parsed as ipaddr.IPv6).isIPv4MappedAddress()) parsed = (parsed as ipaddr.IPv6).toIPv4Address()
13 return parsed.range() === 'unicast'
14 } catch { return false }
16export async function webhookTarget(value: string, allowLocalhost: boolean): Promise<{ url: URL; address: string; family: number }> {
17 const rejected = () => new StreamError(400, 'WEBHOOK_URL_REJECTED', 'Webhook URL must target an allowed public HTTPS destination')
18 let url: URL
19 try { url = new URL(value) } catch { throw rejected() }
20 const hostname = url.hostname.replace(/^\[|\]$/g, '')
21 const localName = hostname === 'localhost' || /^127\.0\.0\.\d{1,3}$/.test(hostname)
22 const development = allowLocalhost && localName
23 if ((!development && url.protocol !== 'https:') || !['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash) throw rejected()
24 let timer: ReturnType<typeof setTimeout> | undefined
25 try {
26 const addresses = isIP(hostname) ? [{ address: hostname, family: isIP(hostname) }] : await Promise.race([
27 lookup(hostname, { all: true, verbatim: true }),
28 new Promise<never>((_, reject) => { timer = setTimeout(() => reject(rejected()), 3000) }),
29 ])
30 if (!addresses.length || addresses.some(({ address }) => !publicWebhookAddress(address) && !(development && (address === '::1' || /^127\.0\.0\.\d{1,3}$/.test(address))))) throw rejected()
31 const selected = addresses.find((address) => address.family === 4) ?? addresses[0]!
32 return { url, address: selected.address, family: selected.family }
33 } finally { clearTimeout(timer) }
35​
36/** Validate on every attempt, pin DNS through connect, preserve TLS hostname
37 * verification, never follow redirects, and bound request/response resources. */
38export async function deliverWebhook(url: string, body: Buffer, signature: string, options: { allowLocalhost: boolean; timeoutMs: number; signal?: AbortSignal }): Promise<{ ok: boolean; done: boolean }> {
39 const target = await webhookTarget(url, options.allowLocalhost)
40 return new Promise((resolve, reject) => {
41 const controller = new AbortController()
42 const timer = setTimeout(() => controller.abort(new Error('Webhook deadline exceeded')), options.timeoutMs)
43 const pinned: LookupFunction = (_hostname, lookupOptions, callback) => {
44 if (lookupOptions.all) callback(null, [{ address: target.address, family: target.family }])
45 else callback(null, target.address, target.family)
46 }
47 const send = target.url.protocol === 'https:' ? httpsRequest : httpRequest
48 const request = send(target.url, { method: 'POST', agent: false, lookup: pinned, signal: options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal,
49 headers: { 'Content-Type': 'application/json', 'Content-Length': body.length, 'Webhook-Signature': signature } }, (response) => {
50 let length = 0
51 const chunks: Buffer[] = []
52 response.on('data', (chunk: Buffer) => {
53 length += chunk.length
54 if (length > 64 * 1024) { response.destroy(new Error('Webhook response exceeds configured limit')); return }
55 chunks.push(chunk)
56 })
57 response.on('error', reject)
58 response.on('end', () => {
59 let done = false
60 try { done = (JSON.parse(Buffer.concat(chunks, length).toString('utf8')) as { done?: unknown })?.done === true } catch { /* empty/non-JSON success means asynchronous processing */ }
61 resolve({ ok: response.statusCode !== undefined && response.statusCode >= 200 && response.statusCode < 300, done })
62 })
63 })
64 request.once('error', reject)
65 request.once('close', () => clearTimeout(timer))
66 request.end(body)
67 })