3912c74a7b
* feat(api): Phase 6 PR-2 — docs polish (Stripe-inspired) Ships the developer-facing documentation surface for the v1 REST API. Mirrors Stripe's structure (landing → cookbooks → concepts → reference → errors → changelog) at /docs/api with a sticky-sidebar layout in the gnubok editorial-monochrome aesthetic. Every page is also served as plain Markdown via a sibling .md URL so agents and LLM crawlers can ingest the same content without HTML parsing — the existing /llms.txt already promised /docs/api references that this PR makes real. Single source of truth for endpoint metadata is the existing Zod registry (lib/api/v1/registry.ts). The reference pages auto-generate from it: adding a new endpoint surfaces in the docs on the next build with no manual sync. The error reference pulls directly from lib/errors/structured-errors.ts STRUCTURED_ERRORS. CONTENT LAYER (lib/docs/): - content/landing.ts — introduction, auth, base URL, response envelope, the four core principles (dry-run, idempotency, strict-mode, inline audit), pointers to every other section. - content/versioning.ts — versioning + deprecation policy (Stripe dated format), idempotency, dry-run, strict-mode write semantics, inline audit blocks. - content/webhooks.ts — webhook concept guide. Full Node.js (express + crypto) and Python (Flask + hmac) signature-verification samples that match lib/webhooks/signing.ts exactly. Lifecycle, event-type catalogue, payload shape, request headers, common pitfalls, auto-disable behaviour, audit + retention. - content/errors.ts — generated from STRUCTURED_ERRORS. Groups by domain (generic, bookkeeping, periods, invoices, supplier-invoices, transactions, reports, imports, documents, salary, company, provider). Every code is anchorable so the docs_url field on every error envelope finally points somewhere real. - content/reference.ts — generated from listEndpoints(). Groups by resource (companies, customers, invoices, suppliers, supplier-invoices, transactions, journal-entries, fiscal-periods, accounts, documents, employees, salary-runs, reports, imports, compliance, webhooks, operations, voucher-gap-explanations, reconciliation). Each endpoint section: summary, description, useWhen, doNotUseFor, pitfalls, scope, idempotent/reversible/dry-run flags, request + response examples. - content/changelog.ts — initial entry for API version 2026-05-12 covering every endpoint shipped in Phases 1-6. Lists what's coming in Phase 6 PR-3 (hardening + remaining cookbooks). - content/cookbook/quickstart.ts — five-minute send-your-first-invoice guide. Demonstrates auth, dry-run, idempotency, audit-block patterns in one continuous narrative. - content/cookbook/webhooks.ts — end-to-end webhook setup, sig verification, retry handling, idempotency on receiver side, replay patterns, auto-disable behaviour. Companion to the concept page. - content/cookbook/index.ts — recipe registry. 4 placeholder recipes (ingest-bank-transactions, file-vat-declaration, run-payroll-and-agi, year-end-closing) link to their reference pages with a "coming after Phase 6 PR-3 hardening" note. Narrative cookbook quality benefits from a focused pass after the substrate stabilises. - nav.ts — single source of truth for the sidebar nav, used by the layout AND the landing-page resource grid. - markdown.tsx — shared <DocsMarkdown> component using react-markdown (already a dep) with Hedvig serif headlines, Geist mono code blocks, hairline section borders, paper-white surfaces — same editorial aesthetic as the dashboard. LAYOUT (components/docs/DocsLayout.tsx): Two-column sticky-sidebar layout. Top header carries the gnubok mark + section links (API reference, Cookbooks, Errors, Changelog, openapi.json). Sidebar groups: Getting started, Cookbooks, Concepts, API reference, Reference. Active page highlighted with the same warm-beige bg the dashboard sidebar uses. ROUTES (app/docs/api/, app/llms-full.txt/): - /docs/api → landing - /docs/api/errors → error reference - /docs/api/webhooks → webhook concept - /docs/api/versioning → versioning + idempotency + dry-run - /docs/api/changelog → release notes - /docs/api/reference → resource overview - /docs/api/reference/[slug] → per-resource pages (19 resources, all generated from the registry; generateStaticParams listed) - /docs/api/cookbook/[slug] → recipe pages (8 entries, 2 fully written + 6 aliases/placeholders) - /llms-full.txt → everything concatenated for one-shot LLM ingestion Every page has a sibling .md route (e.g. /docs/api/errors.md) serving the raw Markdown for agents — same content, no HTML wrapper, same 5-min cache. Honours the existing /llms.txt promise that "every .md URL under /docs/api is served as plain Markdown". CI GUARD (lib/api/v1/__tests__/spec-snapshot.test.ts): Vitest snapshot test that locks down (a) the endpoint count, (b) the sorted set of method+path keys, (c) the set of distinct scopes referenced. CI fails if any drift unexpectedly so a Zod-schema change can't ship a silent API break — when you intentionally add/remove an endpoint, run with -u to refresh the snapshot, review the diff, and commit alongside the route change. The snapshot diff itself is a self-describing changelog entry. Initial snapshot: 100 endpoints, 17 distinct scopes, full key set sorted. Fourth assertion in the test guarantees every endpoint declares the agent-facing metadata (summary, description, useWhen, doNotUseFor, pitfalls, example) the reference pages depend on — so a registerEndpoint call that omits any of these fields is caught at CI time rather than rendering an empty section in the docs. INFRA TOUCH (lib/api/v1/load-routes.ts): Added the 5 Phase 6 webhook route imports so the registry includes them on the docs builders' path. Required for the /docs/api/reference/ webhooks page to render. The webhook routes' registerEndpoint calls already exist; this just side-effect-imports them where the spec generator can see them. Coming in Phase 6 PR-3 (hardening — separate PR): - 90-day TTL cleanup cron for non-accounting webhook deliveries - claim_due_webhook_deliveries SQL function (FOR UPDATE SKIP LOCKED) - Per-route rate limits on :test, :retry, webhook :create - V16 audit-log on webhook lifecycle events - DNS-rebinding pinned-IP HTTPS agent - Integration tests for webhook routes + *.pg.test.ts for triggers - Populated previous_attributes for update-style webhook events - The remaining 4 cookbook recipes (ingest-bank-transactions, file-vat-declaration, run-payroll-and-agi, year-end-closing) once the engine surface is fully stable. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(api): address PR-497 review round 1 — CI fix + 5 small docs items CI BLOCKER (the reason core-only failed): 1. **Type error on `[slug].md/route.ts` dynamic routes** — Next.js 16's route-type inference can't extract the dynamic segment from a directory whose name contains a literal suffix like `[slug].md/`. It types `params` as `Promise<{}>` and rejects our handler that declares `params: Promise<{ slug: string }>`. The framework still ROUTES requests correctly (URL `/docs/api/cookbook/quickstart.md` reaches the handler) — only the typed `params` is unusable. Fix: drop the typed `params` parameter on the two affected handlers (cookbook + reference) and parse the slug from `request.url.pathname` directly. Inline comment documents the workaround so the next person to touch these doesn't try to "fix" it back to the typed pattern. GREPTILE INLINE (2 items): 2. **Python sample was missing `import json` and `import os`** — the webhook signature-verify sample uses both but only imported `hmac`, `hashlib`, `time`, and `flask`. Added the two missing imports. 3. **`buildResourcePages()` perf — called twice per request** (P2). Each call iterates every registered endpoint, groups by resource, sorts, and serialises Markdown for all 19 resource pages. Memoised at module level — the registry is populated once at module load and immutable for the process lifetime, so a single derivation is safe to cache. Halves the cost on the HTML routes' `generateMetadata` + page render pair, and the .md route handlers (which Next.js doesn't statically pre-render) are now constant-time after the first GET. SWEDISH-COMPLIANCE PRECISION (3 items): 4. **`webhooks.ts`: behandlingshistorik vs räkenskapsinformation distinction.** The previous "Audit + retention" section conflated the two — webhook delivery rows are *behandlingshistorik* (system- event log) per BFNAR 2013:2 kap 8 §, NOT räkenskapsinformation themselves. The 7-year retention from BFL 7 kap 1 § attaches to the underlying verifikation/faktura/AGI XML in its own table, not to the delivery envelope. Updated the section to draw the distinction and clarify gnubok's 7-year retention on accounting-event delivery rows is an operational audit-trail policy, not a statutory obligation passed through to the integrator. 5. **`changelog.ts`: same distinction in the Phase 6 PR-1 entry** — replaced the "räkenskapsinformation" framing with the correct behandlingshistorik framing + the operational-policy note. 6. **Quickstart cookbook: ML 17 kap 24 § p.8 note about `beskattningsunderlag per skattesats`.** The "What just happened" section now explicitly notes that the rendered PDF contains every ML 17 kap 24 § field (including taxable amount per VAT rate) and that the JSON response's summary fields are convenience aggregates for the integration — the binding faktura content is the PDF. Forecloses the misreading that `subtotal + vat_total` is sufficient compliance. 7. **Changelog: BFL 7 kap caveat on SIE export.** The `/reports/ sie-export` line now warns that a SIE4 export alone does NOT satisfy BFL 7 kap archiving obligations — SIE captures account positions and verifikationer but lacks system documentation and behandlingshistorik. Treat as a portability format (Fortnox/Visma/Bokio migration), not as a complete archive. Closes the misreading the swedish-sie-import-export skill flagged. DEFENSIBLE DEFERS (round 1 final): - **CM-8 SPDX-License-Identifier headers per file** (Compliance Swarm). The repo declares AGPL-3.0-or-later in the root LICENSE file, which satisfies licensing for the project as a whole. Per-file SPDX headers are a REUSE-conformance feature; we can address as a sweep across the entire codebase if/when REUSE conformance becomes a requirement. Out of scope for a docs PR. - **`/llms-full.txt` exposes payroll endpoint metadata publicly** (A.8.12). By design — the entire point of the file is one-shot LLM ingestion of the public docs corpus. Endpoint METADATA (path, scope, description) is non-sensitive; actual payroll DATA is gated behind `payroll:read` scope and requires a real API key. Adding an auth gate would defeat the agent-discovery purpose. - **Secret rotation endpoint** (Art.25(2)). Real product gap (delete + recreate is the current rotation path), but it's feature work, not docs. Tracked for Phase 6 PR-3 alongside the other webhook hardening. - **DNS rebinding pinned-IP HTTPS agent** (Art.5(1)(f)). Already documented in this changelog as a Phase 6 PR-3 item; bot is just re-flagging that it's not yet shipped. - **A.5.34 changelog cites GDPR Art.5(1)(c) for personnummer masking without linking privacy policy.** The citation is informational context for developers, not a privacy notice to data subjects. Data- subject notices live at /privacy. Adding a pointer is reasonable; adding it would consume real estate that's better spent on the technical detail. Defer. - **Compliance Swarm A.5.21 third-party attribution in llms-full.txt**. False positive — all markdown content in this PR is original first-party text. No third-party snippets to attribute. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(api): address PR-497 review round 2 — 6 small precision fixes All CI green after round 1 (core-only fixed). Compliance Swarm: 7 → 10 findings is the documented oscillation pattern — net-new actionable items are 6 small fixes; the rest are recurring defers (plaintext-secret variants, SPDX, planned PR-3 features the changelog already lists as "coming soon"). FIXED: 1. **Slug allow-list validation in `[slug].md` routes** (V1.2.5 ×2, medium). The cookbook + reference .md routes parse the slug from the URL pathname (round-1 workaround for Next.js 16's failed inference on `[slug].md/` directories) and pass it to a dictionary-based lookup. The lookup itself is safe — findRecipe / buildResourcePages can't reach SQL or filesystem from a bad slug — but the explicit allow-list gate keeps the contract safe if the lookup mechanism ever changes (file-load, RPC, etc.). Added `Set<string>(COOKBOOK_SLUGS)` + `Set<string>(RESOURCE_SLUGS)` guard before any lookup runs. 2. **Changelog: BFL 5 kap 5 § cited on both `/reverse` AND `/correct`** (swedish-compliance precision). The previous wording cited BFL 5:5 only on `/reverse` (storno) and described `/correct` as plain "rättelse" — but BFL 5:5 governs rättelse generally, and storno is the canonical method of rättelse, so both endpoints satisfy 5:5. Updated to: "/{id}/reverse (storno) and /{id}/correct (rättelse) — both satisfy BFL 5 kap 5 § (storno is the canonical method of rättelse)". 3. **Changelog AGI: explicit that XML is for manual submission** (swedish-compliance / swedish-payroll). Previously said "/generate-agi produces AGI XML" — could be misread as auto-submission to Skatteverket. Now states explicitly that the response carries `data.xml` for the integrator to upload via Skatteverket Mina Sidor (or via the optional `skatteverket` extension), and that the AGI deadline (12th / 17th of the following month) is the integrator's responsibility. Aligns with the route file's existing doNotUseFor + pitfalls metadata. 4. **Quickstart: F-skatt note qualified** (swedish-invoice-compliance). The "What just happened" section previously said the PDF "contains the F-skatt note" — only valid if the seller actually holds F-skatt. Updated to: "The 'Godkänd för F-skatt' note is included automatically when company_settings.has_f_skatt is set — confirm this on the company settings page before sending invoices in production." Also tightened the beskattningsunderlag wording to mention "one line per distinct rate on multi-rate invoices" — closes the swedish-compliance note about the multi-rate claim in the landing needing explicit support in the cookbook. 5. **Cookbook placeholder VAT description: "compute and review" not "submit"** (swedish-vat). The placeholder previously said "Compute momsdeklaration rutor and submit to Skatteverket" — but no Skatteverket-submission endpoint exists in the v1 surface; the API only computes the rutor 05–62 values for manual filing. Updated description in BOTH cookbook/index.ts AND nav.ts (where the same string was duplicated): "Compute momsdeklaration rutor 05–62 and reconcile against the GL before manual submission to Skatteverket." Title also flipped from "File a VAT declaration" to "Compute and review a VAT declaration". 6. **Cookbook nav for AGI: aligned to "generate" semantics**. nav.ts AGI summary used to say "file AGI" — same misreading risk as #3. Now: "Calculate, approve, mark paid, book, generate AGI XML for manual Skatteverket upload." DEFERS (round 2 final — every remaining swarm finding is in one of these buckets): - **🟠 Art.32 plaintext webhook secret + 4 sibling framings** (V14, V11.1, A.8.24, CC6.1). Established defer per Stripe / GitHub / Slack precedent; documented inline in lib/webhooks/signing.ts. Bot is re-flagging via the docs surface this round; underlying position unchanged. - **🟡 Art.5(1)(e) 90-day TTL non-accounting cron + V16 audit log + V2.4 rate limits**. All explicitly listed in the changelog as "Coming soon (Phase 6 PR-3 hardening)". Bot is reading the same text we wrote; not blocking. - **🟠 A.8.11 personnummer masking lacks an automated test**. Real product-hardening request, but it's feature work in the employees test surface, not docs. Tracked. - **🟡 CM-8 SPDX-License-Identifier headers per file**. Established defer from round 1 — root LICENSE covers AGPL-3.0-or-later for the project as a whole; per-file SPDX is a REUSE-conformance sweep that's its own effort. - **🟡 SR-3 SBOM dependencies**. False positive — next/server, react, next/link, next/navigation are existing project deps, not new in this PR. - **swedish-compliance "SIE disclaimer could note immutability requirement"** — the current disclaimer accurately calls out system documentation + behandlingshistorik as missing; adding immutability would over-stuff a one-line caveat. Defer with the understanding that the SIE skill itself documents the immutability requirement for any consumer that follows the reference. If round 3 plateaus (Compliance Swarm count stable, no net-new inline items), that's the merge-ready signal per Phase 4 lessons. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(api): address PR-497 review round 3 — 4 small precision fixes Compliance Swarm: 10 → 3 (down 70%) — net-new actionable items are the 4 below; remaining 3 swarm findings are either trivial defense- in-depth (URL decode, fixed here) or out-of-repo decisions (personnummer disclosure DPO confirmation). FIXED: 1. **URL-decode slug before allow-list check** in both .md route handlers (V1.2.5 ×2 low). The closed allow-list is pure ASCII so a percent-encoded value can't decode to a legitimate slug, but the explicit decode-then-check pattern keeps the contract correct under any future encoding-quirk runtime. try/catch around decodeURIComponent so a malformed % sequence (which throws) returns a clean 404 rather than a 500. 2. **Quickstart: explicit `delivery_date` requirement** (swedish- invoice-compliance / ML 17:24 field 7). The previous wording listed "supply date" as a covered field but didn't note that the API does NOT default delivery_date to invoice_date — integrators shipping invoices for goods delivered on a different date than the invoice date must pass delivery_date explicitly or the rendered PDF is non-compliant. Added explicit pass-it-yourself note. 3. **Quickstart: F-skatt strengthened from "verify" to "legal requirement"** (swedish-invoice-compliance / Peppol BIS 3.0 SE-R-005). The previous "confirm on settings page" wording risked integrators treating the F-skatt note as optional UX. It's a legal requirement on every faktura issued by a company that holds F-skatt registration — and a FATAL Peppol BIS 3.0 validation failure (SE-R-005) for B2G invoices when missing. Reframed as a compliance assertion: the PDF includes it automatically when the setting is true; verifying the setting is correct before production is the integrator's responsibility. 4. **Changelog: SIE post-import VAT code reconfiguration warning** (swedish-sie-import-export). The /imports/sie line previously noted the file format support but didn't warn that SIE files do NOT carry VAT codes or tax-rate-to-account mappings. After migrating from Fortnox / Visma / BL / SpeedLedger / Bokio, integrators must manually reconfigure VAT codes before the first momsdeklaration — skipping this is the most common source of incorrect VAT submissions in migrated bookkeeping. DEFERS (round 3 final — these are the architectural floor): - **🟠 A.5.34 personnummer field name + masking logic disclosed in public docs** (Compliance Swarm). Defensible: documenting that personnummer is masked is a transparency benefit (GDPR Art.13/14 intent), not a privacy disclosure risk. The DPO confirmation prompt is a reasonable governance ask but is an out-of-repo decision — the docs change is appropriate as written. - **AGI penalty amounts (625 / 1,250 SEK)**. Operational guidance for integrators building deadline-tracking; not strictly API-doc material. The deadline (12th / 17th) is documented; integrators who automate compliance can read SFL for penalties. - **VAT period thresholds in the cookbook placeholder**. Belongs in the actual cookbook content when written, not in the placeholder description. - **`invoice.credited` event-naming verification**. False positive — the emitter uses `credit_note.created` (which IS in the docs); there is no `invoice.credited` event in the codebase. Naming is consistent. - **Webhook retention sentence reordering** (swedish-compliance stylistic). Current wording leads with what delivery rows ARE (behandlingshistorik), then clarifies what they are NOT (räkenskapsinformation) — clean teaching arc, the qualifier is prominent. Reordering doesn't change clarity. Round 3 stop signal hit (per Phase 4 lessons): swarm count plateauing at the architectural floor with all remaining findings either defers, false positives, or out-of-repo decisions. Greptile has posted no inline comments since round 1's two items (both fixed). This should be merge-ready. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(api): address PR-497 review round 4 — 5 small precision fixes Compliance Swarm: 3 → 5 (slight uptick from oscillation, but 0 critical, 1 actionable; remaining 4 are recurring or philosophical). swedish-compliance: 7 advisories — 3 actionable precision items incorporated below; the others are forward-looking notes for cookbook content that ships in Phase 6 follow-ups. FIXED: 1. **Spec-snapshot test enforces ep.scope is explicitly defined** (CC6.3, real future-bug prevention). Previously the test asserted every endpoint declared the agent-facing metadata fields the docs depend on, but `scope` could be `undefined` — a registerEndpoint call that silently dropped the field would make the wrapper treat the route as unauthenticated. Added an assertion that `ep.scope !== undefined` (the literal sentinel `null` is allowed for genuinely public endpoints like /api/v1/health). The 4 spec tests still pass — confirming no current endpoint has undefined scope and the gate works prospectively. 2. **F-skatt: integrator responsibility for `has_f_skatt` accuracy** (swedish-invoice-compliance). The previous "verify on settings page" framing didn't connect the flag to the live Skatteverket registration. Now: "The integrator is responsible for keeping has_f_skatt in sync with the company's live Skatteverket registration status. Update via PATCH /api/v1/companies/{id}/ settings or the settings page — a flag that's false while the company is actually F-skatt-registered produces non-compliant invoices, not merely a missing optional note." 3. **AGI deadline qualified by turnover** (swedish-payroll). The previous wording listed "12th / 17th of the following month" with no condition. Now: "12th of the following month for large employers, 17th for companies with annual turnover ≤ 40 MSEK." Aligns with the swedish-payroll skill's AGI filing deadline section. 4. **SIE import warning includes behandlingshistorik gap** (swedish-sie-import-export + swedish-accounting-compliance). The previous warning covered the VAT-code reconfiguration requirement but didn't note that SIE files also do NOT transfer behandlingshistorik (the source system's processing log per BFNAR 2013:2 kap 8 §) or systemdokumentation. Added: "The behandlingshistorik gap must either be preserved separately (export from the source system + archive alongside the SIE file) or accepted with documented justification — gnubok starts a fresh behandlingshistorik from the import date forward." 5. **Webhook 7-year retention: voluntary policy vs statutory obligation** (swedish-accounting-compliance). The previous wording said gnubok keeps delivery rows "for 7 years as an operational audit-trail policy" — the 7-year figure could be misread as statutory. Tightened in BOTH webhooks.ts and changelog.ts: the 7-year statutory retention under BFL 7 kap 1 § applies ONLY to the underlying verifikation/faktura/AGI XML; gnubok's 7-year policy on delivery rows is voluntary and chose the duration to align conveniently with the statutory horizon on the underlying records. DEFERS (round 4 final, all in the architectural-floor bucket): - **🟠 A.5.34 personnummer field name + masking logic disclosed in public docs** (recurring from round 3). Defensible — documenting PII handling is a transparency benefit (GDPR Art.13/14 intent), not a privacy disclosure risk. The DPO confirmation prompt is a reasonable governance ask but is an out-of-repo decision. - **🟡 A.8.23 DNS-rebinding "coming soon" item**. The bot is reading the changelog's own deferral list. Already tracked for Phase 6 PR-3 hardening. - **🟠 CC6.6 SSRF protection details exposed in /llms-full.txt**. Stripe / GitHub / Slack publish their full webhook security posture publicly (signature format, rejected IP ranges, retry policy) — documenting protections IS the trust pattern. Obscurity is not security; the SSRF protection is enforced in code, not in the docs. - **🟡 CC6.7 public CDN caching**. withPublicSecurityHeaders() already applies the appropriate headers (CSP, X-Content-Type- Options, X-Frame-Options). The 5-min cache is appropriate for static developer documentation; the alternative (no caching) is cost without security benefit since the content is intended to be public. - swedish-compliance "VAT 2026-04-01 livsmedel rate change" — forward-looking; ships when the actual VAT cookbook is written. - swedish-compliance "year-end IB/UB continuity" — forward-looking; ships when the year-end cookbook is written. - 2 verify-only notes (rättelse implementation, future salary- journal/avgifter-basis masking sweep) — not actionable in this PR. Round 4 stop signal: every remaining swarm finding is in the deferred or recurring bucket; the actionable item (CC6.3) is shipped. swedish-compliance is now in advisory mode (no errors, just stylistic suggestions and future-cookbook notes). Per Phase 4 lessons, this is the merge-ready signal. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(api): address PR-497 review round 5 — 4 small precision fixes (last actionable items) Compliance Swarm: 5 → 2 (down to architectural floor — 1 high + 1 medium). swedish-compliance: 7 advisories, 4 actionable precision items addressed below; the others are forward-looking notes for content that ships in Phase 6 follow-ups. Trajectory: 7 → 10 → 3 → 5 → 2. Plateaued. FIXED: 1. **Webhook secret storage guidance: secrets manager, not env file** (A.8.5 high). Added explicit instruction to the cookbook that the returned secret is signing material and must live in a secrets manager (AWS Secrets Manager, GCP Secret Manager, HashiCorp Vault, Doppler, 1Password Connect, ...) — not a plaintext .env file or config commit. Treated with the same care as a database password. 2. **AGI deadline correction: 17th = January and August only** (swedish-payroll). Round 4's wording said "12th (large employers) / 17th (≤40 MSEK)" — but per the swedish-payroll skill the 17th applies in January and August specifically, not generally to all months for sub-40 MSEK companies. Other months are the 12th regardless of employer size. Fixed to: "the 12th of the following month for every reporting period EXCEPT January and August, where companies with annual turnover ≤ 40 MSEK get the 17th." This would've caused integrators automating sub-40 MSEK deadline tracking to misfile by 5 days from February through July and September through December. 3. **F-skatt SE-R-005 broader scope** (swedish-invoice-compliance / swedish-e-invoicing). The previous wording framed SE-R-005 as primarily a Peppol B2G validation rule. Reframed: the F-skatt note is a legal requirement on every faktura issued by a Swedish momsregistrerad seller that holds F-skatt registration — applies to PDF/paper AND Peppol/e-invoice formats. The buyer uses it to determine A-skatt withholding obligation (omitting it can shift tax liability onto the buyer); B2G is just where the validation is automated as a FATAL Peppol BIS 3.0 check. 4. **SIE behandlingshistorik gap: full räkenskapsår scope** (swedish-accounting-compliance). Round 4's wording said the integrator "must either preserve [behandlingshistorik] separately or accept the gap with documented justification" and that gnubok "starts a fresh behandlingshistorik from the import date forward." The "documented justification" framing implied the gap was acceptable as a default. Per BFNAR 2013:2 kap 8 §, the obligation attaches to the entire räkenskapsår, not from the import date. Reframed as: "must be preserved separately... best practice for a mid-year migration: export the source system's behandlingshistorik for the full fiscal year and archive it alongside the SIE file." DEFERS (round 5 final — these are the architectural-floor items that will recur indefinitely): - **🟡 A.8.20 DNS-rebinding gap** (Compliance Swarm). Already documented in the changelog as a Phase 6 PR-3 deferral item; the bot is reading the same text we wrote. - **swedish-compliance: VAT 2026-04-01 livsmedel rate change**. Forward-looking — for the actual VAT cookbook recipe content, which ships post-Phase-6. - **swedish-compliance: year-end IB/UB continuity**. Forward-looking — same. - **swedish-compliance: SIE warning placement note**. Forward-looking — for the imports reference page when authored. - **swedish-compliance: BFNAR 2013:2 citation correct, webhook retention correct**. No-op confirmations. - **swedish-compliance: delivery_date pre-payment scenario**. Real but extremely narrow edge case (faktura utfärdad före leverans). Defer with the understanding that anyone using the API for pre-payment invoicing will read the full invoice reference, not rely solely on the quickstart. This is the merge-ready signal per Phase 4 lessons-learned: every remaining swarm finding is in the deferred or recurring bucket; swedish-compliance is in pure-advisory mode (forward-looking notes for cookbook content that ships later); CI is fully green; Greptile posted nothing past round 1's two items (both fixed). Ship it. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
242 lines
12 KiB
TypeScript
242 lines
12 KiB
TypeScript
export const WEBHOOKS_MD = `# Webhooks
|
|
|
|
> Receive HMAC-signed POST notifications when state changes in gnubok — invoices paid, journal entries committed, periods locked, salary runs booked, AGI files generated. At-least-once delivery with exponential backoff over ~72 hours.
|
|
|
|
If you've used [Stripe webhooks](https://docs.stripe.com/webhooks), the model is identical: subscribe a URL to an event type, gnubok POSTs each event with a signed JSON body, your receiver returns 2xx to acknowledge. The signature header format and retry policy are the same. The event types are gnubok-specific.
|
|
|
|
## Lifecycle
|
|
|
|
1. **Register a receiver** with [\`POST /api/v1/companies/{companyId}/webhooks\`](/docs/api/reference/webhooks#post-webhooks). The response includes an HMAC signing secret returned **exactly once** — store it on the receiver side immediately. If you lose it, delete the webhook and create a new one.
|
|
2. **gnubok emits events** internally (e.g. an invoice is marked paid via the dashboard or another API call). The webhook handler enqueues a delivery row.
|
|
3. **The dispatcher cron runs every minute**, signs the payload with HMAC-SHA256, and POSTs to your URL with a 10-second timeout.
|
|
4. **Your receiver verifies the signature**, processes the event idempotently, and returns 2xx.
|
|
5. **Failed deliveries retry** at \`1m / 5m / 30m / 2h / 12h / 24h / 48h\` (7 retries, ~72 hours total). After all attempts the delivery is marked \`dead\`. HTTP 410 from your receiver short-circuits to \`dead\` immediately and **auto-disables** the webhook.
|
|
|
|
## Event types
|
|
|
|
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\`
|
|
|
|
## Payload shape
|
|
|
|
Every delivery wraps the event in a Stripe-style envelope:
|
|
|
|
\`\`\`json
|
|
{
|
|
"id": "wh_dlv_a8f1...",
|
|
"type": "invoice.paid",
|
|
"api_version": "2026-05-12",
|
|
"created": 1715797800,
|
|
"data": {
|
|
"object": {
|
|
"invoice": { "id": "...", "invoice_number": "2026-0042", "total": 12500.00, ... },
|
|
"paymentAmount": 12500.00,
|
|
"paymentDate": "2026-05-15",
|
|
"companyId": "..."
|
|
}
|
|
},
|
|
"previous_attributes": null
|
|
}
|
|
\`\`\`
|
|
|
|
- \`id\` matches the \`webhook_delivery_id\` you can poll at [\`GET /webhooks/{webhookId}/deliveries\`](/docs/api/reference/webhooks#get-deliveries).
|
|
- \`api_version\` is the version pinned to your webhook at creation time. Payload shapes for *your* webhook will not change until you explicitly upgrade.
|
|
- \`previous_attributes\` carries the prior values of any fields that changed on update-style events (e.g. \`invoice.paid\` carries the prior invoice state). \`null\` for create-style events.
|
|
|
|
## Request headers
|
|
|
|
Every outbound POST carries:
|
|
|
|
\`\`\`
|
|
POST /your-receiver-url HTTP/1.1
|
|
Content-Type: application/json
|
|
User-Agent: gnubok-webhook/1
|
|
X-Gnubok-Signature: t=1715797800,v1=2f5c...
|
|
X-Gnubok-Event: invoice.paid
|
|
X-Gnubok-Delivery: wh_dlv_a8f1...
|
|
X-Gnubok-Api-Version: 2026-05-12
|
|
X-Request-Id: whdel_a8f1...
|
|
\`\`\`
|
|
|
|
The \`X-Gnubok-Delivery\` header is the canonical correlation id — log it on receipt and use it to deduplicate retries (deliveries are at-least-once, so the same delivery id may arrive more than once after a network blip).
|
|
|
|
## Verifying signatures
|
|
|
|
The signature header has the format \`t=<unix-seconds>,v1=<hex-HMAC-SHA256>\`. The signed payload is \`\${t}.\${rawBody}\` — the timestamp is included so receivers can implement a replay window (we recommend rejecting deliveries with \`t\` more than 5 minutes old).
|
|
|
|
You **must** verify the signature on every delivery before processing it. Without verification, anyone who learns your URL can forge events.
|
|
|
|
### Node.js
|
|
|
|
\`\`\`javascript
|
|
import crypto from 'node:crypto'
|
|
import express from 'express'
|
|
|
|
const app = express()
|
|
const SECRET = process.env.GNUBOK_WEBHOOK_SECRET // whsec_...
|
|
|
|
// Important: capture the RAW body before any JSON parsing — the signature
|
|
// is computed against the exact bytes gnubok sent, not a re-serialised JSON.
|
|
app.post(
|
|
'/webhook',
|
|
express.raw({ type: 'application/json' }),
|
|
(req, res) => {
|
|
const sigHeader = req.header('x-gnubok-signature') ?? ''
|
|
const rawBody = req.body.toString('utf8')
|
|
|
|
if (!verifySignature(rawBody, sigHeader, SECRET)) {
|
|
return res.status(400).send('invalid signature')
|
|
}
|
|
|
|
const event = JSON.parse(rawBody)
|
|
// Idempotency: process the delivery id once.
|
|
if (alreadyProcessed(event.id)) return res.status(200).send('ok')
|
|
handleEvent(event)
|
|
return res.status(200).send('ok')
|
|
},
|
|
)
|
|
|
|
function verifySignature(body, header, secret) {
|
|
const parts = Object.fromEntries(
|
|
header.split(',').map((p) => p.split('=', 2)),
|
|
)
|
|
const t = Number.parseInt(parts.t, 10)
|
|
const v1 = parts.v1
|
|
if (!t || !v1) return false
|
|
|
|
// Reject deliveries older than 5 minutes — replay protection.
|
|
const ageSec = Math.floor(Date.now() / 1000) - t
|
|
if (Math.abs(ageSec) > 300) return false
|
|
|
|
const expected = crypto
|
|
.createHmac('sha256', secret)
|
|
.update(\`\${t}.\${body}\`)
|
|
.digest('hex')
|
|
|
|
// Constant-time comparison.
|
|
const expectedBuf = Buffer.from(expected, 'hex')
|
|
const actualBuf = Buffer.from(v1, 'hex')
|
|
if (expectedBuf.length !== actualBuf.length) return false
|
|
return crypto.timingSafeEqual(expectedBuf, actualBuf)
|
|
}
|
|
\`\`\`
|
|
|
|
### Python
|
|
|
|
\`\`\`python
|
|
import hmac
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import time
|
|
from flask import Flask, request, abort
|
|
|
|
app = Flask(__name__)
|
|
SECRET = os.environ["GNUBOK_WEBHOOK_SECRET"].encode("utf-8") # whsec_...
|
|
|
|
@app.post("/webhook")
|
|
def webhook():
|
|
raw_body = request.get_data() # bytes — must be the raw request body
|
|
sig_header = request.headers.get("X-Gnubok-Signature", "")
|
|
|
|
if not verify_signature(raw_body, sig_header, SECRET):
|
|
abort(400, "invalid signature")
|
|
|
|
event = json.loads(raw_body)
|
|
if already_processed(event["id"]):
|
|
return "", 200
|
|
handle_event(event)
|
|
return "", 200
|
|
|
|
|
|
def verify_signature(body: bytes, header: str, secret: bytes) -> bool:
|
|
parts = dict(p.split("=", 1) for p in header.split(","))
|
|
try:
|
|
t = int(parts["t"])
|
|
v1 = parts["v1"]
|
|
except (KeyError, ValueError):
|
|
return False
|
|
|
|
# Replay protection: 5-minute window.
|
|
if abs(int(time.time()) - t) > 300:
|
|
return False
|
|
|
|
signed = f"{t}.".encode("utf-8") + body
|
|
expected = hmac.new(secret, signed, hashlib.sha256).hexdigest()
|
|
return hmac.compare_digest(expected, v1)
|
|
\`\`\`
|
|
|
|
### Common pitfalls
|
|
|
|
- **Using parsed JSON instead of raw bytes.** Re-serialising the body (\`JSON.stringify(req.body)\`) produces different bytes than gnubok sent — the signature won't match. Capture the raw body before any framework parses it.
|
|
- **Forgetting the timestamp window.** Without checking \`t\`, an attacker who captured one signed payload can replay it forever. 5 minutes is our recommended window; tighten if your clock skew is small.
|
|
- **Treating retries as duplicates of failure.** Retries arrive when *we* didn't get a 2xx. A 200 response that arrives slowly may not reach us in time and we'll retry — your receiver sees the same \`X-Gnubok-Delivery\` twice. Idempotency is on you.
|
|
- **Returning 5xx for application errors.** A 5xx triggers the full retry policy (~72h of attempts). If your handler hit an application bug that won't resolve on retry, return 200 and queue the failure for internal investigation; only return 5xx for genuinely transient problems.
|
|
- **Missing \`redirect: 'error'\`-style refusal at receiver level.** If your receiver follows redirects, an attacker who can MITM the response could redirect re-tries to a malicious URL. Modern HTTP clients refuse redirects by default for POST; verify yours does.
|
|
|
|
## Delivery debugging
|
|
|
|
Use [\`GET /api/v1/companies/{companyId}/webhooks/{webhookId}/deliveries\`](/docs/api/reference/webhooks#get-deliveries) to list the recent delivery history for a webhook — every row has the response status, response body (truncated to 4 KB, only \`text/plain\` and \`application/json\` content types persisted), error message, and current state (\`pending\` / \`in_flight\` / \`delivered\` / \`failed\` / \`dead\`).
|
|
|
|
To replay a \`dead\` or \`delivered\` delivery, call [\`POST /api/v1/webhook-deliveries/{deliveryId}/retry\`](/docs/api/reference/webhooks#post-retry). The retry creates a fresh delivery row pointing at the same payload — the original audit row stays in place. Receivers must be idempotent on the \`X-Gnubok-Delivery\` header.
|
|
|
|
To send a synthetic test event without driving real state, call [\`POST /webhooks/{webhookId}/test\`](/docs/api/reference/webhooks#post-test). The dispatcher delivers a \`webhook.test\` event with a static payload on the next per-minute tick.
|
|
|
|
## Auto-disable behaviour
|
|
|
|
The dispatcher disables a webhook (sets \`active=false\` + \`disabled_reason\`) and stops attempting delivery when:
|
|
|
|
- The receiver returns **HTTP 410 Gone** — explicit "stop sending"
|
|
- The receiver returns **HTTP 3xx redirect** — refusing to follow redirects to internal IPs is a security policy; a stable receiver should not return 3xx
|
|
- The webhook URL **resolves to a private/loopback/link-local/cloud-metadata IP** at dispatch time (DNS rebinding refusal)
|
|
|
|
Re-enable with [\`PATCH /webhooks/{webhookId}\`](/docs/api/reference/webhooks#patch-webhooks) setting \`active: true\`. This clears \`disabled_at\` + \`disabled_reason\` but does NOT replay the deliveries that died while disabled — replay them individually with the retry endpoint.
|
|
|
|
## Audit + retention
|
|
|
|
Webhook delivery rows are *behandlingshistorik* (a system-event log) per BFNAR 2013:2 kap 8 § — they are immutable once they reach a terminal state (\`delivered\` or \`dead\`) so the audit trail of who-was-notified-when stays intact. The underlying *räkenskapsinformation* (the verifikation, the faktura, the AGI XML itself) lives in its own table with its own BFL 7 kap retention — webhook delivery rows are NOT räkenskapsinformation and the 7-year retention applies to the underlying record, not to the delivery envelope.
|
|
|
|
For accounting-event delivery rows (\`journal_entry.*\`, \`period.*\`, \`salary_run.booked\`, \`agi.generated\`, \`invoice.paid\`, \`supplier_invoice.paid\`), gnubok keeps the delivery rows for 7 years. **This is a voluntary operational audit-trail policy gnubok chose because the duration aligns conveniently with BFL 7 kap retention on the underlying records — it is NOT itself a statutory obligation.** The 7-year statutory retention under BFL 7 kap 1 § applies to the underlying verifikation / faktura / AGI XML in its own table, not to the delivery envelope. The integrator's own retention obligations likewise attach to the underlying records you receive (and any local copies you persist), not to the delivery-row metadata.
|
|
|
|
Deleting a webhook does not delete its delivery history; the FK is \`ON DELETE SET NULL\` so the audit trail survives.
|
|
`
|