fix(api): register the v1 stamp endpoint scope and derive the webhook event catalogue from one source (#1930)
POST /api/v1/companies/{companyId}/inbox-items/{id}/stamp registered itself
with scope documents:write but had no V1_ENDPOINT_SCOPES entry, and the
wrapper resolves the required scope from that map before it validates the
bearer token, so the route answered NOT_FOUND to every caller. Add the entry,
drop the three phantom entries that had no route (GET openapi.yaml, GET
companies/:companyId, GET companies/:companyId/events), and add a parity test
that pins the scope map to the endpoint registry in both directions, checks
every pattern against an existing route file, and checks every v1 route file
is imported by load-routes.ts.
The webhook event catalogue was hand-copied in three places and had drifted:
the fan-out handler delivered 28 events while the v1 create enum, the OpenAPI
spec, the generated agent skill and the docs page listed 24, so the four
reconciliation.* events could not be subscribed to. lib/webhooks/public-events.ts
is now the single source; the handler set, the Zod enum and the docs section
derive from it, with tests that pin each surface to the catalogue. The PATCH
webhook docs no longer tell agents to delete and recreate a webhook to rotate
its secret: POST .../rotate-secret exists.
Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Jakob Wennberg
Claude Fable 5
parent
f08fc2c274
commit
d3869e6694
@@ -0,0 +1,118 @@
|
||||
/**
|
||||
* Scope-map / registry parity guard.
|
||||
*
|
||||
* `withApiV1` resolves the required scope for a request from
|
||||
* `V1_ENDPOINT_SCOPES` (lib/auth/scopes.ts), NOT from the endpoint registry,
|
||||
* and answers NOT_FOUND when the map has no entry, before it even validates
|
||||
* the bearer token. So a route that registers itself but forgets the map
|
||||
* entry is live in the OpenAPI spec and the generated agent skill yet 404s
|
||||
* for every caller. That is exactly what happened to
|
||||
* POST .../inbox-items/{id}/stamp.
|
||||
*
|
||||
* This test pins the two sources to each other in both directions, checks
|
||||
* that every pattern points at a route file that exists, and that every v1
|
||||
* route file is imported by load-routes.ts (otherwise it is invisible to
|
||||
* this test and to the spec).
|
||||
*/
|
||||
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { V1_ENDPOINT_SCOPES, V1_PUBLIC_ENDPOINTS } from '@/lib/auth/scopes'
|
||||
import { listEndpoints } from '../registry'
|
||||
// Side-effect import: populates the ENDPOINTS registry from every route file.
|
||||
import '../load-routes'
|
||||
|
||||
const REPO_ROOT = fileURLToPath(new URL('../../../../', import.meta.url))
|
||||
const V1_APP_DIR = join(REPO_ROOT, 'app', 'api', 'v1')
|
||||
|
||||
/**
|
||||
* Public endpoints that legitimately have no registry entry. The OpenAPI
|
||||
* document is generated FROM the registry, so it cannot register itself.
|
||||
*/
|
||||
const PUBLIC_WITHOUT_REGISTRY_ENTRY = new Set<string>(['GET /api/v1/openapi.json'])
|
||||
|
||||
/**
|
||||
* Route files under app/api/v1 that are not part of the registry. Same
|
||||
* exception as above, in file form.
|
||||
*/
|
||||
const ROUTE_FILES_WITHOUT_REGISTRY_ENTRY = new Set<string>(['app/api/v1/openapi.json/route.ts'])
|
||||
|
||||
function endpointKey(e: { method: string; path: string }): string {
|
||||
return `${e.method} ${e.path}`
|
||||
}
|
||||
|
||||
/** `POST /api/v1/companies/:companyId/x/:id` to `app/api/v1/companies/[companyId]/x/[id]/route.ts`. */
|
||||
function routeFileFor(pattern: string): string {
|
||||
const path = pattern.split(' ', 2)[1]
|
||||
return join('app', path.replace(/:([^/]+)/g, '[$1]'), 'route.ts')
|
||||
}
|
||||
|
||||
function walkRouteFiles(dir: string): string[] {
|
||||
const out: string[] = []
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === '__tests__') continue
|
||||
const full = join(dir, name)
|
||||
if (statSync(full).isDirectory()) out.push(...walkRouteFiles(full))
|
||||
else if (name === 'route.ts') out.push(full)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const registered = listEndpoints()
|
||||
const registeredByKey = new Map(registered.map((e) => [endpointKey(e), e]))
|
||||
|
||||
describe('V1_ENDPOINT_SCOPES <-> endpoint registry parity', () => {
|
||||
it('has a scope-map entry, with the same scope, for every registered non-public endpoint', () => {
|
||||
const problems = registered
|
||||
.filter((e) => e.scope !== null)
|
||||
.flatMap((e) => {
|
||||
const key = endpointKey(e)
|
||||
const mapped = V1_ENDPOINT_SCOPES[key]
|
||||
if (mapped === undefined) return [`${key}: registered with scope ${e.scope} but missing from V1_ENDPOINT_SCOPES (the wrapper answers 404)`]
|
||||
if (mapped !== e.scope) return [`${key}: registry says ${e.scope}, V1_ENDPOINT_SCOPES says ${mapped}`]
|
||||
return []
|
||||
})
|
||||
expect(problems).toEqual([])
|
||||
})
|
||||
|
||||
it('lists every registered public (scope: null) endpoint in V1_PUBLIC_ENDPOINTS', () => {
|
||||
const problems = registered
|
||||
.filter((e) => e.scope === null)
|
||||
.map(endpointKey)
|
||||
.filter((key) => !V1_PUBLIC_ENDPOINTS.includes(key))
|
||||
expect(problems).toEqual([])
|
||||
})
|
||||
|
||||
it('has a registered endpoint behind every V1_ENDPOINT_SCOPES entry', () => {
|
||||
const phantoms = Object.keys(V1_ENDPOINT_SCOPES).filter((key) => !registeredByKey.has(key))
|
||||
expect(phantoms).toEqual([])
|
||||
})
|
||||
|
||||
it('has a registered public endpoint (or a documented exception) behind every V1_PUBLIC_ENDPOINTS entry', () => {
|
||||
const problems = V1_PUBLIC_ENDPOINTS.flatMap((key) => {
|
||||
if (PUBLIC_WITHOUT_REGISTRY_ENTRY.has(key)) return []
|
||||
const def = registeredByKey.get(key)
|
||||
if (!def) return [`${key}: in V1_PUBLIC_ENDPOINTS but not registered`]
|
||||
if (def.scope !== null) return [`${key}: in V1_PUBLIC_ENDPOINTS but registered with scope ${def.scope}`]
|
||||
return []
|
||||
})
|
||||
expect(problems).toEqual([])
|
||||
})
|
||||
|
||||
it('points every scope-map and public pattern at a route file that exists', () => {
|
||||
const patterns = [...Object.keys(V1_ENDPOINT_SCOPES), ...V1_PUBLIC_ENDPOINTS]
|
||||
const missing = patterns.filter((key) => !existsSync(join(REPO_ROOT, routeFileFor(key))))
|
||||
expect(missing).toEqual([])
|
||||
})
|
||||
|
||||
it('imports every app/api/v1 route file from load-routes.ts', () => {
|
||||
const loader = readFileSync(join(REPO_ROOT, 'lib', 'api', 'v1', 'load-routes.ts'), 'utf8')
|
||||
const notLoaded = walkRouteFiles(V1_APP_DIR)
|
||||
.map((full) => full.slice(REPO_ROOT.length).replace(/^\/+/, ''))
|
||||
.filter((rel) => !ROUTE_FILES_WITHOUT_REGISTRY_ENTRY.has(rel))
|
||||
.filter((rel) => !loader.includes(`'@/${rel.replace(/\.ts$/, '')}'`))
|
||||
expect(notLoaded).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -16,8 +16,20 @@ describe('resolveRequiredScope', () => {
|
||||
|
||||
it('resolves :param patterns to a single scope', () => {
|
||||
expect(
|
||||
resolveRequiredScope('GET', '/api/v1/companies/8fd5b1f4-1111-2222-3333-444455556666'),
|
||||
).toBe('companies:read')
|
||||
resolveRequiredScope(
|
||||
'GET',
|
||||
'/api/v1/companies/8fd5b1f4-1111-2222-3333-444455556666/customers/0b6c7d8e-1111-2222-3333-444455556666',
|
||||
),
|
||||
).toBe('customers:read')
|
||||
})
|
||||
|
||||
it('resolves the inbox-items stamp verb (previously unregistered: 404 with a valid key)', () => {
|
||||
expect(
|
||||
resolveRequiredScope(
|
||||
'POST',
|
||||
'/api/v1/companies/8fd5b1f4-1111-2222-3333-444455556666/inbox-items/0b6c7d8e-1111-2222-3333-444455556666/stamp',
|
||||
),
|
||||
).toBe('documents:write')
|
||||
})
|
||||
|
||||
it('returns null for unknown paths', () => {
|
||||
|
||||
+12
-6
@@ -10,7 +10,15 @@
|
||||
* Endpoints not listed here are public (no auth): only the discovery routes
|
||||
* (`/llms.txt`, `/.well-known/skills`, `/api/v1/health`, `/api/v1/openapi.json`)
|
||||
* fall into that bucket. Everything else under `/api/v1/` MUST be in this map
|
||||
* or the wrapper will refuse the request with INSUFFICIENT_SCOPE.
|
||||
* or the wrapper answers NOT_FOUND before it even looks at the bearer token
|
||||
* (`resolveRequiredScope` returns null for an unknown path).
|
||||
*
|
||||
* This map and the endpoint registry (`lib/api/v1/registry.ts`, populated by
|
||||
* `load-routes.ts`) are kept in lock-step by
|
||||
* `lib/api/v1/__tests__/scope-registry-parity.test.ts`: every registered
|
||||
* endpoint needs an entry with the same scope, and every entry needs a
|
||||
* registered endpoint. The inbox-items stamp route shipped without an entry
|
||||
* and answered 404 to valid keys until that test existed.
|
||||
*/
|
||||
|
||||
import type { ApiKeyScope } from './api-keys'
|
||||
@@ -22,7 +30,6 @@ import type { ApiKeyScope } from './api-keys'
|
||||
export const V1_PUBLIC_ENDPOINTS: ReadonlyArray<string> = [
|
||||
'GET /api/v1/health',
|
||||
'GET /api/v1/openapi.json',
|
||||
'GET /api/v1/openapi.yaml',
|
||||
]
|
||||
|
||||
/**
|
||||
@@ -40,7 +47,6 @@ export const V1_ENDPOINT_SCOPES: Record<string, ApiKeyScope> = {
|
||||
'GET /api/v1/companies': 'companies:read',
|
||||
// Issue #1814: programmatic company creation (partner provisioning, agents).
|
||||
'POST /api/v1/companies': 'companies:write',
|
||||
'GET /api/v1/companies/:companyId': 'companies:read',
|
||||
// Issue #1348: company-settings write (same field set as the MCP tool
|
||||
// gnubok_update_company_settings; direct write, no staging).
|
||||
'PATCH /api/v1/companies/:companyId/settings': 'companies:write',
|
||||
@@ -48,9 +54,6 @@ export const V1_ENDPOINT_SCOPES: Record<string, ApiKeyScope> = {
|
||||
// Operations (async long-running tasks)
|
||||
'GET /api/v1/operations/:id': 'operations:read',
|
||||
|
||||
// Events (webhook fallback / event log polling)
|
||||
'GET /api/v1/companies/:companyId/events': 'events:read',
|
||||
|
||||
// Customers (Phase 2 PR-A: reads; Phase 2 PR-B-1: writes)
|
||||
'GET /api/v1/companies/:companyId/customers': 'customers:read',
|
||||
'GET /api/v1/companies/:companyId/customers/:id': 'customers:read',
|
||||
@@ -117,6 +120,9 @@ export const V1_ENDPOINT_SCOPES: Record<string, ApiKeyScope> = {
|
||||
'POST /api/v1/companies/:companyId/documents': 'documents:write',
|
||||
'GET /api/v1/companies/:companyId/documents/:id/download': 'documents:read',
|
||||
'POST /api/v1/companies/:companyId/documents/:id/link': 'documents:write',
|
||||
// Inbox item stamp: closes an invoice_inbox_items row against the JE it
|
||||
// was booked to. Rides documents:write like the link verb it complements.
|
||||
'POST /api/v1/companies/:companyId/inbox-items/:id/stamp': 'documents:write',
|
||||
|
||||
// Phase 3: transactions + reconciliation vertical.
|
||||
// Reads
|
||||
|
||||
@@ -1,3 +1,22 @@
|
||||
import {
|
||||
PUBLIC_WEBHOOK_EVENT_GROUPS,
|
||||
type PublicWebhookEventGroup,
|
||||
} from '@/lib/webhooks/public-events'
|
||||
|
||||
/**
|
||||
* The "Event types" section, rendered from the same catalogue the fan-out
|
||||
* handler subscribes to and the v1 create schema validates against.
|
||||
*/
|
||||
function renderEventTypes(): string {
|
||||
return PUBLIC_WEBHOOK_EVENT_GROUPS.map((group: PublicWebhookEventGroup) => {
|
||||
const heading = group.note ? `**${group.title}** *(${group.note})*` : `**${group.title}**`
|
||||
const lines = group.events.map((event) =>
|
||||
event.description ? `- \`${event.type}\`: ${event.description}` : `- \`${event.type}\``,
|
||||
)
|
||||
return [heading, ...lines].join('\n')
|
||||
}).join('\n\n')
|
||||
}
|
||||
|
||||
export const WEBHOOKS_MD = `# Webhooks
|
||||
|
||||
> Receive HMAC-signed POST notifications when state changes in Accounted: invoices paid, journal entries committed, periods locked, salary runs booked, AGI files generated. At-least-once delivery with exponential backoff over ~87 hours (about 3.6 days).
|
||||
@@ -16,45 +35,7 @@ If you've used [Stripe webhooks](https://docs.stripe.com/webhooks), the model is
|
||||
|
||||
The following event types are deliverable as webhooks. Subscribing to a type that requires elevated scope (\`salary_run.*\` and \`agi.*\` need \`payroll:read\`) returns \`INSUFFICIENT_SCOPE\` at registration time.
|
||||
|
||||
**Invoicing**
|
||||
- \`invoice.created\`: draft invoice created
|
||||
- \`invoice.sent\`: invoice marked sent (email delivered or external)
|
||||
- \`invoice.paid\`: invoice fully paid
|
||||
- \`credit_note.created\`: credit note issued
|
||||
|
||||
**AP / suppliers**
|
||||
- \`supplier.created\`
|
||||
- \`supplier_invoice.registered\`
|
||||
- \`supplier_invoice.approved\`
|
||||
- \`supplier_invoice.paid\`
|
||||
- \`supplier_invoice.credited\`
|
||||
- \`supplier_invoice.uncredited\`: credit reversal
|
||||
|
||||
**Customers**
|
||||
- \`customer.created\`
|
||||
|
||||
**Bookkeeping**
|
||||
- \`journal_entry.committed\`: voucher posted (immutable from this point)
|
||||
- \`journal_entry.reversed\`: storno entry posted
|
||||
- \`journal_entry.corrected\`: rättelse via \`correctEntry\` (BFL 5 kap 5 §)
|
||||
|
||||
**Transactions**
|
||||
- \`transaction.categorized\`: bank transaction assigned an account + tax code
|
||||
- \`transaction.reconciled\`: transaction matched to a posted entry
|
||||
|
||||
**Periods**
|
||||
- \`period.locked\`: fiscal period closed for writes
|
||||
- \`period.unlocked\`: fiscal period reopened
|
||||
- \`period.year_closed\`: full year-end procedure complete
|
||||
|
||||
**Payroll** *(requires \`payroll:read\` scope alongside \`webhooks:manage\`)*
|
||||
- \`salary_run.created\`
|
||||
- \`salary_run.approved\`
|
||||
- \`salary_run.booked\`: journal entries posted
|
||||
- \`agi.generated\`: AGI XML produced
|
||||
|
||||
**Documents**
|
||||
- \`document.uploaded\`
|
||||
${renderEventTypes()}
|
||||
|
||||
## Payload shape
|
||||
|
||||
|
||||
@@ -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())
|
||||
})
|
||||
})
|
||||
@@ -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}**`)
|
||||
})
|
||||
})
|
||||
+5
-37
@@ -28,48 +28,16 @@ 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. Restricted to the
|
||||
* resource-state-change events that are useful to external integrations;
|
||||
* MCP telemetry events and internal-only flows (event_log writes, etc.) are
|
||||
* deliberately excluded.
|
||||
*
|
||||
* Adding a new event type to this set is a public-API change: bump
|
||||
* API_V1_VERSION + add to the changelog when you do.
|
||||
* 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>([
|
||||
'invoice.created',
|
||||
'invoice.sent',
|
||||
'invoice.paid',
|
||||
'credit_note.created',
|
||||
'customer.created',
|
||||
'supplier.created',
|
||||
'supplier_invoice.registered',
|
||||
'supplier_invoice.approved',
|
||||
'supplier_invoice.paid',
|
||||
'supplier_invoice.credited',
|
||||
'supplier_invoice.uncredited',
|
||||
'transaction.categorized',
|
||||
'transaction.reconciled',
|
||||
'reconciliation.matched',
|
||||
'reconciliation.unmatched',
|
||||
'reconciliation.signed_off',
|
||||
'reconciliation.reopened',
|
||||
'journal_entry.committed',
|
||||
'journal_entry.reversed',
|
||||
'journal_entry.corrected',
|
||||
'period.locked',
|
||||
'period.unlocked',
|
||||
'period.year_closed',
|
||||
'salary_run.created',
|
||||
'salary_run.approved',
|
||||
'salary_run.booked',
|
||||
'agi.generated',
|
||||
'document.uploaded',
|
||||
])
|
||||
const PUBLIC_WEBHOOK_EVENTS = new Set<CoreEventType>(PUBLIC_WEBHOOK_EVENT_CATALOGUE)
|
||||
|
||||
let registered = false
|
||||
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
Reference in New Issue
Block a user