Open History to see the last commit
1// Test-only public HTTPS receiver. Never bundled into the consumer example.
2import { createHash, createPublicKey, timingSafeEqual, verify } from 'node:crypto'
3import type { JsonWebKey } from 'node:crypto'
4import { attachDatabasePool } from '@neon/functions'
5import pg from 'pg'
6
7const required = (name: string) => { const value = process.env[name]; if (!value) throw new Error(`Missing receiver setting: ${name}`); return value }
8const schema = required('DS_SCHEMA')
9if (!/^ds_test_[a-f0-9]{32}$/.test(schema)) throw new Error('Receiver only supports isolated test schemas')
10const digest = (value: string) => createHash('sha256').update(value).digest()
11const admin = digest(required('DS_RECEIVER_KEY'))
12const base = required('DS_EXPECTED_SERVER')
13const jwks = JSON.parse(required('DS_RECEIVER_JWKS')) as { keys: (JsonWebKey & { kid: string })[] }
14const keys = new Map(jwks.keys.map((key) => [key.kid, createPublicKey({ key, format: 'jwk' })]))
15const pool = new pg.Pool({ connectionString: required('DATABASE_URL'), max: 2, connectionTimeoutMillis: 5000 })
16attachDatabasePool(pool)
17process.once('SIGINT', () => { void pool.end() })
18export default {
19 async fetch(request: Request): Promise<Response> {
20 const url = new URL(request.url)
21 if (url.pathname === '/health' || url.pathname === '/deliveries') {
22 const authorization = request.headers.get('authorization') ?? ''
23 if (authorization.length > 1024 || !timingSafeEqual(digest(authorization), admin)) return new Response(null, { status: 401 })
24 if (url.pathname === '/health') return Response.json({ ready: true, build: required('DS_BUILD_HASH') })
25 const rows = await pool.query(`SELECT wake_id, payload, encode(raw_body, 'base64') AS raw_body, signature, attempts FROM "${schema}".webhook_test_deliveries WHERE subscription_id = $1 ORDER BY wake_id LIMIT 64`, [url.searchParams.get('subscription_id')])
26 return Response.json(rows.rows)
27 }
28 if (request.method !== 'POST' || !['/sync', '/async', '/retry'].includes(url.pathname)) return new Response(null, { status: 404 })
29 const signature = request.headers.get('webhook-signature') ?? ''
30 const fields = /^t=(\d{1,12}),kid=([A-Za-z0-9_-]{1,128}),ed25519=([A-Za-z0-9_-]{86})$/.exec(signature)
31 if (!fields || Math.abs(Date.now() / 1000 - Number(fields[1])) > 300 || !keys.has(fields[2]!)) return new Response(null, { status: 401 })
32 const reader = request.body?.getReader()
33 if (!reader) return new Response(null, { status: 400 })
34 const chunks: Uint8Array[] = []
35 let size = 0
36 try {
37 for (;;) {
38 const next = await reader.read()
39 if (next.done) break
40 size += next.value.length
41 if (size > 512 * 1024) { await reader.cancel(); return new Response(null, { status: 413 }) }
42 chunks.push(next.value)
43 }
44 } finally { reader.releaseLock() }
45 const raw = Buffer.concat(chunks, size)
46 if (!verify(null, Buffer.concat([Buffer.from(`${fields[1]}.`), raw]), keys.get(fields[2]!)!, Buffer.from(fields[3]!, 'base64url'))) return new Response(null, { status: 401 })
47 const payload = JSON.parse(raw.toString('utf8')) as { subscription_id: string; tenant_id: string; wake_id: string; callback_url: string }
48 if (payload.tenant_id !== 'function-a' || !/^[A-Za-z0-9_-]{1,128}$/.test(payload.subscription_id)
49 || payload.callback_url !== `${base}/__ds/subscriptions/${encodeURIComponent(payload.subscription_id)}/callback`) return new Response(null, { status: 403 })
50 const saved = await pool.query<{ attempts: number }>(`INSERT INTO "${schema}".webhook_test_deliveries (wake_id, subscription_id, payload, raw_body, signature)
51 VALUES ($1,$2,$3,$4,$5) ON CONFLICT (wake_id) DO UPDATE SET attempts = webhook_test_deliveries.attempts + 1 RETURNING attempts`,
52 [payload.wake_id, payload.subscription_id, payload, raw, signature])
53 if (url.pathname === '/retry' && saved.rows[0]!.attempts === 1) return Response.json({ done: false }, { status: 500 })
54 return Response.json({ done: url.pathname !== '/async' }, { status: url.pathname === '/async' ? 202 : 200 })
55 },
56}