fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,284 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getClient, getPool } from '@/tests/pg/setup'
import { seedCompany } from '@/tests/pg/fixtures'
// ──────────────────────────────────────────────────────────────────────
// Fixtures: parent webhook + child delivery
// ──────────────────────────────────────────────────────────────────────
async function insertWebhook(params: {
// userId kept in the signature for parity with seedCompany's return: the
// webhooks table itself has no user_id column (see route comment in
// app/api/v1/companies/[companyId]/webhooks/route.ts).
userId: string
companyId: string
eventType?: string
active?: boolean
}): Promise<string> {
void params.userId
const id = randomUUID()
await getPool().query(
`INSERT INTO public.webhooks
(id, company_id, name, event_type, webhook_url, secret, active)
VALUES ($1, $2, 'pg-test', $3, 'https://example.com/hook', $4, $5)`,
[
id,
params.companyId,
params.eventType ?? 'invoice.paid',
`whsec_${randomUUID().replace(/-/g, '')}`,
params.active ?? true,
],
)
return id
}
async function insertDelivery(params: {
webhookId: string | null
companyId: string
status?: 'pending' | 'in_flight' | 'delivered' | 'failed' | 'dead'
nextAttemptAt?: string
eventType?: string
attempts?: number
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at, attempts)
VALUES ($1, $2, $3, $4, '{"hello":"world"}'::jsonb, '2026-05-12',
$5, $6, $7)`,
[
id,
params.webhookId,
params.companyId,
params.eventType ?? 'invoice.paid',
params.status ?? 'pending',
params.nextAttemptAt ?? new Date().toISOString(),
params.attempts ?? 0,
],
)
return id
}
async function getDeliveryStatus(id: string): Promise<string | null> {
const r = await getPool().query<{ status: string }>(
`SELECT status FROM public.webhook_deliveries WHERE id = $1`,
[id],
)
return r.rows[0]?.status ?? null
}
// Direct-insert rows for one test isolation. Each it() seeds its own
// company + webhook so the dispatcher sees a clean slate; we just need to
// make sure the function only returns rows we created, which we do by
// asserting on ids.
describe('claim_due_webhook_deliveries.pg: atomic SKIP LOCKED claim', () => {
it('claims a pending row that is due', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'pending' })
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).toContain(deliveryId)
expect(await getDeliveryStatus(deliveryId)).toBe('in_flight')
})
it('claims a failed row that has reached its retry deadline', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
// next_attempt_at in the past: retry due.
const deliveryId = await insertDelivery({
webhookId,
companyId,
status: 'failed',
nextAttemptAt: new Date(Date.now() - 60_000).toISOString(),
attempts: 2,
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).toContain(deliveryId)
expect(await getDeliveryStatus(deliveryId)).toBe('in_flight')
})
it('skips a row whose next_attempt_at is still in the future', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({
webhookId,
companyId,
status: 'failed',
nextAttemptAt: new Date(Date.now() + 5 * 60_000).toISOString(),
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).not.toContain(deliveryId)
// Status stays pre-claim.
expect(await getDeliveryStatus(deliveryId)).toBe('failed')
})
it('skips dangling rows (webhook_id IS NULL)', async () => {
const { companyId } = await seedCompany()
// webhook deleted between enqueue and dispatch: FK ON DELETE SET NULL.
const deliveryId = await insertDelivery({
webhookId: null,
companyId,
status: 'pending',
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).not.toContain(deliveryId)
})
it('skips terminal-status rows', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveredId = await insertDelivery({
webhookId,
companyId,
status: 'delivered',
})
const deadId = await insertDelivery({
webhookId,
companyId,
status: 'dead',
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
const ids = rows.map((r) => r.id)
expect(ids).not.toContain(deliveredId)
expect(ids).not.toContain(deadId)
})
// The status filter `IN ('pending', 'failed')` is what prevents
// double-delivery once a tick has already claimed a row to in_flight.
// recoverStuckInFlight is the ONLY legitimate path back from in_flight
// (sweeps the row to 'failed' after the stuck-threshold), so the claim
// function must NEVER re-pick a row already marked in_flight.
it('skips rows already in in_flight status', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const inFlightId = await insertDelivery({
webhookId,
companyId,
status: 'in_flight',
})
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(rows.map((r) => r.id)).not.toContain(inFlightId)
// Status must NOT have been re-flipped.
expect(await getDeliveryStatus(inFlightId)).toBe('in_flight')
})
it('respects the batch size', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const ids = await Promise.all(
Array.from({ length: 5 }, () =>
insertDelivery({ webhookId, companyId, status: 'pending' }),
),
)
const { rows } = await getPool().query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[2],
)
expect(rows.length).toBe(2)
// The 3 unclaimed rows stay pending.
const unclaimed = ids.filter((id) => !rows.some((r) => r.id === id))
for (const id of unclaimed) {
expect(await getDeliveryStatus(id)).toBe('pending')
}
})
it('rejects out-of-range batch sizes', async () => {
await expect(
getPool().query(`SELECT * FROM public.claim_due_webhook_deliveries($1, now())`, [0]),
).rejects.toThrow(/p_batch_size must be in/i)
await expect(
getPool().query(`SELECT * FROM public.claim_due_webhook_deliveries($1, now())`, [-1]),
).rejects.toThrow(/p_batch_size must be in/i)
await expect(
getPool().query(`SELECT * FROM public.claim_due_webhook_deliveries($1, now())`, [10000]),
).rejects.toThrow(/p_batch_size must be in/i)
})
// SKIP LOCKED is the entire point of this migration. Two transactions
// calling the function at the same moment must not both see the same
// row: the row locked by the first caller is invisible to the second,
// closing the duplicate-delivery window the old SELECT-then-UPDATE-
// intersect pattern documented as load-bearing.
it('SKIP LOCKED: a concurrent caller does not see rows locked by an in-flight transaction', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({
webhookId,
companyId,
status: 'pending',
})
const a = await getClient()
const b = await getClient()
try {
await a.query('BEGIN')
await b.query('BEGIN')
// A claims first. The row is now status='in_flight' AND held under
// a row lock by transaction A (UPDATE sets ROW EXCLUSIVE).
const aClaim = await a.query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(aClaim.rows.map((r) => r.id)).toContain(deliveryId)
// B's call SKIPs the locked row entirely. Without SKIP LOCKED this
// call would BLOCK on the row lock; the test would hang and only
// fail via testTimeout. SKIP LOCKED makes it return promptly with
// the row simply absent from results.
const bClaim = await b.query<{ id: string }>(
`SELECT id FROM public.claim_due_webhook_deliveries($1, now())`,
[10],
)
expect(bClaim.rows.map((r) => r.id)).not.toContain(deliveryId)
// Commit A and roll back B (no-op since B claimed nothing).
await a.query('COMMIT')
await b.query('ROLLBACK')
} finally {
a.release()
b.release()
}
// Final state: row is in_flight, claimed exactly once.
expect(await getDeliveryStatus(deliveryId)).toBe('in_flight')
})
})
@@ -0,0 +1,126 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(() => ({ __client: true })),
}))
// `after` is a no-op outside a request scope in these tests; the module falls
// back to a floating promise, which is the path a plain node server takes too.
vi.mock('next/server', () => ({
after: () => {
throw new Error('after() called outside a request scope')
},
}))
import { kickWebhookDispatch, resetKickStateForTests, KICK_BATCH_SIZE } from '../dispatch-kick'
/**
* A zero DispatchSummary. Spread rather than repeated so adding a counter to
* the summary does not mean re-editing every case in this file; these tests
* are about scheduling and coalescing, never about the counts.
*/
const EMPTY_SUMMARY = {
picked: 0,
delivered: 0,
failed: 0,
dead: 0,
skipped: 0,
released: 0,
recovered: 0,
recoveredDead: 0,
}
/** Resolves after the microtask queue drains, so floating work has run. */
const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
beforeEach(() => {
vi.clearAllMocks()
resetKickStateForTests()
})
describe('kickWebhookDispatch', () => {
it('runs one dispatch cycle with the small kick batch size', async () => {
const dispatch = vi.fn().mockResolvedValue({ ...EMPTY_SUMMARY, picked: 1, delivered: 1 })
kickWebhookDispatch(dispatch)
await flush()
expect(dispatch).toHaveBeenCalledTimes(1)
expect(dispatch.mock.calls[0][0]).toMatchObject({ batchSize: KICK_BATCH_SIZE })
})
it('claims far fewer rows than the cron, so a backlog cannot own a request tail', () => {
// Each delivery can burn the full 10 s receiver timeout; the cron's 50 is
// fine on a dedicated invocation, not on the tail of a user request.
expect(KICK_BATCH_SIZE).toBeLessThan(50)
})
it('returns synchronously: the emitter never waits on receiver HTTP', async () => {
let settled = false
const dispatch = vi.fn(
() =>
new Promise((resolve) => {
setTimeout(() => {
settled = true
resolve({ ...EMPTY_SUMMARY })
}, 20)
}),
)
const returned = kickWebhookDispatch(dispatch as never)
// eventBus.emit awaits its subscribers, so a kick that blocked here would
// put a stranger's slow endpoint on the critical path of committing a
// verifikat.
expect(returned).toBeUndefined()
expect(settled).toBe(false)
await new Promise((resolve) => setTimeout(resolve, 40))
expect(settled).toBe(true)
})
it('coalesces a burst of kicks into a single cycle', async () => {
// A bulk booking emits once per row. Without coalescing, 100 rows would
// mean 100 claim round trips against the same handful of due deliveries.
const dispatch = vi.fn().mockResolvedValue({ ...EMPTY_SUMMARY })
for (let i = 0; i < 100; i++) kickWebhookDispatch(dispatch)
await flush()
expect(dispatch).toHaveBeenCalledTimes(1)
})
it('accepts a new kick once the previous cycle has started', async () => {
const dispatch = vi.fn().mockResolvedValue({ ...EMPTY_SUMMARY })
kickWebhookDispatch(dispatch)
await flush()
kickWebhookDispatch(dispatch)
await flush()
expect(dispatch).toHaveBeenCalledTimes(2)
})
it('swallows a dispatch failure: a failed kick is latency, not a lost delivery', async () => {
const dispatch = vi.fn().mockRejectedValue(new Error('receiver unreachable'))
expect(() => kickWebhookDispatch(dispatch)).not.toThrow()
await flush()
expect(dispatch).toHaveBeenCalledTimes(1)
})
it('does not wedge the coalescing flag when a cycle fails', async () => {
// The cron still covers every row, but a stuck flag would silently
// disable the fast path for the life of the function instance.
const failing = vi.fn().mockRejectedValue(new Error('boom'))
kickWebhookDispatch(failing)
await flush()
const ok = vi.fn().mockResolvedValue({ ...EMPTY_SUMMARY })
kickWebhookDispatch(ok)
await flush()
expect(ok).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,231 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { PinnedFetchResult } from '../pinned-fetch'
// Mock the logger so the warn-vs-error level can be asserted: the real logger
// suppresses warn in the test environment, and the point of this suite is that
// a dropped audit row surfaces at error level (which always forwards to the
// observability sink) rather than being swallowed.
const { logWarn, logError } = vi.hoisted(() => ({
logWarn: vi.fn(),
logError: vi.fn(),
}))
vi.mock('@/lib/logger', () => ({
createLogger: () => ({
info: vi.fn(),
warn: logWarn,
error: logError,
child: vi.fn(),
}),
}))
// Import after mocks
import { dispatchDueDeliveries } from '../dispatcher'
const COMPANY_ID = '11111111-1111-4111-8111-111111111111'
const WEBHOOK_ID = '22222222-2222-4222-8222-222222222222'
const DELIVERY_ID = '33333333-3333-4333-8333-333333333333'
interface Recorded {
auditInserts: Record<string, unknown>[]
webhookUpdates: Record<string, unknown>[]
webhookSelects: string[]
}
/**
* Minimal Supabase stub shaped to the exact call chains the dispatcher uses.
* `webhooksSelectResult` lets a test simulate the PostgREST 42703 that a
* phantom column would produce, so the audit row's company scope can be
* proven independent of the prior-state snapshot.
*/
function makeSupabase(opts: {
auditInsertError?: { message: string; code: string } | null
priorSnapshotError?: { message: string; code: string } | null
} = {}): { client: SupabaseClient; recorded: Recorded } {
const recorded: Recorded = { auditInserts: [], webhookUpdates: [], webhookSelects: [] }
const client = {
rpc: vi.fn(async (fn: string) => {
if (fn === 'claim_due_webhook_deliveries') {
return {
data: [
{
id: DELIVERY_ID,
webhook_id: WEBHOOK_ID,
company_id: COMPANY_ID,
event_type: 'invoice.paid',
payload: { id: 'inv-1' },
previous_attributes: null,
api_version: '2026-05-12',
attempts: 0,
},
],
error: null,
}
}
return { data: null, error: null }
}),
from: vi.fn((table: string) => {
if (table === 'audit_log') {
return {
insert: vi.fn(async (row: Record<string, unknown>) => {
recorded.auditInserts.push(row)
return { error: opts.auditInsertError ?? null }
}),
}
}
if (table === 'webhook_deliveries') {
// update(...).eq(...) -> markDead / markDelivered
// update(...).eq('id').eq('status').select('id') -> touchInFlight
//
// The touch must resolve to a NON-empty row set: an empty result means
// "this delivery is no longer ours" and the dispatcher skips the
// attempt, which would take the 410 auto-disable path out of reach.
// The stuck sweep no longer runs through this chain at all; it goes
// through rpc('recover_stuck_webhook_deliveries').
const thenable = {
eq: () => thenable,
select: async () => ({ data: [{ id: DELIVERY_ID }], error: null }),
then: (resolve: (v: { error: null }) => unknown) => resolve({ error: null }),
}
return { update: () => thenable }
}
if (table === 'webhooks') {
return {
select: (cols: string) => {
recorded.webhookSelects.push(cols)
return {
// loadWebhooksByIds
in: async () => ({
data: [
{
id: WEBHOOK_ID,
company_id: COMPANY_ID,
webhook_url: 'https://receiver.example.com/hook',
secret: 'whsec_test',
},
],
error: null,
}),
// disableWebhook prior-state snapshot
eq: () => ({
maybeSingle: async () =>
opts.priorSnapshotError
? { data: null, error: opts.priorSnapshotError }
: {
data: {
company_id: COMPANY_ID,
name: 'Payments receiver',
active: true,
disabled_at: null,
disabled_reason: null,
},
error: null,
},
}),
}
},
update: (row: Record<string, unknown>) => {
recorded.webhookUpdates.push(row)
return { eq: async () => ({ error: null }) }
},
}
}
throw new Error(`unexpected table: ${table}`)
}),
} as unknown as SupabaseClient
return { client, recorded }
}
/** Receiver responds 410 Gone: the auto-disable path. */
const gone410 = async (): Promise<PinnedFetchResult> => ({
kind: 'ok',
status: 410,
headers: { 'content-type': 'application/json' },
body: '{}',
bodyTruncated: false,
pinnedAddress: '93.184.216.34',
})
describe('dispatcher auto-disable audit row', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('writes a company-scoped SECURITY_EVENT row attributed to the system dispatcher', async () => {
const { client, recorded } = makeSupabase()
const summary = await dispatchDueDeliveries({
supabase: client,
pinnedFetchImpl: gone410 as never,
})
expect(summary.dead).toBe(1)
expect(recorded.webhookUpdates[0]).toMatchObject({ active: false, disabled_reason: 'http_410_gone' })
expect(recorded.auditInserts).toHaveLength(1)
const audit = recorded.auditInserts[0]
expect(audit).toMatchObject({
company_id: COMPANY_ID,
action: 'SECURITY_EVENT',
table_name: 'webhooks',
record_id: WEBHOOK_ID,
user_id: null,
actor_id: null,
actor_type: 'system',
actor_label: 'webhook-dispatcher',
})
expect(audit.description).toContain('http_410_gone')
expect(audit.old_state).toMatchObject({ active: true })
})
it('never selects a user_id column from webhooks (no such column exists)', async () => {
const { client, recorded } = makeSupabase()
await dispatchDueDeliveries({ supabase: client, pinnedFetchImpl: gone410 as never })
expect(recorded.webhookSelects.length).toBeGreaterThan(0)
for (const cols of recorded.webhookSelects) {
expect(cols).not.toContain('user_id')
}
})
it('keeps the audit row company-scoped when the prior-state snapshot read fails', async () => {
const { client, recorded } = makeSupabase({
priorSnapshotError: { message: 'column webhooks.x does not exist', code: '42703' },
})
await dispatchDueDeliveries({ supabase: client, pinnedFetchImpl: gone410 as never })
expect(recorded.auditInserts).toHaveLength(1)
const audit = recorded.auditInserts[0]
expect(audit.company_id).toBe(COMPANY_ID)
expect(audit.actor_type).toBe('system')
expect(audit.old_state).toBeNull()
expect(audit.description).toContain('prior snapshot unavailable')
})
it('surfaces a failed audit insert at error level rather than swallowing it', async () => {
const { client } = makeSupabase({
auditInsertError: { message: 'insert denied', code: '42501' },
})
await dispatchDueDeliveries({ supabase: client, pinnedFetchImpl: gone410 as never })
expect(logError).toHaveBeenCalledWith(
'audit_log insert failed for webhook auto-disable',
expect.any(Error),
expect.objectContaining({ webhookId: WEBHOOK_ID, companyId: COMPANY_ID, reason: 'http_410_gone' }),
)
// Must not degrade to warn: warn is suppressed in test and never reaches
// the observability sink, which is what made the gap silent.
expect(logWarn).not.toHaveBeenCalledWith(
'audit_log insert failed for webhook auto-disable',
expect.anything(),
)
})
})
@@ -0,0 +1,470 @@
/**
* Stuck-in_flight recovery and per-row re-stamping (#1257).
*
* Two defects are pinned here:
*
* 1. the sweep window used to be a fixed 2x REQUEST_TIMEOUT_MS (20 s), which
* is shorter than a single serial cycle, so cycle N recovered rows cycle
* N-1 was still working through;
* 2. recovery reset rows to 'failed' without charging an attempt, so
* MAX_ATTEMPTS stopped being a real cap.
*
* The window is now derived from the bounded cycle and the cap is enforced
* server-side by recover_stuck_webhook_deliveries, so the assertions here are
* about what the dispatcher hands the RPC and about the per-row re-stamp that
* makes a row's in_flight age measure its own attempt.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { PinnedFetchResult } from '../pinned-fetch'
vi.mock('@/lib/logger', () => ({
createLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
child: vi.fn(),
}),
}))
// Import after mocks
import { dispatchDueDeliveries, __TESTING__ } from '../dispatcher'
const COMPANY_ID = '11111111-1111-4111-8111-111111111111'
const WEBHOOK_ID = '22222222-2222-4222-8222-222222222222'
const DELIVERY_IDS = [
'aaaaaaaa-0001-4000-8000-000000000001',
'aaaaaaaa-0002-4000-8000-000000000002',
'aaaaaaaa-0003-4000-8000-000000000003',
]
/** Fixed clock so the derived window is exactly assertable. */
const NOW = new Date('2026-07-30T10:00:00.000Z')
interface RecordedUpdate {
payload: Record<string, unknown>
filters: Record<string, unknown>
}
interface Recorded {
rpcCalls: { fn: string; args: Record<string, unknown> }[]
deliveryUpdates: RecordedUpdate[]
}
/**
* Ordered-log Supabase stub in the same house style as
* dispatcher-auto-disable.test.ts. Every write against webhook_deliveries is
* appended to `deliveryUpdates` in the order it resolves, so the interleaving
* of touch writes and terminal writes is directly assertable.
*
* `lostOwnership` makes a specific delivery's touch resolve to zero rows,
* which is how the real table reports "another cycle owns this row now".
*/
function makeSupabase(opts: {
deliveryCount?: number
attempts?: number
lostOwnership?: Set<string>
/** Rows the sweep RPC reports as recovered this tick. */
recovered?: Array<{ id: string; status: string; attempts: number }>
} = {}): { client: SupabaseClient; recorded: Recorded } {
const recorded: Recorded = { rpcCalls: [], deliveryUpdates: [] }
const count = opts.deliveryCount ?? 1
const client = {
rpc: vi.fn(async (fn: string, args: Record<string, unknown>) => {
recorded.rpcCalls.push({ fn, args })
if (fn === 'claim_due_webhook_deliveries') {
return {
data: DELIVERY_IDS.slice(0, count).map((id) => ({
id,
webhook_id: WEBHOOK_ID,
company_id: COMPANY_ID,
event_type: 'invoice.paid',
payload: { id: 'inv-1' },
previous_attributes: null,
api_version: '2026-05-12',
attempts: opts.attempts ?? 0,
})),
error: null,
}
}
// recover_stuck_webhook_deliveries: nothing stuck unless a case says so.
return { data: opts.recovered ?? [], error: null }
}),
from: vi.fn((table: string) => {
if (table === 'webhook_deliveries') {
return {
update: (payload: Record<string, unknown>) => {
const filters: Record<string, unknown> = {}
const rec: RecordedUpdate = { payload, filters }
const chain: Record<string, unknown> = {
eq: (col: string, val: unknown) => {
filters[col] = val
return chain
},
in: (col: string, val: unknown) => {
filters[col] = val
return chain
},
// touchInFlight terminates with .select('id')
select: async () => {
recorded.deliveryUpdates.push(rec)
const id = filters.id as string
const lost = opts.lostOwnership?.has(id) ?? false
return { data: lost ? [] : [{ id }], error: null }
},
// markDelivered / markDead / markFailedForRetry await the chain
then: (resolve: (v: { error: null }) => unknown) => {
recorded.deliveryUpdates.push(rec)
return resolve({ error: null })
},
}
return chain
},
}
}
if (table === 'webhooks') {
return {
select: () => ({
in: async () => ({
data: [
{
id: WEBHOOK_ID,
company_id: COMPANY_ID,
webhook_url: 'https://receiver.example.com/hook',
secret: 'whsec_test',
},
],
error: null,
}),
}),
}
}
throw new Error(`unexpected table: ${table}`)
}),
} as unknown as SupabaseClient
return { client, recorded }
}
/** Receiver answers 200 and records which delivery ids were actually POSTed. */
function makeOkFetch(postedIds: string[]) {
return async (
_url: string,
init: { headers: Record<string, string> },
): Promise<PinnedFetchResult> => {
postedIds.push(init.headers['X-Gnubok-Delivery'])
return {
kind: 'ok',
status: 200,
headers: { 'content-type': 'application/json' },
body: '{"ok":true}',
bodyTruncated: false,
pinnedAddress: '93.184.216.34',
}
}
}
function recoverArgs(recorded: Recorded): Record<string, unknown> {
const call = recorded.rpcCalls.find((c) => c.fn === 'recover_stuck_webhook_deliveries')
if (!call) throw new Error('recover_stuck_webhook_deliveries was never called')
return call.args
}
describe('dispatcher stuck-in_flight recovery window', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('derives a window wider than one bounded cycle, so a mid-cycle row cannot be swept', async () => {
const { client, recorded } = makeSupabase()
await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
const args = recoverArgs(recorded)
const windowMs = NOW.getTime() - Date.parse(args.p_stuck_before as string)
// The cycle budget (what actually bounds a cycle, whatever its batch size)
// plus one in-flight request plus slack. Spelled out as a literal as well
// as a derivation so a change to any constant has to be deliberate.
expect(windowMs).toBe(160_000)
expect(windowMs).toBe(
__TESTING__.CYCLE_BUDGET_MS +
__TESTING__.REQUEST_TIMEOUT_MS +
__TESTING__.STUCK_RECOVERY_SLACK_MS,
)
// The old threshold. A concurrent tick must no longer be able to re-arm a
// row that a live cycle claimed only a couple of attempts ago.
expect(windowMs).toBeGreaterThan(__TESTING__.REQUEST_TIMEOUT_MS * 2)
// And it must cover the whole bounded cycle, not just part of it.
expect(windowMs).toBeGreaterThan(__TESTING__.CYCLE_BUDGET_MS)
expect(args.p_now).toBe(NOW.toISOString())
})
it('uses the same window for the 5-row kick as for the 50-row cron', async () => {
const windows: number[] = []
for (const batchSize of [5, __TESTING__.DEFAULT_BATCH_SIZE, 500]) {
const { client, recorded } = makeSupabase()
await dispatchDueDeliveries({
supabase: client,
batchSize,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
windows.push(NOW.getTime() - Date.parse(recoverArgs(recorded).p_stuck_before as string))
}
// The sweep is tenant-global, so a small batch must not shrink the window
// and a large one must not stretch it: the cycle budget bounds every
// caller alike. A batch-derived window (the pre-#1257 shape, and the shape
// a "floor at DEFAULT_BATCH_SIZE" would silently allow again above 50)
// would produce 50_000 here for the kick and 160_000 for the cron.
expect(windows).toEqual([160_000, 160_000, 160_000])
})
it('hands the attempts cap and the retry schedule to the RPC', async () => {
const { client, recorded } = makeSupabase()
await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
const args = recoverArgs(recorded)
// The cap stays single-sourced in TS; the increment happens in SQL, which
// is the only place `attempts = attempts + 1` can be expressed atomically.
expect(args.p_max_attempts).toBe(__TESTING__.MAX_ATTEMPTS)
expect(__TESTING__.MAX_ATTEMPTS).toBe(8)
// And so does the backoff: a swept row must wait exactly as long as a row
// whose receiver answered 500. Re-arming at p_now let a repeatedly
// stranded delivery spend all 8 attempts inside half an hour and land in
// the terminal, immutable 'dead' state without ever being contacted.
expect(args.p_backoff).toEqual([...__TESTING__.RETRY_BACKOFF_SECONDS])
expect(args.p_backoff).toEqual([60, 300, 1800, 7200, 43200, 86400, 172800])
})
it('surfaces the sweep outcome in the summary, dead rows separately', async () => {
const { client } = makeSupabase({
recovered: [
{ id: DELIVERY_IDS[0], status: 'failed', attempts: 2 },
{ id: DELIVERY_IDS[1], status: 'dead', attempts: 8 },
{ id: DELIVERY_IDS[2], status: 'dead', attempts: 8 },
],
})
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
// A tick that takes deliveries terminal has to be visible in the cron's
// own summary line, not only in a helper-level log.warn.
expect(summary.recovered).toBe(3)
expect(summary.recoveredDead).toBe(2)
})
})
describe('dispatcher per-row in_flight re-stamp', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('re-stamps each row immediately before its own attempt, not once at claim time', async () => {
const { client, recorded } = makeSupabase({ deliveryCount: 3 })
const posted: string[] = []
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch(posted) as never,
})
expect(summary.delivered).toBe(3)
expect(posted).toEqual(DELIVERY_IDS)
// touch, terminal, touch, terminal, touch, terminal. A single re-stamp at
// claim time (the pre-fix behaviour) would leave only the three terminal
// writes here, and rows 2 and 3 would carry the claim's updated_at into
// the next cycle's sweep window.
expect(recorded.deliveryUpdates).toHaveLength(6)
for (let i = 0; i < 3; i++) {
const touch = recorded.deliveryUpdates[i * 2]
expect(touch.payload).toEqual({ status: 'in_flight' })
expect(touch.filters).toEqual({ id: DELIVERY_IDS[i], status: 'in_flight' })
const terminal = recorded.deliveryUpdates[i * 2 + 1]
expect(terminal.payload).toMatchObject({ status: 'delivered' })
expect(terminal.filters).toEqual({ id: DELIVERY_IDS[i] })
}
})
it('drops the POST when the touch shows the row is no longer ours', async () => {
const { client, recorded } = makeSupabase({
deliveryCount: 3,
lostOwnership: new Set([DELIVERY_IDS[1]]),
})
const posted: string[] = []
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch(posted) as never,
})
// The duplicate POST is what the issue calls avoidable load: the loser of
// the race would have had its terminal write swallowed by the immutability
// trigger anyway.
expect(posted).toEqual([DELIVERY_IDS[0], DELIVERY_IDS[2]])
expect(posted).not.toContain(DELIVERY_IDS[1])
expect(summary.skipped).toBe(1)
expect(summary.delivered).toBe(2)
// No terminal write for the row we no longer own.
const terminalForRow2 = recorded.deliveryUpdates.filter(
(u) => u.filters.id === DELIVERY_IDS[1] && u.payload.status !== 'in_flight',
)
expect(terminalForRow2).toHaveLength(0)
})
it('reconciles the summary: picked === delivered + failed + dead + skipped + released', async () => {
const { client } = makeSupabase({
deliveryCount: 3,
lostOwnership: new Set([DELIVERY_IDS[2]]),
})
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: makeOkFetch([]) as never,
})
expect(summary.picked).toBe(3)
expect(
summary.delivered + summary.failed + summary.dead + summary.skipped + summary.released,
).toBe(summary.picked)
})
})
describe('dispatcher cycle budget', () => {
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
vi.restoreAllMocks()
})
it('hands back unattempted claims instead of stranding them in in_flight', async () => {
const { client, recorded } = makeSupabase({ deliveryCount: 3 })
const posted: string[] = []
// `Date.now` is the dispatcher's only real-clock read (the injected `now`
// covers everything else), so driving it directly is enough to simulate a
// receiver that ate the whole budget on the first row.
let clock = 1_000_000
vi.spyOn(Date, 'now').mockImplementation(() => clock)
const slowFetch = async (
_url: string,
init: { headers: Record<string, string> },
): Promise<PinnedFetchResult> => {
posted.push(init.headers['X-Gnubok-Delivery'])
clock += __TESTING__.CYCLE_BUDGET_MS
return {
kind: 'ok',
status: 200,
headers: { 'content-type': 'application/json' },
body: '{"ok":true}',
bodyTruncated: false,
pinnedAddress: '93.184.216.34',
}
}
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: slowFetch as never,
})
// Row 1 fits, rows 2 and 3 do not: they are released, not POSTed.
expect(posted).toEqual([DELIVERY_IDS[0]])
expect(summary.delivered).toBe(1)
expect(summary.released).toBe(2)
expect(summary.picked).toBe(3)
// Released rows go back to a re-claimable state immediately. Without this
// they would sit in in_flight for the full 160 s window before any sweep
// could re-arm them, and the sweep would then charge them an attempt they
// never made.
//
// 'pending', not 'failed': these rows carry attempts = 0, so they had
// never been attempted and their pre-claim status was necessarily
// 'pending'. webhook_deliveries is customer-visible behandlingshistorik;
// a delivery that was claimed and handed back without a single POST must
// not read as a failure there.
const release = recorded.deliveryUpdates.at(-1)
expect(release?.payload).toEqual({
status: 'pending',
next_attempt_at: NOW.toISOString(),
})
expect(release?.filters).toEqual({
id: [DELIVERY_IDS[1], DELIVERY_IDS[2]],
status: 'in_flight',
})
// Not an attempt: `attempts` must not be bumped and the previous attempt's
// diagnostic must survive.
expect(release?.payload).not.toHaveProperty('attempts')
expect(release?.payload).not.toHaveProperty('error')
})
it('releases a previously attempted row back to failed, not pending', async () => {
const { client, recorded } = makeSupabase({ deliveryCount: 3, attempts: 2 })
const posted: string[] = []
let clock = 1_000_000
vi.spyOn(Date, 'now').mockImplementation(() => clock)
const slowFetch = async (
_url: string,
init: { headers: Record<string, string> },
): Promise<PinnedFetchResult> => {
posted.push(init.headers['X-Gnubok-Delivery'])
clock += __TESTING__.CYCLE_BUDGET_MS
return {
kind: 'ok',
status: 200,
headers: { 'content-type': 'application/json' },
body: '{"ok":true}',
bodyTruncated: false,
pinnedAddress: '93.184.216.34',
}
}
const summary = await dispatchDueDeliveries({
supabase: client,
now: NOW,
pinnedFetchImpl: slowFetch as never,
})
expect(summary.released).toBe(2)
// attempts > 0 means the row was already in the retry loop before this
// cycle claimed it, so 'failed' is its real pre-claim status.
const release = recorded.deliveryUpdates.at(-1)
expect(release?.payload).toEqual({
status: 'failed',
next_attempt_at: NOW.toISOString(),
})
})
})
@@ -0,0 +1,29 @@
/**
* registerWebhookHandler() must subscribe to exactly the catalogue in
* lib/webhooks/public-events.ts: an event an agent can subscribe to via the
* API but that the handler never fans out would be silently undeliverable.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(() => ({ __client: true })),
}))
vi.mock('next/server', () => ({ after: vi.fn() }))
import { eventBus } from '@/lib/events/bus'
import { registerWebhookHandler } from '../handler'
import { PUBLIC_WEBHOOK_EVENTS } from '../public-events'
describe('registerWebhookHandler', () => {
beforeEach(() => {
eventBus.clear()
vi.clearAllMocks()
})
it('subscribes to every catalogued event type and nothing else', () => {
const on = vi.spyOn(eventBus, 'on')
registerWebhookHandler()
const subscribed = on.mock.calls.map(([eventType]) => eventType).sort()
expect(subscribed).toEqual([...PUBLIC_WEBHOOK_EVENTS].sort())
})
})
+271
View File
@@ -0,0 +1,271 @@
import { describe, expect, it, vi } from 'vitest'
import { EventEmitter } from 'node:events'
import type { ClientRequest, IncomingMessage } from 'node:http'
import type { RequestOptions } from 'node:https'
import { pinnedHttpsFetch } from '@/lib/webhooks/pinned-fetch'
// Stand up a minimal stub for node:https.request that captures the args
// we want to assert on (pinned IP, SNI, Host header) and lets us synthesise
// a controlled response back to the caller.
function makeStubRequest(args: {
status: number
headers?: Record<string, string>
body?: string
emitError?: Error
emitTimeout?: boolean
}) {
const captured: {
options: RequestOptions | null
bodyWritten: string
} = { options: null, bodyWritten: '' }
const fakeRequest = (
options: RequestOptions,
callback: (res: IncomingMessage) => void,
): ClientRequest => {
captured.options = options
const req = new EventEmitter() as ClientRequest & EventEmitter
// ClientRequest API surface we touch in pinned-fetch:
req.write = ((chunk: string) => {
captured.bodyWritten += chunk
return true
}) as ClientRequest['write']
req.end = (() => {
// Dispatch the response (or error) asynchronously to mimic real
// network timing: pinned-fetch attaches handlers BEFORE end().
queueMicrotask(() => {
if (args.emitError) {
req.emit('error', args.emitError)
return
}
if (args.emitTimeout) {
req.emit('timeout')
return
}
const res = new EventEmitter() as IncomingMessage & EventEmitter
;(res as unknown as { statusCode: number }).statusCode = args.status
;(res as unknown as { headers: Record<string, string> }).headers =
args.headers ?? { 'content-type': 'application/json' }
// IncomingMessage stubs need stream-shaped methods that pinned-fetch
// calls (resume on redirect-drain, destroy on size truncation).
;(res as unknown as { resume: () => unknown }).resume = () => {
/* no-op: body is already buffered in args.body */
}
;(res as unknown as { destroy: () => unknown }).destroy = () => {
// Truncation path: emit `close` so finalize() runs.
queueMicrotask(() => res.emit('close'))
}
callback(res)
// Emit body bytes then `end`.
queueMicrotask(() => {
if (args.body) res.emit('data', Buffer.from(args.body, 'utf8'))
res.emit('end')
})
})
return req
}) as ClientRequest['end']
req.destroy = (() => {
// no-op: tests don't read the socket after destroy.
return req
}) as ClientRequest['destroy']
req.setTimeout = (() => req) as ClientRequest['setTimeout']
return req
}
return { captured, fakeRequest }
}
function makeStubValidator(addresses: string[]) {
return vi.fn(async () => ({
ok: true as const,
hostname: 'example.com',
resolvedAddresses: addresses,
}))
}
describe('pinnedHttpsFetch', () => {
it('pins the socket to the validated IP while keeping SNI + Host on the hostname', async () => {
const { captured, fakeRequest } = makeStubRequest({
status: 200,
body: 'ok',
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{
method: 'POST',
headers: { 'X-Gnubok-Event': 'invoice.paid' },
body: '{"hello":"world"}',
timeoutMs: 1000,
maxResponseBytes: 1024,
},
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('ok')
if (result.kind !== 'ok') throw new Error('unreachable')
expect(result.status).toBe(200)
expect(result.body).toBe('ok')
expect(result.pinnedAddress).toBe('203.0.113.42')
// Socket goes to the IP: DNS does not re-resolve.
expect(captured.options?.host).toBe('203.0.113.42')
// SNI carries the hostname so the receiver's TLS cert validates.
expect(captured.options?.servername).toBe('example.com')
// HTTP Host header carries the hostname for vhost routing.
const headers = captured.options?.headers as Record<string, string>
expect(headers.host).toBe('example.com')
// Custom dispatcher header survives.
expect(headers['X-Gnubok-Event']).toBe('invoice.paid')
expect(captured.bodyWritten).toBe('{"hello":"world"}')
})
it('includes the port in the Host header when non-default', async () => {
const { captured, fakeRequest } = makeStubRequest({ status: 204 })
await pinnedHttpsFetch(
'https://example.com:8443/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(captured.options?.port).toBe(8443)
const headers = captured.options?.headers as Record<string, string>
expect(headers.host).toBe('example.com:8443')
})
it('returns unsafe_url when validation rejects the hostname', async () => {
const { fakeRequest } = makeStubRequest({ status: 200 })
const spyRequest = vi.fn(fakeRequest)
const validator = vi.fn(async () => ({
ok: false as const,
reason: 'private_address' as const,
detail: '10.0.0.1 is private',
}))
const result = await pinnedHttpsFetch(
'https://internal.example/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{ validateUrl: validator, httpsRequest: spyRequest },
)
expect(result.kind).toBe('unsafe_url')
if (result.kind === 'unsafe_url') {
expect(result.reason).toBe('private_address')
expect(result.pinnedAddress).toBeNull()
}
// Critically: we never opened a socket.
expect(spyRequest).not.toHaveBeenCalled()
})
it('treats 3xx responses as redirect_blocked', async () => {
const { fakeRequest } = makeStubRequest({
status: 302,
headers: { location: 'https://elsewhere.example/' },
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('redirect_blocked')
if (result.kind === 'redirect_blocked') {
expect(result.status).toBe(302)
expect(result.pinnedAddress).toBe('203.0.113.42')
}
})
it('maps transport errors to transport_error', async () => {
const { fakeRequest } = makeStubRequest({
status: 0,
emitError: new Error('ECONNREFUSED 203.0.113.42:443'),
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('transport_error')
if (result.kind === 'transport_error') {
expect(result.detail).toContain('ECONNREFUSED')
expect(result.pinnedAddress).toBe('203.0.113.42')
}
})
it('maps timeout events to timeout', async () => {
const { fakeRequest } = makeStubRequest({
status: 0,
emitTimeout: true,
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('timeout')
})
it('truncates response body at maxResponseBytes', async () => {
const big = 'x'.repeat(10_000)
const { fakeRequest } = makeStubRequest({
status: 200,
headers: { 'content-type': 'text/plain' },
body: big,
})
const result = await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 100 },
{
validateUrl: makeStubValidator(['203.0.113.42']),
httpsRequest: fakeRequest,
},
)
expect(result.kind).toBe('ok')
if (result.kind === 'ok') {
expect(result.body.length).toBe(100)
expect(result.bodyTruncated).toBe(true)
}
})
it('picks the first resolved IP deterministically', async () => {
const { captured, fakeRequest } = makeStubRequest({ status: 200 })
await pinnedHttpsFetch(
'https://example.com/hooks',
{ method: 'POST', headers: {}, body: '', timeoutMs: 1000, maxResponseBytes: 1024 },
{
validateUrl: makeStubValidator(['203.0.113.42', '198.51.100.55']),
httpsRequest: fakeRequest,
},
)
// First entry, not the second, not random.
expect(captured.options?.host).toBe('203.0.113.42')
})
})
@@ -0,0 +1,47 @@
/**
* The webhook event catalogue (lib/webhooks/public-events.ts) is the single
* source for three surfaces that used to be hand-copied and drifted (24 vs
* 28 events): the v1 create schema (and so the OpenAPI spec and the generated
* agent skill), the docs page, and the fan-out handler. These tests pin each
* surface back to the catalogue so a re-hardcoded list fails CI.
*/
import { describe, expect, it } from 'vitest'
import { PUBLIC_WEBHOOK_EVENTS, PUBLIC_WEBHOOK_EVENT_GROUPS } from '../public-events'
import { WEBHOOKS_MD } from '@/lib/docs/content/webhooks'
import { generateOpenApiSpec } from '@/lib/api/v1/registry'
// Side-effect import: populates the endpoint registry from every route file.
import '@/lib/api/v1/load-routes'
describe('public webhook event catalogue', () => {
it('has no duplicate event types and no empty groups', () => {
expect(new Set(PUBLIC_WEBHOOK_EVENTS).size).toBe(PUBLIC_WEBHOOK_EVENTS.length)
for (const group of PUBLIC_WEBHOOK_EVENT_GROUPS) expect(group.events.length).toBeGreaterThan(0)
})
it('includes the reconciliation events the handler delivers', () => {
expect(PUBLIC_WEBHOOK_EVENTS).toEqual(
expect.arrayContaining([
'reconciliation.matched',
'reconciliation.unmatched',
'reconciliation.signed_off',
'reconciliation.reopened',
]),
)
})
it('is exactly the event_type enum the v1 create endpoint advertises in the OpenAPI spec', () => {
const spec = generateOpenApiSpec('https://unit.test')
const op = (spec.paths['/api/v1/companies/{companyId}/webhooks'] as Record<string, unknown>).post as {
requestBody: { content: Record<string, { schema: { properties: Record<string, { enum?: unknown[] }> } }> }
}
const enumValues = op.requestBody.content['application/json'].schema.properties.event_type.enum
expect(enumValues).toEqual([...PUBLIC_WEBHOOK_EVENTS])
})
it('is exactly the list the docs page renders', () => {
const section = WEBHOOKS_MD.split('## Event types')[1]?.split('## Payload shape')[0] ?? ''
const documented = [...section.matchAll(/^- `([a-z_]+\.[a-z_]+)`/gm)].map((m) => m[1])
expect(documented).toEqual([...PUBLIC_WEBHOOK_EVENTS])
for (const group of PUBLIC_WEBHOOK_EVENT_GROUPS) expect(section).toContain(`**${group.title}**`)
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,261 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool } from '@/tests/pg/setup'
import { seedCompany } from '@/tests/pg/fixtures'
// Verifies the three webhook-substrate DB guards shipped in Phase 6 PR-1:
// - enforce_webhook_delivery_immutability (BEFORE UPDATE)
// - block_webhook_delivery_terminal_delete (BEFORE DELETE)
// - assert_webhook_delivery_company_match (BEFORE INSERT)
//
// CLAUDE.md ("Migration Rules" + Testing section) mandates a *.pg.test.ts
// for any PR that touches a trigger / RPC / RLS / DEFERRABLE constraint.
// PR-1 (#496) shipped the triggers without the accompanying pg test; this
// closes that test debt.
async function insertWebhook(params: {
// userId kept in the signature for parity with seedCompany's return: the
// webhooks table itself has no user_id column (see route comment in
// app/api/v1/companies/[companyId]/webhooks/route.ts).
userId: string
companyId: string
eventType?: string
}): Promise<string> {
void params.userId
const id = randomUUID()
await getPool().query(
`INSERT INTO public.webhooks
(id, company_id, name, event_type, webhook_url, secret, active)
VALUES ($1, $2, 'pg-test', $3, 'https://example.com/hook', $4, true)`,
[
id,
params.companyId,
params.eventType ?? 'invoice.paid',
`whsec_${randomUUID().replace(/-/g, '')}`,
],
)
return id
}
async function insertDelivery(params: {
webhookId: string | null
companyId: string
status?: 'pending' | 'in_flight' | 'delivered' | 'failed' | 'dead'
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES ($1, $2, $3, 'invoice.paid', '{"hello":"world"}'::jsonb,
'2026-05-12', $4, now())`,
[id, params.webhookId, params.companyId, params.status ?? 'pending'],
)
return id
}
describe('webhook_deliveries triggers: immutability + DELETE block', () => {
// The lifecycle that dispatcher.ts depends on must remain mutable:
// pending → in_flight (claim), in_flight → failed (retry-pending),
// failed → in_flight (re-claim). Only `delivered` and `dead` are
// terminal and locked.
it('allows pending → in_flight (claim) transition', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'pending' })
const result = await getPool().query(
`UPDATE public.webhook_deliveries SET status = 'in_flight' WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
it('allows in_flight → failed (retry-pending) transition', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'in_flight' })
const result = await getPool().query(
`UPDATE public.webhook_deliveries SET status = 'failed', attempts = 1 WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
it('allows failed → in_flight (re-claim) transition', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'failed' })
const result = await getPool().query(
`UPDATE public.webhook_deliveries SET status = 'in_flight' WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
it('allows in_flight → delivered (success terminal) transition', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'in_flight' })
const result = await getPool().query(
`UPDATE public.webhook_deliveries
SET status = 'delivered', delivered_at = now(), response_status = 200
WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
it('rejects UPDATE on a delivered row (status flip-back blocked)', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'delivered' })
await expect(
getPool().query(
`UPDATE public.webhook_deliveries SET status = 'pending' WHERE id = $1`,
[deliveryId],
),
).rejects.toThrow(/terminal status \(delivered\) is immutable/i)
})
it('rejects UPDATE on a dead row (response rewrite blocked)', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'dead' })
await expect(
getPool().query(
`UPDATE public.webhook_deliveries
SET response_body = 'tampered' WHERE id = $1`,
[deliveryId],
),
).rejects.toThrow(/terminal status \(dead\) is immutable/i)
})
it('rejects DELETE on a delivered row', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'delivered' })
await expect(
getPool().query(
`DELETE FROM public.webhook_deliveries WHERE id = $1`,
[deliveryId],
),
).rejects.toThrow(/terminal status \(delivered\) cannot be deleted/i)
})
it('rejects DELETE on a dead row', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'dead' })
await expect(
getPool().query(
`DELETE FROM public.webhook_deliveries WHERE id = $1`,
[deliveryId],
),
).rejects.toThrow(/terminal status \(dead\) cannot be deleted/i)
})
// Non-terminal rows are still deletable: the queue-cleanup path
// (operator clears a stuck pending row, dev environment wipes,
// companies CASCADE delete) keeps working.
it('allows DELETE on a pending row', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const deliveryId = await insertDelivery({ webhookId, companyId, status: 'pending' })
const result = await getPool().query(
`DELETE FROM public.webhook_deliveries WHERE id = $1`,
[deliveryId],
)
expect(result.rowCount).toBe(1)
})
})
describe('webhook_deliveries triggers: cross-tenant INSERT guard', () => {
it('rejects INSERT when delivery.company_id != webhooks.company_id', async () => {
// Tenant A owns the webhook; tenant B owns the company on the
// delivery row. A compromised service-role caller (or future bug)
// attempting to enqueue a delivery against another tenant's webhook
// is refused at write time: closes cases (a) (cross-tenant
// visibility) and (c) (existence leak) flagged in migration
// 20260515190000's comment.
const a = await seedCompany()
const b = await seedCompany()
const webhookId = await insertWebhook({ userId: a.userId, companyId: a.companyId })
await expect(
getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES (gen_random_uuid(), $1, $2, 'invoice.paid',
'{"hello":"world"}'::jsonb, '2026-05-12', 'pending', now())`,
[webhookId, b.companyId],
),
).rejects.toThrow(/company_id .+ does not match parent webhooks\.company_id/i)
})
it('accepts INSERT when delivery.company_id == webhooks.company_id', async () => {
const { userId, companyId } = await seedCompany()
const webhookId = await insertWebhook({ userId, companyId })
const result = await getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES (gen_random_uuid(), $1, $2, 'invoice.paid',
'{"hello":"world"}'::jsonb, '2026-05-12', 'pending', now())
RETURNING id`,
[webhookId, companyId],
)
expect(result.rowCount).toBe(1)
})
it('allows INSERT with webhook_id IS NULL (dangling row after webhook delete)', async () => {
// ON DELETE SET NULL on the FK leaves these rows after a webhook is
// deleted. New inserts with webhook_id IS NULL aren't a normal write
// path (the handler never inserts a null webhook_id) but the trigger
// explicitly bypasses the check rather than blocking: leaving room
// for an admin-side audit-replay tool that recreates an archived
// delivery for forensic export.
const { companyId } = await seedCompany()
const result = await getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES (gen_random_uuid(), NULL, $1, 'invoice.paid',
'{"hello":"world"}'::jsonb, '2026-05-12', 'pending', now())
RETURNING id`,
[companyId],
)
expect(result.rowCount).toBe(1)
})
it('rejects INSERT pointing at a non-existent webhook_id', async () => {
// Bypass-check path: the trigger early-returns when the parent
// lookup yields NULL so the FK constraint surfaces the bad
// reference rather than the more-confusing company_match error.
// This test pins the FK-error pathway.
const { companyId } = await seedCompany()
const ghostWebhookId = randomUUID()
await expect(
getPool().query(
`INSERT INTO public.webhook_deliveries
(id, webhook_id, company_id, event_type, payload, api_version,
status, next_attempt_at)
VALUES (gen_random_uuid(), $1, $2, 'invoice.paid',
'{"hello":"world"}'::jsonb, '2026-05-12', 'pending', now())`,
[ghostWebhookId, companyId],
),
).rejects.toThrow(/webhook_deliveries_webhook_id_fkey|foreign key/i)
})
})
+135
View File
@@ -0,0 +1,135 @@
/**
* Emit-triggered webhook dispatch kick.
*
* Without this, the floor on webhook delivery latency is the per-minute cron
* at /api/webhooks/dispatch/cron: a delivery enqueued one second after a tick
* waits the remaining 59 before anyone looks at it. External consumers had no
* way around that except polling /api/events, which the 100 rpm per-key limit
* makes expensive and which still cannot beat the tick interval (issue #1201).
*
* So: once fanOutToWebhooks has inserted delivery rows, schedule one dispatch
* cycle immediately. The cron is unchanged and remains the retry and sweep
* path; this only moves the FIRST attempt forward.
*
* Three properties matter and are all load-bearing:
*
* 1. NEVER awaited by the emitter. eventBus.emit() is awaited at ~99 call
* sites, including journal_entry.committed, and dispatchDueDeliveries POSTs
* to receivers with a 10 s timeout each. Awaiting it here would put a
* stranger's slow HTTP endpoint on the critical path of committing a
* verifikat. kickWebhookDispatch() is synchronous and returns immediately.
*
* 2. Coalesced per instance. A bulk operation emits once per row, and each
* emission would otherwise schedule its own cycle: 100 bulk-booked
* transactions would mean 100 claim round trips. While one kick is
* outstanding, further kicks are dropped; the rows they enqueued are picked
* up by that kick, the next one, or the cron.
*
* 3. Never throws. It runs inside an event-bus subscriber, where an
* unhandled rejection would surface as a failed emit on a route that has
* already done its real work.
*
* claim_due_webhook_deliveries claims with FOR UPDATE SKIP LOCKED and flips
* rows to in_flight in the same statement, so a kick and the cron never claim
* the same row at the same moment. That is a claim-time guarantee only, and it
* is worth being precise about what it does NOT buy: the RPC autocommits, so
* its locks are gone before any POST is issued, and from then on ownership is
* just status='in_flight'. Delivery therefore stays at-least-once, exactly as
* the public docs promise ("the same delivery id may arrive more than once ...
* idempotency is on you").
*
* The kick does not widen that. Since #1257 the stuck sweep's window is a
* constant derived from the dispatcher's cycle budget rather than from the
* caller's batch size, so it is identical for both callers and always wider
* than any live cycle: neither the cron nor this 5-row kick can re-arm a row
* the other still owns. What remains is the genuine crash case, where a
* hard-killed invocation's rows are recovered while its POSTs may still be in
* flight; the ownership check in touchInFlight drops the loser's POST before
* it is issued.
*
* One asymmetry is worth stating plainly: the cron route backs the dispatcher's
* CYCLE_BUDGET_MS with `export const maxDuration = 300`, but this path cannot.
* after() runs inside whatever arbitrary API route emitted the event, and that
* route's maxDuration is not ours to set. It does not need to be: a kick claims
* at most KICK_BATCH_SIZE (5) rows and each attempt is capped at
* REQUEST_TIMEOUT_MS (10 s), so a kick cycle cannot exceed ~50 s of attempt
* time and the dispatcher's 110 s budget check never fires here. The bound on
* the kick is its batch size, not a clock.
*/
import { after } from 'next/server'
import { dispatchDueDeliveries } from './dispatcher'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { createLogger } from '@/lib/logger'
const log = createLogger('webhooks/dispatch-kick')
/**
* Deliveries claimed per emit-triggered cycle. Deliberately far below the
* cron's 50: this work runs after a user-facing request on the same function
* instance, and each delivery can burn up to REQUEST_TIMEOUT_MS. Five covers
* the realistic fanout (one or two receivers for the event that just fired)
* without letting a backlog turn one request's tail into a minute of work.
* Anything beyond it is the cron's job, which is what the cron is for.
*/
export const KICK_BATCH_SIZE = 5
/**
* True while a kick is scheduled but has not started running. Module scope,
* so it is per function instance rather than global: two concurrent instances
* each get one in-flight kick, which is fine (SKIP LOCKED makes the claims
* disjoint).
*/
let kickPending = false
/** Test seam: swap the dispatch implementation without a live Supabase. */
type DispatchFn = typeof dispatchDueDeliveries
/**
* Schedule one webhook dispatch cycle to run after the current response.
* Returns immediately; the caller must not await the delivery work.
*/
export function kickWebhookDispatch(dispatchImpl?: DispatchFn): void {
if (kickPending) return
kickPending = true
const dispatch = dispatchImpl ?? dispatchDueDeliveries
const run = async (): Promise<void> => {
// Cleared first, not last: a kick scheduled while this cycle is running
// targets rows this cycle may already have passed, so it deserves its own
// slot. Clearing here also means a cycle that dies mid-flight cannot
// wedge the flag on for the life of the instance.
kickPending = false
try {
await dispatch({
supabase: createServiceClientNoCookies(),
batchSize: KICK_BATCH_SIZE,
})
} catch (err) {
// The cron will retry every one of these rows. A failed kick is a
// latency regression, never a lost delivery, so warn rather than error.
log.warn('emit-triggered webhook dispatch failed; cron will retry', {
error: err instanceof Error ? err.message : String(err),
})
}
}
try {
// Keeps the serverless instance alive past the response so the POSTs
// actually complete. Same pattern as the enable-banking callback.
after(() => run())
} catch {
// Outside a request scope (unit tests, scripts, a plain node server):
// run it as a floating promise instead. Deferred rather than called
// inline, so this path coalesces a synchronous burst exactly like the
// after() path does: calling run() here would clear kickPending before
// the next kick in the same tick ever sees it. run() never rejects.
queueMicrotask(() => void run())
}
}
/** Test-only: reset the coalescing flag between cases. */
export function resetKickStateForTests(): void {
kickPending = false
}
File diff suppressed because it is too large Load Diff
+168
View File
@@ -0,0 +1,168 @@
/**
* Webhook event-bus handler.
*
* Subscribes to every CoreEventType the v1 API surface emits and converts
* each emission into N rows in `webhook_deliveries`: one per active webhook
* subscribed to (company_id, event_type). A dispatch cycle is then scheduled
* immediately (see dispatch-kick.ts); the per-minute cron stays as the retry
* and sweep path.
*
* Wired from lib/init.ts via registerWebhookHandler() so every API route
* that calls ensureInitialized() gets the subscription wired exactly once.
*
* Design notes:
* - We do NOT block the emitting route on delivery insert: the handler
* runs inside Promise.allSettled in the bus (see lib/events/bus.ts), so
* a DB insert failure is logged but doesn't crash the emitter.
* - We capture `previous_attributes` only for events whose payload carries
* both a prior and current shape. Phase 6 PR-1 emits null for everything:
* adding the diff is a follow-up that requires touching each route's
* emit() call site to capture the prior row.
* - Service-role client because this code runs from the bus, outside any
* authenticated Supabase context.
*/
import { eventBus } from '@/lib/events/bus'
import type { CoreEventType } from '@/lib/events/types'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { createLogger } from '@/lib/logger'
import { API_V1_VERSION } from '@/lib/api/v1/version'
import { kickWebhookDispatch } from './dispatch-kick'
import { PUBLIC_WEBHOOK_EVENTS as PUBLIC_WEBHOOK_EVENT_CATALOGUE } from './public-events'
const log = createLogger('webhooks/handler')
/**
* Set of event types that the v1 webhook surface delivers. Derived from the
* public catalogue in ./public-events.ts, which is also what the v1 create
* schema and the docs page enumerate: add new event types THERE, not here.
*/
const PUBLIC_WEBHOOK_EVENTS = new Set<CoreEventType>(PUBLIC_WEBHOOK_EVENT_CATALOGUE)
let registered = false
/**
* Subscribe the webhook handler to every event in PUBLIC_WEBHOOK_EVENTS.
* Idempotent: safe to call from ensureInitialized() across hot reloads.
*/
export function registerWebhookHandler(): void {
if (registered) return
registered = true
for (const eventType of PUBLIC_WEBHOOK_EVENTS) {
eventBus.on(eventType, async (payload) => {
// payload type depends on eventType but every variant carries
// companyId: the only field we structurally need here.
const companyId = (payload as { companyId?: string }).companyId
if (!companyId) {
// Surface as an error: every CoreEvent payload variant types
// companyId as required, so a missing value indicates an emit-site
// bug that silently breaks webhook delivery for that event. Logging
// at error level ensures it shows up in monitoring rather than
// disappearing into routine warn-noise.
log.error('event missing companyId: webhook fanout skipped', new Error('missing companyId'), { eventType })
return
}
try {
await fanOutToWebhooks({
eventType,
companyId,
payload: minimisePayload(payload as Record<string, unknown>),
})
} catch (err) {
log.error('webhook fanout failed', err as Error, { eventType, companyId })
}
})
}
log.info('webhook handler registered', { eventCount: PUBLIC_WEBHOOK_EVENTS.size })
}
/**
* Drop fields from the in-process event payload that have no value to an
* external webhook receiver. Currently strips:
* - userId: an internal Supabase auth.users.id UUID: no value to the
* receiver, identifies the gnubok-side actor not the resource. The
* companyId stays (it's the tenant scope, useful for multi-tenant
* receivers).
*
* Centralising the projection here means a future tightening (e.g.
* stripping personnummer fields from payroll payloads) lands in one
* place rather than per-emit-site. GDPR Art.5(1)(c) data minimisation.
*/
export function minimisePayload(payload: Record<string, unknown>): Record<string, unknown> {
const projected: Record<string, unknown> = {}
for (const [key, value] of Object.entries(payload)) {
if (key === 'userId') continue
projected[key] = value
}
return projected
}
/**
* Look up active webhooks for (companyId, eventType) and insert one
* webhook_deliveries row per match. Pending rows are picked up by the
* dispatcher cron at next-minute boundary.
*/
async function fanOutToWebhooks(args: {
eventType: string
companyId: string
payload: Record<string, unknown>
}): Promise<void> {
const supabase = createServiceClientNoCookies()
const { data: webhooks, error: fetchErr } = await supabase
.from('webhooks')
.select('id, secret, api_version_pinned')
.eq('company_id', args.companyId)
.eq('event_type', args.eventType)
.eq('active', true)
.is('disabled_at', null)
if (fetchErr) {
log.error('webhook lookup failed', fetchErr as Error, {
companyId: args.companyId,
eventType: args.eventType,
})
return
}
if (!webhooks || webhooks.length === 0) return
// Synthesise a correlation id for the fanout batch. The event bus is
// async: by the time we reach here the originating route's request
// context is gone, so we can't recover the live request_id. A fresh
// 'whfan_<uuid>' keeps the BFNAR 2013:2 kap 8 § behandlingshistorik
// requirement satisfied (the column is never NULL on a fresh insert)
// and lets a per-fanout audit query group the rows that came from the
// same emission. Threading the originating request_id into the event
// payload itself is a future-direction improvement.
const fanoutId = `whfan_${crypto.randomUUID()}`
const rows = webhooks.map((w) => ({
webhook_id: (w as { id: string }).id,
company_id: args.companyId,
event_type: args.eventType,
payload: args.payload,
api_version: (w as { api_version_pinned: string }).api_version_pinned ?? API_V1_VERSION,
// previous_attributes is null in Phase 6 PR-1; populated in a follow-up
// when each route's emit() call captures the prior row.
previous_attributes: null,
request_id: fanoutId,
}))
const { error: insertErr } = await supabase.from('webhook_deliveries').insert(rows)
if (insertErr) {
log.error('webhook_deliveries insert failed', insertErr as Error, {
companyId: args.companyId,
eventType: args.eventType,
webhookCount: rows.length,
})
return
}
// Deliver now instead of waiting for the next cron tick (#1201). Scheduled,
// never awaited: see lib/webhooks/dispatch-kick.ts for why the emitter must
// not block on a receiver's HTTP endpoint.
kickWebhookDispatch()
}
+275
View File
@@ -0,0 +1,275 @@
/**
* Pinned-IP HTTPS POST for webhook dispatch.
*
* Closes the DNS-rebinding window between url-guard validation and the
* actual HTTPS request. The previous shape was:
*
* 1. validateWebhookUrl() → DNS resolves to [public IP], returns ok
* 2. fetch(webhook_url) → re-resolves DNS; an attacker who flipped
* the A record in the interval gets a
* private-IP socket
*
* The new shape pins the request to the IP validated in step 1, with the
* original hostname carried in:
* - the TLS SNI extension (so the receiver's cert continues to match)
* - the HTTP Host header (so vhost routing on the receiver continues to
* work)
*
* The request socket therefore never re-resolves DNS, foreclosing the
* rebind race. Documented openly per the url-guard.ts file header
* ("closing that requires a custom HTTPS agent that pins the resolved IP").
*
* Built on `node:https.request` rather than undici's Agent because (a) the
* project doesn't take a dependency on undici, (b) the stdlib API is more
* explicit about the SNI / Host / IP split, (c) https.request is enough
* for HTTP/1.1 + TLS, which every webhook receiver supports.
*
* Inversion seam: `httpsRequest` injectable for tests so we don't need to
* stand up an HTTPS server to verify the pinning / SNI / Host shape. The
* dispatcher's tests pass a stub through `pinnedFetchImpl`.
*/
import {
request as httpsRequestDefault,
type RequestOptions as HttpsRequestOptions,
} from 'node:https'
import type { ClientRequest, IncomingMessage } from 'node:http'
import { validateWebhookUrl as validateWebhookUrlDefault } from './url-guard'
export type PinnedFetchResult =
| {
kind: 'ok'
status: number
headers: Record<string, string>
body: string
bodyTruncated: boolean
pinnedAddress: string
}
| { kind: 'unsafe_url'; reason: string; detail: string; pinnedAddress: null }
| { kind: 'redirect_blocked'; status: number; detail: string; pinnedAddress: string }
| { kind: 'timeout'; detail: string; pinnedAddress: string }
| { kind: 'transport_error'; detail: string; pinnedAddress: string | null }
export interface PinnedFetchInit {
method: string
headers: Record<string, string>
body: string
timeoutMs: number
/** Max bytes captured from response body: receivers returning long error pages get truncated. */
maxResponseBytes: number
}
export interface PinnedFetchDeps {
/** DNS validation seam. Defaults to url-guard's validateWebhookUrl. */
validateUrl?: typeof validateWebhookUrlDefault
/** Raw HTTPS request seam. Defaults to node:https.request. */
httpsRequest?: (
options: HttpsRequestOptions,
callback: (res: IncomingMessage) => void,
) => ClientRequest
}
export async function pinnedHttpsFetch(
rawUrl: string,
init: PinnedFetchInit,
deps: PinnedFetchDeps = {},
): Promise<PinnedFetchResult> {
const validateUrl = deps.validateUrl ?? validateWebhookUrlDefault
const httpsRequest = deps.httpsRequest ?? httpsRequestDefault
let parsed: URL
try {
parsed = new URL(rawUrl)
} catch {
return {
kind: 'unsafe_url',
reason: 'invalid_url',
detail: 'URL did not parse.',
pinnedAddress: null,
}
}
const validation = await validateUrl(rawUrl)
if (!validation.ok) {
return {
kind: 'unsafe_url',
reason: validation.reason,
detail: validation.detail,
pinnedAddress: null,
}
}
// Pick the first vetted address. validateWebhookUrl rejects the whole
// set when ANY entry is unsafe, so the first is safe by construction.
// Deterministic choice keeps log output stable across retries.
const pinnedAddress = validation.resolvedAddresses[0]
if (!pinnedAddress) {
// Defensive: validateWebhookUrl returns ok only when there's at least
// one address, but a future refactor could regress this and we want
// the failure to be loud, not a silent DNS-lookup-by-empty-host.
return {
kind: 'transport_error',
detail: 'No resolved address from validateWebhookUrl',
pinnedAddress: null,
}
}
const port = parsed.port ? Number(parsed.port) : 443
return new Promise<PinnedFetchResult>((resolve) => {
let settled = false
const settle = (r: PinnedFetchResult) => {
if (settled) return
settled = true
resolve(r)
}
// The HTTP Host header must carry the original hostname (vhost routing
// on the receiver). Include the port only when non-default: RFC 7230
// §5.4 says the port is omitted when it matches the scheme default.
const hostHeader = port === 443 ? parsed.hostname : `${parsed.hostname}:${port}`
const requestOptions: HttpsRequestOptions = {
protocol: 'https:',
// Pin the socket to the validated IP. node:https accepts the
// address directly: no further DNS lookup happens.
host: pinnedAddress,
port,
path: parsed.pathname + parsed.search,
method: init.method,
// SNI carries the original hostname so the receiver's TLS cert
// (which is issued for the hostname, not the IP) validates.
//
// Cert-vs-hostname verification: Node's default checkServerIdentity
// matches the cert's SAN/CN against `servername` (or `host` when
// servername is unset). Because `servername` is set to the original
// hostname, the IP substitution above does NOT weaken the hostname-
// verification step: a forged endpoint at the pinned IP presenting
// a valid cert for a DIFFERENT hostname would fail the handshake.
// No explicit checkServerIdentity override is needed; relying on
// the default is the documented contract.
servername: parsed.hostname,
headers: {
...init.headers,
// Lowercase 'host': Node's https.request would synthesise one
// from `host` (the pinned IP) if we didn't set it explicitly,
// which would break vhost routing on the receiver.
host: hostHeader,
},
// Fresh socket per call: webhook delivery doesn't benefit from
// Keep-Alive (the dispatcher serializes and the IP changes per
// dispatch from re-validation). agent:false also forecloses any
// accidental pool-level reuse across pinned IPs.
agent: false,
}
let absoluteTimer: NodeJS.Timeout | null = null
const req = httpsRequest(requestOptions, (res) => {
// Receivers MUST return a non-redirect. Following a 3xx would let
// them bounce the dispatcher to a private address AFTER the SSRF
// guard cleared. We don't follow redirects; treat as terminal here
// and let the dispatcher mark the row dead with reason='redirect_
// blocked' for consistency with the old fetch path's behavior.
const status = res.statusCode ?? 0
if (status >= 300 && status < 400) {
// Drain body so the socket cleans up; ignore errors.
res.resume()
req.destroy()
if (absoluteTimer) clearTimeout(absoluteTimer)
return settle({
kind: 'redirect_blocked',
status,
detail: `Receiver returned ${status}; redirects are refused.`,
pinnedAddress,
})
}
const chunks: Buffer[] = []
let total = 0
let truncated = false
res.on('data', (chunk: Buffer) => {
if (truncated) return
if (total + chunk.length > init.maxResponseBytes) {
const remaining = init.maxResponseBytes - total
if (remaining > 0) chunks.push(chunk.subarray(0, remaining))
total = init.maxResponseBytes
truncated = true
// Destroy the stream: no point pulling the rest over the wire.
res.destroy()
} else {
chunks.push(chunk)
total += chunk.length
}
})
const finalize = () => {
if (absoluteTimer) clearTimeout(absoluteTimer)
const headers: Record<string, string> = {}
for (const [k, v] of Object.entries(res.headers)) {
if (typeof v === 'string') headers[k] = v
else if (Array.isArray(v)) headers[k] = v.join(', ')
}
settle({
kind: 'ok',
status,
headers,
body: Buffer.concat(chunks).toString('utf8'),
bodyTruncated: truncated,
pinnedAddress,
})
}
// Two completion paths to handle: 'end' (normal completion) and
// 'close' (when we destroyed the stream for size truncation, where
// 'end' does not fire). Node emits BOTH 'end' and 'close' on normal
// completions, so `once()` + a self-removing pair keeps finalize
// single-shot without relying on the outer `settled` guard to
// squash duplicate header reconstruction.
const finalizeOnce = () => {
res.removeListener('end', finalizeOnce)
res.removeListener('close', finalizeOnce)
finalize()
}
res.once('end', finalizeOnce)
res.once('close', finalizeOnce)
res.on('error', (err) => {
if (absoluteTimer) clearTimeout(absoluteTimer)
settle({ kind: 'transport_error', detail: err.message, pinnedAddress })
})
})
// Two-layer timeout: socket-idle timeout via Node's built-in, plus a
// wall-clock absolute timeout. node:https `timeout` is idle-only and
// wouldn't fire if a slow receiver dribbles bytes; the absolute timer
// is the hard cap.
req.setTimeout(init.timeoutMs)
req.on('timeout', () => {
req.destroy()
if (absoluteTimer) clearTimeout(absoluteTimer)
settle({
kind: 'timeout',
detail: `Socket idle for ${init.timeoutMs} ms`,
pinnedAddress,
})
})
absoluteTimer = setTimeout(() => {
req.destroy()
settle({
kind: 'timeout',
detail: `Request exceeded ${init.timeoutMs} ms wall-clock`,
pinnedAddress,
})
}, init.timeoutMs)
req.on('error', (err) => {
if (absoluteTimer) clearTimeout(absoluteTimer)
settle({ kind: 'transport_error', detail: err.message, pinnedAddress })
})
if (init.body) req.write(init.body)
req.end()
})
}
+129
View File
@@ -0,0 +1,129 @@
/**
* The public webhook event catalogue: the single source of truth for which
* CoreEventType values the v1 webhook surface delivers.
*
* Everything that enumerates webhook events derives from this module, so the
* lists cannot drift apart again (they did: the handler delivered 28 events
* while the create schema and the docs page listed 24, so nobody could
* subscribe to the four reconciliation.* events):
*
* 1. lib/webhooks/handler.ts subscribes the fan-out handler to every event.
* 2. app/api/v1/companies/[companyId]/webhooks/route.ts builds the create
* schema's `event_type` enum from it, which is what the OpenAPI spec and
* the generated agent skill (skills/accounted-api) advertise.
* 3. lib/docs/content/webhooks.ts renders its "Event types" section from
* the groups below.
*
* Restricted to the resource-state-change events that are useful to external
* integrations; MCP telemetry events and internal-only flows (event_log
* writes, drafts, deletes) are deliberately excluded.
*
* Adding an event type here is a public-API change: add a changelog entry in
* lib/docs/content/changelog.ts. Additive changes do not bump API_V1_VERSION.
*
* This module must stay a leaf (type-only imports): it is imported by docs
* pages, route modules and the event-bus handler alike.
*/
import type { CoreEventType } from '@/lib/events/types'
export interface PublicWebhookEventEntry {
type: CoreEventType
/** Short docs prose, rendered after the event name on the docs page. */
description?: string
}
export interface PublicWebhookEventGroup {
/** Docs section heading, e.g. "Invoicing". */
title: string
/** Optional note rendered next to the heading (e.g. an extra scope requirement). */
note?: string
events: ReadonlyArray<PublicWebhookEventEntry>
}
export const PUBLIC_WEBHOOK_EVENT_GROUPS = [
{
title: 'Invoicing',
events: [
{ type: 'invoice.created', description: 'draft invoice created' },
{ type: 'invoice.sent', description: 'invoice marked sent (email delivered or external)' },
{ type: 'invoice.paid', description: 'invoice fully paid' },
{ type: 'credit_note.created', description: 'credit note issued' },
],
},
{
title: 'AP / suppliers',
events: [
{ type: 'supplier.created' },
{ type: 'supplier_invoice.registered' },
{ type: 'supplier_invoice.approved' },
{ type: 'supplier_invoice.paid' },
{ type: 'supplier_invoice.credited' },
{ type: 'supplier_invoice.uncredited', description: 'credit reversal' },
],
},
{
title: 'Customers',
events: [{ type: 'customer.created' }],
},
{
title: 'Bookkeeping',
events: [
{ type: 'journal_entry.committed', description: 'voucher posted (immutable from this point)' },
{ type: 'journal_entry.reversed', description: 'storno entry posted' },
{ type: 'journal_entry.corrected', description: 'rättelse via `correctEntry` (BFL 5 kap 5 §)' },
],
},
{
title: 'Transactions',
events: [
{ type: 'transaction.categorized', description: 'bank transaction assigned an account + tax code' },
{ type: 'transaction.reconciled', description: 'transaction matched to a posted entry' },
],
},
{
title: 'Reconciliation',
events: [
{
type: 'reconciliation.matched',
description: 'an outside item (bank row or skattekonto row) linked to a journal entry',
},
{ type: 'reconciliation.unmatched', description: 'a reconciliation link removed' },
{ type: 'reconciliation.signed_off', description: 'an account signed off as reconciled through a date' },
{ type: 'reconciliation.reopened', description: 'a sign-off reopened' },
],
},
{
title: 'Periods',
events: [
{ type: 'period.locked', description: 'fiscal period closed for writes' },
{ type: 'period.unlocked', description: 'fiscal period reopened' },
{ type: 'period.year_closed', description: 'full year-end procedure complete' },
],
},
{
title: 'Payroll',
note: 'requires `payroll:read` scope alongside `webhooks:manage`',
events: [
{ type: 'salary_run.created' },
{ type: 'salary_run.approved' },
{ type: 'salary_run.booked', description: 'journal entries posted' },
{ type: 'agi.generated', description: 'AGI XML produced' },
],
},
{
title: 'Documents',
events: [{ type: 'document.uploaded' }],
},
] as const satisfies ReadonlyArray<PublicWebhookEventGroup>
/** Union of every deliverable event type, narrowed from the catalogue. */
export type PublicWebhookEventType = (typeof PUBLIC_WEBHOOK_EVENT_GROUPS)[number]['events'][number]['type']
/**
* Flat, ordered list of every deliverable event type. Pass straight to
* `z.enum(...)` or `new Set(...)`.
*/
export const PUBLIC_WEBHOOK_EVENTS: ReadonlyArray<PublicWebhookEventType> = PUBLIC_WEBHOOK_EVENT_GROUPS.flatMap(
(group) => group.events.map((event) => event.type),
)
+76
View File
@@ -0,0 +1,76 @@
/**
* Webhook signature generation + verification.
*
* Signature header (Stripe-style):
* X-Gnubok-Signature: t=<unix>,v1=<hex-HMAC-SHA256>
*
* Where the signed payload is:
* `${t}.${rawBody}`
*
* The `t` (unix timestamp in seconds) is included in the signed payload
* so receivers can implement replay-window checks. The receiver-side
* verification (parse the header, recompute the HMAC, apply a 5-minute
* tolerance) is documented in the docs cookbook (lib/docs/content/webhooks.ts);
* receivers can pick their own tolerance.
*
* Why HMAC-SHA256 (not Ed25519): every Node/Python/Go/Ruby stdlib has it,
* receivers can verify without adding a dep. Asymmetric signing buys nothing
* for outbound webhooks where the receiver has no use for verifying the
* signer's identity beyond "this is the secret you set on creation".
*/
import crypto from 'crypto'
const ALGORITHM = 'sha256'
export interface SignedHeaderParts {
/** Unix seconds. */
t: number
/** Hex-encoded HMAC-SHA256(t + "." + body, secret). */
v1: string
}
/**
* Generate the value of the `X-Gnubok-Signature` header for an outbound
* delivery.
*/
export function signPayload(args: {
body: string
secret: string
/** Override for tests. Defaults to current unix-seconds. */
timestamp?: number
}): { header: string; parts: SignedHeaderParts } {
const t = args.timestamp ?? Math.floor(Date.now() / 1000)
const v1 = crypto
.createHmac(ALGORITHM, args.secret)
.update(`${t}.${args.body}`)
.digest('hex')
return {
header: `t=${t},v1=${v1}`,
parts: { t, v1 },
}
}
/**
* Generate a fresh webhook secret. 32 bytes of crypto-random hex (256 bits
* of entropy, 64-character output). Returned to the caller exactly once on
* webhook creation; we do not store the plaintext anywhere except the
* `webhooks.secret` column (used for signing on every outbound delivery).
*
* **Documented Security Decision (OWASP V14.2 / ISO 27001:2022 A.8.24):**
* `webhooks.secret` is stored in plaintext rather than hashed. This is
* unavoidable for outbound HMAC signing: the signing operation needs the
* original byte sequence on every delivery, so a one-way hash would
* preclude signing. Stripe, GitHub, Slack, and Twilio all follow the same
* pattern for the same reason. Defense-in-depth comes from the
* service-role-only INSERT/UPDATE/DELETE on `webhooks` (no anon/auth
* write path), the column-level select projection on every read endpoint
* (the row never includes `secret` outside the create response), and
* Supabase encryption-at-rest. Re-evaluate if/when KMS-backed signing
* becomes available without per-call latency cost.
*
* Receivers use this same value verbatim when verifying signatures.
*/
export function generateWebhookSecret(): string {
return crypto.randomBytes(32).toString('hex')
}
+184
View File
@@ -0,0 +1,184 @@
/**
* Webhook URL safety guard.
*
* SSRF mitigation for the dispatcher: a webhook receiver URL is supplied by
* the caller, and the dispatcher POSTs HMAC-signed payloads to it from the
* Vercel function's network position. Without validation, a malicious
* caller could direct the dispatcher at internal addresses (cloud metadata
* endpoints at 169.254.169.254, kube-internal services at 10.x, loopback,
* etc.) and exfiltrate signed payloads or probe internal infrastructure.
*
* Two-layer defense:
* 1. At create / update time the v1 routes call `assertSafeWebhookUrl`
* and reject the request with VALIDATION_ERROR if the URL fails.
* 2. At dispatch time the dispatcher calls the same helper before each
* HTTP request: DNS records can change between creation and
* dispatch (rebind attacks, DNS hijack), so the create-time check
* alone is insufficient.
*
* Errors carry a stable `reason` string so the route can surface a
* structured details object and the dispatcher can stamp it on the
* delivery's error column.
*/
import { promises as dns } from 'node:dns'
export type WebhookUrlValidationReason =
| 'invalid_url'
| 'non_https_scheme'
| 'dns_lookup_failed'
| 'no_dns_records'
| 'private_address'
| 'loopback_address'
| 'link_local_address'
| 'cgnat_address'
| 'metadata_address'
export interface WebhookUrlValidationError {
ok: false
reason: WebhookUrlValidationReason
detail: string
}
export interface WebhookUrlValidationOk {
ok: true
hostname: string
/** All A/AAAA records resolved at validation time. Every entry is publicly routable. */
resolvedAddresses: string[]
}
export type WebhookUrlValidationResult = WebhookUrlValidationOk | WebhookUrlValidationError
/**
* Validate that the URL is HTTPS and that EVERY A/AAAA record for the
* hostname resolves to a publicly-routable address. Returns a
* discriminated result rather than throwing so call sites can surface a
* clean validation error envelope.
*
* Multi-record enumeration (vs single dns.lookup) closes a round-robin
* DNS bypass: a hostname with two A records [public, private] returns
* either non-deterministically per call. Single-lookup validation could
* return the public IP at create time and the private IP at dispatch
* time. Resolving ALL records and rejecting if ANY is unsafe forecloses
* that path. A separate DNS-rebinding window (between dispatch-time
* validation and the actual fetch) remains; closing that requires a
* custom HTTPS agent that pins the resolved IP: tracked for follow-up.
*/
export async function validateWebhookUrl(
rawUrl: string,
opts?: { resolve4?: typeof dns.resolve4; resolve6?: typeof dns.resolve6 },
): Promise<WebhookUrlValidationResult> {
let parsed: URL
try {
parsed = new URL(rawUrl)
} catch {
return { ok: false, reason: 'invalid_url', detail: 'URL did not parse.' }
}
if (parsed.protocol !== 'https:') {
return {
ok: false,
reason: 'non_https_scheme',
detail: `webhook_url must use https:// (got ${parsed.protocol}).`,
}
}
const resolve4 = opts?.resolve4 ?? dns.resolve4
const resolve6 = opts?.resolve6 ?? dns.resolve6
// Resolve A and AAAA in parallel. Each returns an array of address
// strings or throws ENODATA / ENOTFOUND when there are no records of
// that family. Treat a per-family ENODATA as "no records" rather than
// a hard failure: the other family may still resolve.
const [v4Result, v6Result] = await Promise.allSettled([
resolve4(parsed.hostname),
resolve6(parsed.hostname),
])
const addresses: string[] = []
let hardFailure: Error | null = null
for (const r of [v4Result, v6Result]) {
if (r.status === 'fulfilled') {
addresses.push(...r.value)
} else {
const code = (r.reason as { code?: string } | null)?.code
// ENODATA / ENOTFOUND for one family is normal (e.g. v6-only or
// v4-only host). Other errors (server failure, timeout) propagate.
if (code !== 'ENODATA' && code !== 'ENOTFOUND') {
hardFailure = r.reason instanceof Error ? r.reason : new Error(String(r.reason))
}
}
}
if (addresses.length === 0) {
return {
ok: false,
reason: hardFailure ? 'dns_lookup_failed' : 'no_dns_records',
detail: hardFailure
? `DNS lookup failed for ${parsed.hostname}: ${hardFailure.message}`
: `No A/AAAA records for ${parsed.hostname}.`,
}
}
for (const address of addresses) {
const classification = classifyAddress(address)
if (classification !== 'public') {
return {
ok: false,
reason: classification,
detail: `Resolved address ${address} for ${parsed.hostname} is not publicly routable (${classification}).`,
}
}
}
return { ok: true, hostname: parsed.hostname, resolvedAddresses: addresses }
}
type AddressClass =
| 'public'
| 'loopback_address'
| 'private_address'
| 'link_local_address'
| 'cgnat_address'
| 'metadata_address'
/**
* Map an IPv4 or IPv6 address string to a safety class. Returns 'public'
* only when the address falls outside every known unsafe range we care
* about for SSRF prevention.
*/
function classifyAddress(address: string): AddressClass {
// IPv4
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(address)
if (v4) {
const o = [v4[1], v4[2], v4[3], v4[4]].map((s) => Number.parseInt(s, 10))
// Cloud metadata endpoint: explicit class so we surface it distinctly.
// 169.254.169.254 is AWS/GCP/Azure/Hetzner; classify before the broader
// 169.254.0.0/16 link-local check.
if (o[0] === 169 && o[1] === 254 && o[2] === 169 && o[3] === 254) {
return 'metadata_address'
}
if (o[0] === 169 && o[1] === 254) return 'link_local_address'
if (o[0] === 127) return 'loopback_address'
if (o[0] === 10) return 'private_address'
if (o[0] === 172 && o[1] >= 16 && o[1] <= 31) return 'private_address'
if (o[0] === 192 && o[1] === 168) return 'private_address'
if (o[0] === 100 && o[1] >= 64 && o[1] <= 127) return 'cgnat_address'
// 0.0.0.0/8: "this network", treat as loopback-equivalent.
if (o[0] === 0) return 'loopback_address'
return 'public'
}
// IPv6: minimal classification. Lower-case for case-insensitive match.
const v6 = address.toLowerCase()
if (v6 === '::1' || v6 === '0:0:0:0:0:0:0:1') return 'loopback_address'
if (v6 === '::' || v6 === '0:0:0:0:0:0:0:0') return 'loopback_address'
// ::ffff:0:0/96: IPv4-mapped IPv6. Re-classify the embedded IPv4.
const mapped = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(v6)
if (mapped) return classifyAddress(mapped[1])
// fc00::/7: unique local
if (/^f[cd]/.test(v6)) return 'private_address'
// fe80::/10: link-local
if (/^fe[89ab]/.test(v6)) return 'link_local_address'
return 'public'
}