docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
-338
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,104 +0,0 @@
|
||||
# Settlement account remediation
|
||||
|
||||
Use this runbook to review journal entries that may have been posted against a
|
||||
different settlement account than the cash account linked to their source bank
|
||||
transaction. It covers historical entries created before and around the fixes
|
||||
for issues #985, #986, and #987.
|
||||
|
||||
The audit is intentionally broader than a list of confirmed errors. A current
|
||||
`cash_account_id` does not prove that the transaction had that link when the
|
||||
entry was posted. Never correct an entry from query output alone.
|
||||
|
||||
## Invariants
|
||||
|
||||
- Never edit or delete a posted journal entry.
|
||||
- Correct a confirmed error with storno plus a replacement entry through
|
||||
`gnubok_correct_entry`.
|
||||
- Keep every replacement line balanced and preserve the original line metadata.
|
||||
- Do not write directly to `journal_entries` or `journal_entry_lines`.
|
||||
- Do not correct a locked or closed period without a separately reviewed and
|
||||
explicitly approved unlock or reopening workflow.
|
||||
- Never run a production correction without explicit approval for the exact
|
||||
company, vouchers, and replacement lines.
|
||||
|
||||
## Detect candidates
|
||||
|
||||
Run [`scripts/audit-settlement-account-mismatches.sql`](../scripts/audit-settlement-account-mismatches.sql)
|
||||
against the intended database. The query is read-only and returns current
|
||||
posted entries whose exact directional settlement leg differs from
|
||||
`cash_accounts.ledger_account`.
|
||||
|
||||
Treat `review_priority` only as an ordering aid:
|
||||
|
||||
- `high_review_priority_hardcoded_1930_signature` matches the known historical
|
||||
failure shape, but still needs evidence review.
|
||||
- `manual_review_payment_aware_correction_required` identifies a payment flow with a
|
||||
mismatching account. Detection is supported, but the generic correction
|
||||
procedure below is not. Stop and use a payment-aware correction path.
|
||||
- Every `manual_review_*` result may be a later cash-account link, a manual
|
||||
reconciliation, or another legitimate accounting shape.
|
||||
|
||||
## Review each candidate
|
||||
|
||||
1. Confirm the transaction belongs to the reported cash account using the
|
||||
original bank feed or statement and the bank connection metadata.
|
||||
2. Confirm that the cash-account link existed when the journal entry was
|
||||
posted. `transaction_updated_at` close to `committed_at` is supporting
|
||||
evidence, not proof.
|
||||
3. Fetch the current journal entry and all lines. Stop if the entry was already
|
||||
reversed, corrected, or linked manually after posting.
|
||||
4. Confirm there is exactly one settlement leg and that its direction and SEK
|
||||
amount match the bank transaction.
|
||||
5. Confirm the only required accounting change is replacing the observed
|
||||
settlement account with `expected_settlement_account`.
|
||||
6. Check `effective_lock_status`. Both the fiscal period's `is_closed` and
|
||||
`locked_at` fields and the company-wide `bookkeeping_locked_through` date
|
||||
are authoritative lock layers. Any result other than `open` is a hard stop
|
||||
for the ordinary correction flow. If VAT has already been filed, determine
|
||||
whether an omprövning is required before reopening anything.
|
||||
7. Stop when `booking_flow` is `customer_invoice_payment` or
|
||||
`supplier_invoice_payment`. The generic correction service does not relink
|
||||
all invoice-payment references from the reversed entry. A payment-aware,
|
||||
tested correction procedure is required for those candidates.
|
||||
|
||||
Keep the reviewed candidate set, evidence, proposed replacement lines, and
|
||||
reviewer identity together as the correction record.
|
||||
|
||||
## Stage the correction
|
||||
|
||||
For a confirmed candidate in an open and unlocked period:
|
||||
|
||||
1. Re-run the audit query immediately before staging and retain its
|
||||
`original_lines` value. It includes currency amounts, exchange rates, tax
|
||||
codes, dimensions, cost centers, and projects that the ordinary journal
|
||||
query does not return.
|
||||
2. Re-fetch the entry with `gnubok_query_journal` to confirm that its status,
|
||||
voucher, amounts, and visible lines still match the fresh audit result.
|
||||
3. Copy every object from `original_lines` into the `lines` input for
|
||||
`gnubok_correct_entry`.
|
||||
4. On the one confirmed settlement line, replace only `account_number` with
|
||||
`expected_settlement_account`.
|
||||
5. Preserve debit and credit amounts, line descriptions, currency metadata,
|
||||
tax codes, dimensions, cost centers, and projects exactly as recorded.
|
||||
6. Verify that total debits equal total credits and both totals are positive.
|
||||
7. Stage `gnubok_correct_entry` using the voucher reference or freshly fetched
|
||||
entry UUID. Review its original and correction previews line by line.
|
||||
The preview must show the preserved currency, tax, and dimension metadata.
|
||||
8. Approve the staged operation with `gnubok_approve_pending_operation` only
|
||||
after the exact operation has explicit authorization. High-risk approval
|
||||
requires `confirmed: true`.
|
||||
|
||||
Do not use `gnubok_reverse_journal_entry` by itself for this case. The business
|
||||
event remains valid; only its settlement account is being corrected.
|
||||
|
||||
## Verify after approval
|
||||
|
||||
1. Confirm the original entry is retained with status `reversed`.
|
||||
2. Confirm a posted storno and a posted corrected entry were created in the
|
||||
intended fiscal period.
|
||||
3. Confirm the bank transaction now links to the posted corrected entry.
|
||||
4. Confirm the corrected settlement leg uses the expected account and amount.
|
||||
5. Run `gnubok_get_general_ledger` for both the observed and expected accounts.
|
||||
6. Re-run the audit query. The corrected transaction must no longer appear.
|
||||
7. Record the new voucher references and verification evidence with the
|
||||
reviewed candidate set.
|
||||
File diff suppressed because one or more lines are too long
@@ -1,192 +0,0 @@
|
||||
# Template mis-booking remediation
|
||||
|
||||
Use this runbook to review posted entries that a defective booking template may
|
||||
have mis-classified, and to correct the confirmed ones lawfully.
|
||||
|
||||
Companion to [`SETTLEMENT_ACCOUNT_REMEDIATION.md`](./SETTLEMENT_ACCOUNT_REMEDIATION.md),
|
||||
which covers the same class of problem for settlement legs. The invariants and
|
||||
the correction mechanics are identical; only the detection differs.
|
||||
|
||||
## Which defects this covers
|
||||
|
||||
Two templates produced postings that **succeeded** and are therefore sitting in
|
||||
customers' huvudböcker today:
|
||||
|
||||
| Defect | Was | Should be | Fixed in |
|
||||
|---|---|---|---|
|
||||
| `travel_hotel` debited car hire | `5820` Hyrbilskostnader | `5830` Kost och logi | #1397 |
|
||||
| Representation over-deducted VAT | 25% input VAT | 12% (restaurang/servering) | #1396 |
|
||||
|
||||
**Deliberately not covered:** `vehicle_parking` (`5614`) and `it_cloud_hosting`
|
||||
(`5421`) named accounts that never existed in BAS 2026. `account-backfill.ts`
|
||||
only seeds accounts present in `BAS_REFERENCE`, so those templates failed with
|
||||
`AccountsNotInChartError` every time and **nothing was ever posted through
|
||||
them**. There is nothing to remediate.
|
||||
|
||||
## What the law requires
|
||||
|
||||
BFL 5 kap 5 §: a rättelse must leave both the original and the correction
|
||||
visible, and record when it was made and by whom. Silent overwriting is never
|
||||
permitted. A manual book may use a readable strike-and-replace correction while
|
||||
the bookkeeping is still open. This runbook is for Accounted's computerized
|
||||
bookkeeping and supports only a **särskild rättelsepost**: storno plus a
|
||||
correcting verifikation linked to the original through `gnubok_correct_entry`.
|
||||
|
||||
There is **no numeric materiality threshold in BFL**. Materiality governs
|
||||
whether a historical correction is worth making, not whether the law permits a
|
||||
silent one: it never does.
|
||||
|
||||
For the VAT defect specifically, if the affected period's momsdeklaration has
|
||||
already been filed, an over-deducted input VAT means an **omprövning** to
|
||||
Skatteverket, not merely a ledger correction. Establish that before touching
|
||||
anything.
|
||||
|
||||
## Invariants
|
||||
|
||||
- Never edit or delete a posted journal entry.
|
||||
- Correct a confirmed error with storno plus a replacement through
|
||||
`gnubok_correct_entry`. Never `gnubok_reverse_journal_entry` alone: the
|
||||
business event remains valid, only its classification is wrong.
|
||||
- Do not write directly to `journal_entries` or `journal_entry_lines`.
|
||||
- Any `effective_lock_status` other than `open` is a hard stop for the current
|
||||
`gnubok_correct_entry` path. Never unlock, reopen or edit the original merely
|
||||
to make a correction possible. A locked-period correction requires a
|
||||
separately reviewed and tested path that records a storno and replacement in
|
||||
an open period, references the original, and preserves who corrected it and
|
||||
when. If a declaration or closing relied on the locked period, establish the
|
||||
required omprövning or closing consequences before requesting approval.
|
||||
- Never run a production correction without explicit approval for the exact
|
||||
company, vouchers and replacement lines.
|
||||
- No automated bulk mutation. Ever.
|
||||
|
||||
## Detect candidates
|
||||
|
||||
Run [`scripts/audit-template-misbookings.sql`](../scripts/audit-template-misbookings.sql)
|
||||
against the intended database. It is read-only, creates nothing, and returns
|
||||
only posted entries.
|
||||
|
||||
The audit now separates the broad signature from the evidence classification.
|
||||
There is no direct template id on a journal entry, but `source_type`, exact line
|
||||
shape, transaction context and linked underlag can rule candidates in or out.
|
||||
Both signatures still have legitimate shapes:
|
||||
|
||||
- `5820` is the **correct** account for actual car hire.
|
||||
- Representation at 25% is lawful only when the supply is actually subject to
|
||||
25% VAT and the supplier invoice is correct.
|
||||
|
||||
Read `evidence_classification` as the remediation queue:
|
||||
|
||||
| Classification | Meaning |
|
||||
|---|---|
|
||||
| `confirmed_correction` | Exact defective shape plus corroborating evidence. Review the underlag, then stage `gnubok_correct_entry` and request explicit approval for the exact voucher and replacement lines. |
|
||||
| `insufficient_evidence` | The shape matches, but the underlag or provenance is not decisive. Obtain evidence before proposing any write. |
|
||||
| `false_positive` | Not attributable to either defective live template. This is not a general verdict that every aspect of the voucher is correct. |
|
||||
|
||||
`source_type` values `import` and `correction` are false positives for this
|
||||
template-remediation audit because neither live template generated them. Keep
|
||||
any independent accounting concern outside this remediation batch.
|
||||
|
||||
Linked underlag is resolved from direct journal-entry and journal-line links,
|
||||
transactions and supplier invoices. Document identifiers and extracted VAT
|
||||
signals are returned, but storage paths and file names are not. A decisive 25%
|
||||
extraction on a representation voucher rules out the defective 12% restaurant
|
||||
template signature. It does not by itself prove that the representation cap,
|
||||
participant record or business purpose was handled correctly.
|
||||
|
||||
Every representation row therefore carries
|
||||
`independent_representation_review = participants_purpose_and_300_sek_vat_base_cap_required`.
|
||||
`observed_6072_cost_exceeds_300_sek` is a triage signal only: the statutory cap
|
||||
is per person and occasion, so the number of participants and the underlag are
|
||||
still required.
|
||||
|
||||
Read `review_priority` as a supporting ordering aid:
|
||||
|
||||
| Priority | Meaning |
|
||||
|---|---|
|
||||
| `high_hotel_counterparty_on_car_hire_account` | A `5820` line with a hotel-shaped counterparty. The strongest signal, still needs evidence. |
|
||||
| `medium_12pct_vat_on_car_hire_account` | `5820` with 12% VAT beside it. Car hire is 25%, so this is suggestive. |
|
||||
| `high_vat_is_25pct_of_6072_cost` | Representation whose input VAT is 25% of the cost leg. |
|
||||
| `manual_review_5820_no_corroborating_signal` | A `5820` entry with no hotel-shaped text or 12% VAT ratio. Most likely legitimate car hire. |
|
||||
| `manual_review_6072_with_vat` | A `6072` entry with `2641` VAT whose aggregate ratio is not exactly 25%. It may be correct or may be a mixed voucher masking the defective representation leg. |
|
||||
|
||||
The classifier is verified against read-only probes for confirmed, insufficient
|
||||
and false-positive outcomes. The audit aggregates multiple `6072` and `2641`
|
||||
lines per entry and returns one candidate instead of a many-to-many set of line
|
||||
pairs. Mixed representation vouchers without decisive underlag remain
|
||||
`insufficient_evidence`; they are never cleared merely because their aggregate
|
||||
VAT ratio differs from the exact defective 25% signature.
|
||||
|
||||
Treat lock and VAT-return impact as overlays, not evidence classes:
|
||||
|
||||
- `effective_lock_status` identifies candidates that the current correction
|
||||
service cannot handle. Never unlock or reopen merely to permit a correction.
|
||||
- `vat_return_impact = potential_if_confirmed` means a representation candidate
|
||||
could affect ruta 48. Determine the filing status before requesting approval.
|
||||
- `vat_reporting_period`, `vat_deadline_statuses` and `vat_filing_status`
|
||||
surface the in-app filing record. `not_proven_by_in_app_records` is unknown,
|
||||
not proof that no declaration was filed externally.
|
||||
- Keep exact company and voucher identifiers in an access-controlled approval
|
||||
manifest. Public issue updates should use aggregate batches unless disclosure
|
||||
has been explicitly approved.
|
||||
|
||||
## Review each candidate
|
||||
|
||||
1. Open the underlag (kvitto/faktura) and confirm what was actually purchased.
|
||||
A hotel night and a rental car are both plausible on `5820`.
|
||||
2. For the VAT defect, classify the actual supply and determine the legally
|
||||
applicable rate; do not accept the invoice rate as proof. Restaurant and
|
||||
catering supplies are normally 12%, while alcohol and some mixed supplies
|
||||
can include 25%. If the supplier charged an inapplicable rate, request a
|
||||
corrected invoice before treating any input VAT as deductible or clearing
|
||||
the candidate.
|
||||
3. Fetch the entry and all lines. Stop if it was already reversed or corrected.
|
||||
4. Check `effective_lock_status`. Anything other than `open` is a hard stop.
|
||||
5. For the VAT defect, establish whether the period's momsdeklaration has been
|
||||
filed. If so, an omprövning is in scope and the ledger correction alone is
|
||||
not sufficient.
|
||||
6. Decide materiality. A 40 kr VAT difference on one lunch two years ago in a
|
||||
closed period may not warrant a separate correction in an open period; a
|
||||
systematic error across a year is different. Record the decision either way.
|
||||
|
||||
Keep the reviewed set, the evidence, the proposed replacement lines and the
|
||||
reviewer identity together as the correction record.
|
||||
|
||||
## Stage the correction
|
||||
|
||||
Follow the identical procedure in
|
||||
[`SETTLEMENT_ACCOUNT_REMEDIATION.md`](./SETTLEMENT_ACCOUNT_REMEDIATION.md#stage-the-correction):
|
||||
retain `original_lines`, copy every original line, change only what is wrong,
|
||||
verify the replacement balances, stage
|
||||
`gnubok_correct_entry`, and approve only with explicit authorisation.
|
||||
|
||||
`gnubok_correct_entry` routes through `correctEntry()` in
|
||||
`lib/core/bookkeeping/storno-service.ts`. It retains the original, creates a
|
||||
posted storno with `reverses_id`, creates the replacement with
|
||||
`correction_of_id`, and records the acting user and timestamps. Never replace
|
||||
this audited envelope with direct journal-table writes.
|
||||
|
||||
For the hotel defect, the only change is `account_number` on the cost line,
|
||||
`5820` to `5830`.
|
||||
|
||||
For the VAT defect, the cost and VAT amounts change while accounts `6072` and
|
||||
`2641`, the gross total, and the settlement leg remain unchanged. Calculate the
|
||||
deductible VAT from the corrected invoice and the representation rules,
|
||||
including the 300 SEK base per person and occasion. Do not blindly divide the
|
||||
gross by 1.12 when the receipt mixes rates or exceeds the deduction cap;
|
||||
non-deductible VAT remains on `6072`.
|
||||
|
||||
Journal lines have no `vat_rate` field. `tax_code` is a free-text tag and does
|
||||
not drive the VAT return, but if it explicitly encodes the obsolete 25% rate,
|
||||
update or clear it so the corrected entry is not misleading. Preserve currency,
|
||||
`amount_in_currency`, `exchange_rate`, descriptions, dimensions, cost centers,
|
||||
projects, and unrelated tax metadata exactly as recorded.
|
||||
|
||||
## Verify after approval
|
||||
|
||||
1. The original is retained with status `reversed`.
|
||||
2. A posted storno and a posted corrected entry exist in the intended period.
|
||||
3. The corrected leg uses the expected account and amount.
|
||||
4. Re-run the audit query: the corrected entry no longer appears.
|
||||
5. For the VAT defect, re-run the momsdeklaration for the period and confirm
|
||||
ruta 48 moves by the expected amount.
|
||||
6. Record the new voucher references with the correction record.
|
||||
File diff suppressed because one or more lines are too long
@@ -1,74 +0,0 @@
|
||||
# Arkitektur — ACCOUNTED
|
||||
|
||||
> **Status:** automatisk första version, genererad av `siax-scaffold` ur repots
|
||||
> faktiska filer. Den beskriver vad som finns, inte vad som är bestämt. Läs
|
||||
> igenom, rätta och fyll i avsnitten som är markerade TODO innan dokumentet
|
||||
> betraktas som en arkitekturbeskrivning (ARK-serien).
|
||||
|
||||
Senast verifierad mot kod: 2026-11-10
|
||||
|
||||
## 1. Översikt
|
||||
|
||||
| Fält | Värde |
|
||||
| --- | --- |
|
||||
| Repo | `accounted` |
|
||||
| Körtid | node |
|
||||
| Ramverk | Next.js |
|
||||
| Paketnamn | `erp-base` |
|
||||
| Domäner i `siax.config.json` | inga |
|
||||
|
||||
|
||||
## 2. Komponenter
|
||||
|
||||
Toppnivåkataloger som innehåller kod eller konfiguration (härledda ur filträdet):
|
||||
|
||||
| Katalog | Roll |
|
||||
| --- | --- |
|
||||
| `packages/` | TODO: beskriv katalogens roll (packages) |
|
||||
| `lib/` | TODO: beskriv katalogens roll (lib) |
|
||||
| `scripts/` | TODO: beskriv katalogens roll (scripts) |
|
||||
| `docs/` | TODO: beskriv katalogens roll (docs) |
|
||||
| `tests/` | TODO: beskriv katalogens roll (tests) |
|
||||
|
||||
Undermoduler som är deklarerade i `children[]`:
|
||||
|
||||
| Sökväg | Syfte |
|
||||
| --- | --- |
|
||||
| — | Inga undermoduler (apps/, packages/, services/) finns. |
|
||||
|
||||
## 3. Startpunkter
|
||||
|
||||
| Fil | Typ |
|
||||
| --- | --- |
|
||||
| — | Ingen startpunkt hittades i `package.json`, `pyproject.toml` eller `Dockerfile`. |
|
||||
|
||||
## 4. Språk och filfördelning
|
||||
|
||||
| Ändelse | Omfattning |
|
||||
| --- | --- |
|
||||
| .ts | 3878 filer |
|
||||
| .tsx | 667 filer |
|
||||
| .mjs | 21 filer |
|
||||
| .sh | 8 filer |
|
||||
| .js | 3 filer |
|
||||
| .py | 2 filer |
|
||||
|
||||
## 5. Dataflöde
|
||||
|
||||
TODO: beskriv hur data rör sig genom repot: inkommande anrop/jobb → lagring → utdata, och vilka externa system som anropas. Scaffolden kan inte härleda detta ur filerna.
|
||||
|
||||
## 6. Gränser och beroenden
|
||||
|
||||
TODO: lista vilka SIAX-komponenter repot äger respektive konsumerar (REUSE FIRST), samt vilka kontrakt som är stabila utåt. Se `siax.repo.json` → `consumes`/`consumedBy`.
|
||||
|
||||
## 7. Drift och miljöer
|
||||
|
||||
Ingen `siax.config.json` finns — repot är inte deklarerat som driftsatt. Om det driftsätts ska `siax.config.json` skapas först (REPO-06).
|
||||
|
||||
TODO: verifiera mot faktisk nod och `docker ps` (GOV-06). Ett dokument får inte påstå drift som inte är mätt.
|
||||
|
||||
## 8. Källhänvisning
|
||||
|
||||
- Genererad: 2026-11-10 av `siax-scaffold` (scaffold 2026-11-09).
|
||||
- Underlag: filträdet, `package.json`/`pyproject.toml`, `Dockerfile`, `siax.repo.json`.
|
||||
- Ändringslogg: se `CHANGELOG.md` och git-historiken.
|
||||
@@ -1,47 +0,0 @@
|
||||
# SCAFFOLD-TODO — vad som är härlett och vad som måste verifieras
|
||||
|
||||
**Genererad:** 2026-11-10 av `siax-scaffold` (siax-standard,
|
||||
`packages/scaffold`) mot Golden Standard v2.0.
|
||||
|
||||
Den här filen finns för att en mall inte får låtsas veta saker. Varje rad nedan
|
||||
är antingen **härledd ur repot** (källan står i kolumn 3) eller ett
|
||||
**konservativt defaultvärde** som en människa måste bekräfta. Radera raden när
|
||||
den är verifierad — filen ska till slut kunna tas bort helt.
|
||||
|
||||
## Härledda värden i `siax.repo.json`
|
||||
|
||||
| Fält | Värde | Härlett ur |
|
||||
|---|---|---|
|
||||
| `repo` | `ACCOUNTED` | `git remote.origin.url` (VERSALER per REPO-08) |
|
||||
| `codeowners` | `["@sax3l"]` | default (organisationens ägare) |
|
||||
| `category` | `platform` | DEFAULT — ej härledbart |
|
||||
| `subcategory` | `TODO: fyll i underkategori (t.ex. compute-os, saas-ersättare)` | TODO-markör |
|
||||
| `operationalState` | `degraded` | driftsartefakter finns (Dockerfile) — EJ VERIFIERAT driftläge |
|
||||
| `domains` | `0 st` | inga funna |
|
||||
| `children` | `3 st` | faktiska kataloger under apps/, packages/, services/ |
|
||||
| `packageName` | `erp-base` | `package.json` → name |
|
||||
|
||||
## Måste verifieras av människa
|
||||
|
||||
- [ ] Bekräfta `codeowners` — scaffolden defaultade till `@sax3l` (CI-14).
|
||||
- [ ] Verifiera `category` i `siax.repo.json` mot den kanoniska taxonomin och CL0UD APP_REGISTRY (GOV-01/REPO-05). Scaffolden defaultade till `platform` — den kan inte veta.
|
||||
- [ ] Fyll i `subcategory` i `siax.repo.json` (REPO-04).
|
||||
- [ ] Rätta `operationalState` mot verkligheten (`docker ps` på noden, GOV-06). Scaffolden satte `degraded` eftersom driftsartefakter finns men driftläget inte går att mäta från filsystemet — det är det konservativa valet som HÅLLER REPO-06/CD-01/API-01 aktiva i doctorn i stället för att tysta dem.
|
||||
- [ ] Beskriv varje post i `children[]` — sökvägarna är härledda ur filträdet, syftet är inte (ARK-11).
|
||||
- [ ] Beskriv hela HTTP-ytan i `contracts/openapi.yaml` — skelettet gör API-01 grön men API-02/03/04 förblir röda.
|
||||
- [ ] Fastställ `appId` mot CL0UD APP_REGISTRY och ta bort `appIdJustification` (REPO-05).
|
||||
- [ ] Fyll i consumes[] och consumedBy[] från FAS 2-beroendekartan — de får aldrig gissas.
|
||||
- [ ] Fyll i `node` (server5–server11) i `siax.repo.json`, eller lämna `null` om repot inte driftsätts.
|
||||
- [ ] Kör återställningen skarpt och skriv in datumet i `docs/runbook/backup-restore.md` (DOC-07).
|
||||
|
||||
## Kontroller som scaffolden AVSIKTLIGT lämnar röda
|
||||
|
||||
- **REPO-05** — `appId` är `null` med motivering. Ett påhittat appId skulle se konformt ut och peka på ingenting i CL0UD APP_REGISTRY.
|
||||
- **DOC-07** — `docs/runbook/backup-restore.md` saknar datum för bevisad restore. Scaffolden skriver aldrig in ett datum: kontrollen letar efter ett datum, och ett genererat sådant skulle göra den grön utan att någon återställning ägt rum. Kör återställningen, skriv in datumet.
|
||||
- **API-02/03/04** — ett genererat kontraktsskelett beskriver ingen route.
|
||||
|
||||
|
||||
---
|
||||
|
||||
_Genererad av `siax-scaffold` (siax-standard). Varje `TODO:` i filen måste
|
||||
fyllas i av en människa. Samlad lista: `docs/compliance/SCAFFOLD-TODO.md`._
|
||||
@@ -10,16 +10,16 @@
|
||||
- Default branch: `main`
|
||||
- Bedömd nivå: **INTEGRATION_TESTED** (manifestets DoD-anspråk: nej)
|
||||
- UI: ja — app, public
|
||||
- CI-arbetsflöden: 2
|
||||
- CI-arbetsflöden: 3
|
||||
|
||||
## Git- och arbetsyteläge
|
||||
|
||||
- Aktuell branch: `main` — ahead 0 / behind 0
|
||||
- Ocommittade filer: 0 · otrackade: 0
|
||||
- Worktrees: 1
|
||||
- Lokala grenar: 1 · remote: 5
|
||||
- Lokala grenar: 1 · remote: 2
|
||||
|
||||
## Livebevis (observerat 2026-11-09T23:48:50)
|
||||
## Livebevis (observerat 2026-11-10T03:05:09)
|
||||
|
||||
Ingen produktionsdomän är deklarerad i manifestet. Det är ett gap för en produkt som ska driftas.
|
||||
|
||||
@@ -87,4 +87,4 @@ curl -fsS https://<prod-host>/health && curl -fsS https://<prod-host>/ready
|
||||
- `siax-standard/standard/SIAX-REPO-OPERATIONS-CONTRACT.md`
|
||||
- `siax-standard/standard/registry/REUSE_FIRST_POLICY.md`
|
||||
|
||||
_Genererad 2026-11-09T23:41:39 från git, manifest, kodsignaler och live-prober. Omgenereras av `scripts/estate-production-audit.py`._
|
||||
_Genererad 2026-11-10T03:03:34 från git, manifest, kodsignaler och live-prober. Omgenereras av `scripts/estate-production-audit.py`._
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
# Backup & restore
|
||||
|
||||
## Vad som säkerhetskopieras
|
||||
|
||||
TODO: lista varje tillstånd repot äger — databas, volymer, objektlager,
|
||||
hemligheter. Sådant som inte står här är inte säkerhetskopierat.
|
||||
|
||||
| Tillstånd | Var | Frekvens | Retention |
|
||||
|---|---|---|---|
|
||||
| TODO | TODO | TODO | TODO |
|
||||
|
||||
## Återställning — steg
|
||||
|
||||
1. TODO: exakt kommando för att hämta senaste dumpen.
|
||||
2. TODO: exakt kommando för att läsa in den.
|
||||
3. TODO: hur du verifierar att data faktiskt är tillbaka (räkna rader, anropa
|
||||
en endpoint) — inte bara att kommandot gav exit 0.
|
||||
|
||||
## Senast bevisad restore
|
||||
|
||||
**EJ BEVISAD.**
|
||||
|
||||
TODO: kör återställningen skarpt mot en tom miljö och skriv in datumet här på
|
||||
formen ÅÅÅÅ-MM-DD tillsammans med vem som körde den och vad som verifierades.
|
||||
|
||||
> Detta fält är avsiktligt tomt. `siax-scaffold` skriver ALDRIG in ett datum
|
||||
> här: DOC-07 letar efter ett datum, och ett genererat datum skulle göra
|
||||
> kontrollen grön utan att någon återställning ägt rum. Kontrollen ska förbli
|
||||
> röd tills påståendet är sant.
|
||||
|
||||
**RTO/RPO:** TODO: mät, gissa inte.
|
||||
|
||||
---
|
||||
|
||||
_Genererad av `siax-scaffold` (siax-standard). Varje `TODO:` i filen måste
|
||||
fyllas i av en människa. Samlad lista: `docs/compliance/SCAFFOLD-TODO.md`._
|
||||
@@ -1,26 +0,0 @@
|
||||
# Deploy
|
||||
|
||||
TODO: `siax.config.json` saknas (REPO-06) — fyll i framework, build,
|
||||
start, port, healthcheck och per-miljö-domän, och spegla dem här.
|
||||
|
||||
## Steg
|
||||
|
||||
1. TODO: hur en ändring når drift (börvärde i estatet: merge till `main` →
|
||||
`.gitea/workflows/cd.yml` → Coolify-webhook på den nod repot bor på).
|
||||
Skriv det som FAKTISKT sker — inte det som borde ske (DOC-19).
|
||||
2. TODO: hur du verifierar att den nya versionen kör (healthcheck-URL, exakt
|
||||
`curl`-kommando och förväntat svar).
|
||||
3. TODO: rollback — exakt kommando/knapp och hur lång tid det tar (CD-*).
|
||||
|
||||
## Förutsättningar
|
||||
|
||||
- Hemligheter hämtas från Infisical, aldrig ur repot (AR-6, SEC-01).
|
||||
- TODO: vilka env-nycklar som måste finnas innan deploy.
|
||||
|
||||
**Runbooken ska vara körbar av någon som inte byggt systemet (DOC-06).**
|
||||
Så länge något `TODO` står kvar är den inte det.
|
||||
|
||||
---
|
||||
|
||||
_Genererad av `siax-scaffold` (siax-standard). Varje `TODO:` i filen måste
|
||||
fyllas i av en människa. Samlad lista: `docs/compliance/SCAFFOLD-TODO.md`._
|
||||
@@ -1,35 +0,0 @@
|
||||
# Incident
|
||||
|
||||
## 1. Bekräfta
|
||||
|
||||
TODO: exakt kommando/URL som visar om tjänsten lever (healthcheck, `docker ps`
|
||||
på noden, dashboard). Ett incidentsvar börjar alltid med en mätning.
|
||||
|
||||
## 2. Klassa
|
||||
|
||||
| Läge | Innebörd | Åtgärd |
|
||||
|---|---|---|
|
||||
| Nere | ingen trafik betjänas | eskalera direkt, se `oncall.md` |
|
||||
| Degraderad | fel/latens över SLO | TODO: tröskelvärden ur `docs/slo.md` (OBS-10) |
|
||||
| Kosmetiskt | ingen kundpåverkan | ärende, inte incident |
|
||||
|
||||
## 3. Vanliga orsaker (fylls på efter varje incident)
|
||||
|
||||
- TODO: känd felkälla 1 — symptom, kommando som bekräftar, åtgärd.
|
||||
- TODO: känd felkälla 2.
|
||||
|
||||
## 4. Återställ
|
||||
|
||||
1. TODO: rollback enligt `deploy.md`.
|
||||
2. TODO: om data är påverkad — följ `backup-restore.md` (och notera att
|
||||
återställningen då faktiskt är bevisad, DOC-07).
|
||||
|
||||
## 5. Efterarbete
|
||||
|
||||
Postmortem i `docs/incidents/` — orsak, tidslinje, vad som saknades i
|
||||
mätningen, vilken kontroll som skulle ha fångat det. Aldrig skuld på person.
|
||||
|
||||
---
|
||||
|
||||
_Genererad av `siax-scaffold` (siax-standard). Varje `TODO:` i filen måste
|
||||
fyllas i av en människa. Samlad lista: `docs/compliance/SCAFFOLD-TODO.md`._
|
||||
@@ -1,21 +0,0 @@
|
||||
# Oncall
|
||||
|
||||
**Jour:** TODO: vem som svarar, på vilken kanal, inom vilken tid. Står här
|
||||
"ingen jour" ska det vara ett medvetet beslut — inte en glömska.
|
||||
|
||||
**Eskalering:** TODO: namn + kontaktväg. Sista instans i estatet: Simon
|
||||
(goat@siax.io).
|
||||
|
||||
**Innan du väcker någon:**
|
||||
|
||||
1. Kör bekräftelsesteget i `incident.md` §1.
|
||||
2. Kolla om det finns en känd orsak i `incident.md` §3.
|
||||
3. TODO: länk till dashboard/larm (OBS-06/OBS-08).
|
||||
|
||||
**Larmvägar:** TODO: vilka larm som faktiskt är kopplade. Ett larm som ingen
|
||||
tar emot är inget larm.
|
||||
|
||||
---
|
||||
|
||||
_Genererad av `siax-scaffold` (siax-standard). Varje `TODO:` i filen måste
|
||||
fyllas i av en människa. Samlad lista: `docs/compliance/SCAFFOLD-TODO.md`._
|
||||
@@ -1,110 +0,0 @@
|
||||
# Auth Bot Protection Runbook
|
||||
|
||||
Accounted's password login, email registration, password recovery, and
|
||||
anonymous sandbox signup support Cloudflare Turnstile through Supabase Auth.
|
||||
The browser integration is dependency-free and loads Cloudflare's official
|
||||
`api.js` directly. Supabase Auth validates each token with the Turnstile
|
||||
secret configured in the project.
|
||||
|
||||
The Turnstile site key is public. The matching secret must exist only in
|
||||
Cloudflare and Supabase Auth. Do not add the secret to this repository,
|
||||
Vercel application variables, Docker images, browser code, logs, or analytics.
|
||||
|
||||
## Rollout states
|
||||
|
||||
The browser exposes the current client state on every protected form through
|
||||
`data-turnstile-rollout-state`:
|
||||
|
||||
- `disabled`: `NEXT_PUBLIC_TURNSTILE_SITE_KEY` is absent. The widget is not
|
||||
loaded and existing Auth calls continue without a CAPTCHA token.
|
||||
- `client-enabled`: the public site key is present. Protected submit buttons
|
||||
remain disabled until the widget returns a token, and the token is passed to
|
||||
Supabase Auth. This state does not prove that provider-side enforcement is
|
||||
active.
|
||||
|
||||
When client-enabled, `data-turnstile-widget-state` reports `loading`, `ready`,
|
||||
`verified`, or `error` without exposing the token. Never record or inspect the
|
||||
token value itself.
|
||||
|
||||
This split keeps login available during rollout. It also means merging this
|
||||
code alone does not activate bot protection.
|
||||
|
||||
The hosted rollout in this runbook is scoped to Accounted's main Supabase
|
||||
project. A separate tenant backend needs its own reviewed widget, hostname
|
||||
allowlist, keys, test identities, and activation record. Do not copy the main
|
||||
project's secret into another project.
|
||||
|
||||
## Hosted activation order
|
||||
|
||||
Use separate Turnstile widgets and key pairs for staging and production.
|
||||
|
||||
1. In Cloudflare, create a managed Turnstile widget and allow only the exact
|
||||
hostnames served by that environment. Include each approved white-label
|
||||
hostname explicitly. Do not allow arbitrary hostnames.
|
||||
2. Set `NEXT_PUBLIC_TURNSTILE_SITE_KEY` for the matching Vercel environment and
|
||||
redeploy. The CSP is widened to `https://challenges.cloudflare.com` only in
|
||||
hosted builds that have this variable.
|
||||
3. Verify all four protected forms reach `client-enabled` and `verified` on
|
||||
staging with a controlled test account. Confirm Auth requests include a
|
||||
CAPTCHA token, but do not copy or log it. Confirm the canonical callback
|
||||
URL and every approved white-label callback URL still complete Auth.
|
||||
4. In the matching Supabase project, open Authentication, Bot and Abuse
|
||||
Protection. Select Cloudflare Turnstile, enter the matching secret, and
|
||||
enable CAPTCHA protection.
|
||||
5. Verify on staging that requests without a token, with an invalid token,
|
||||
with an expired token, and with an already-used token are rejected. Verify
|
||||
normal login, registration, recovery, and sandbox entry still work.
|
||||
6. Repeat the same ordered rollout for production. Do not use real customer
|
||||
addresses for verification and do not run password or mail-volume tests
|
||||
against production.
|
||||
|
||||
Rollback uses the reverse safety order: disable Supabase CAPTCHA enforcement
|
||||
first, then remove the public site key and redeploy. Removing the site key
|
||||
while provider enforcement remains active would block every protected flow.
|
||||
|
||||
## Self-hosted activation
|
||||
|
||||
The Docker image accepts the same optional
|
||||
`NEXT_PUBLIC_TURNSTILE_SITE_KEY`. Its entrypoint substitutes the public value
|
||||
into the built client. The generic image always permits the Cloudflare
|
||||
Turnstile script and frame origins in CSP so the optional runtime key can work.
|
||||
|
||||
Configure the matching Turnstile secret and provider in the installation's
|
||||
GoTrue or Supabase Auth service. Keep the same activation and rollback order as
|
||||
hosted. Leaving the public key unset preserves the existing self-hosted flows.
|
||||
|
||||
## Controlled testing
|
||||
|
||||
Cloudflare publishes dummy site keys and secrets for automated tests. Use the
|
||||
official always-pass or always-fail pair only in a non-production environment.
|
||||
A production secret rejects dummy tokens.
|
||||
|
||||
Turnstile tokens expire after five minutes and are single-use. Every Auth
|
||||
attempt resets the widget, including failed attempts, so a retry obtains a new
|
||||
token.
|
||||
|
||||
## Remaining operational controls
|
||||
|
||||
These settings are not controlled by repository code and remain deployment
|
||||
tasks:
|
||||
|
||||
- Record the current Supabase Auth rate-limit values from Authentication,
|
||||
Rate Limits before activation. Exercise sustained limits only on staging and
|
||||
record the expected `429` threshold.
|
||||
- Enable leaked-password protection in Supabase Auth when the project plan
|
||||
supports it. A read-only Security Advisor check on 2026-08-25 reported
|
||||
`Leaked Password Protection Disabled` for the main project.
|
||||
- Monitor Supabase Auth logs and Turnstile Analytics for challenge failures,
|
||||
Auth `429` responses, recovery or signup volume, and anonymous-user growth.
|
||||
Alerting must not include email addresses, passwords, CAPTCHA tokens, or
|
||||
other credentials.
|
||||
- Anonymous-user retention and deletion require a separate approved retention
|
||||
policy. This integration does not delete Auth users.
|
||||
|
||||
## References
|
||||
|
||||
- [Supabase CAPTCHA protection](https://supabase.com/docs/guides/auth/auth-captcha)
|
||||
- [Supabase Auth rate limits](https://supabase.com/docs/guides/auth/rate-limits)
|
||||
- [Cloudflare explicit rendering](https://developers.cloudflare.com/turnstile/get-started/client-side-rendering/)
|
||||
- [Cloudflare CSP requirements](https://developers.cloudflare.com/turnstile/reference/content-security-policy/)
|
||||
- [Cloudflare test keys](https://developers.cloudflare.com/turnstile/troubleshooting/testing/)
|
||||
@@ -1,211 +0,0 @@
|
||||
# Authorization Policy: Privileged RPCs
|
||||
|
||||
This document records the access-control model of database functions that run
|
||||
with elevated privileges (SECURITY DEFINER) and can mutate or destroy tenant
|
||||
data. It exists so the authorization contract of each function is reviewable
|
||||
without reading migration SQL, and so changes to that contract are deliberate.
|
||||
|
||||
No machine-readable authorization matrix (authorization-matrix.csv or similar)
|
||||
exists in this repository yet; this document is currently the authoritative
|
||||
inventory. If such a matrix is introduced, every function listed here must get
|
||||
a row in it.
|
||||
|
||||
## SIE bulk-delete pair: `replace_sie_import` and `undo_sie_import`
|
||||
|
||||
Defined in:
|
||||
|
||||
- `supabase/migrations/20260727120000_replace_sie_import_authorize_actor.sql`
|
||||
- `supabase/migrations/20260727121000_undo_sie_import_caller_guard.sql`
|
||||
|
||||
Both functions hard-delete a completed SIE import's verifikationer so a fiscal
|
||||
period can be re-imported (replace) or restored to its pre-import state (undo).
|
||||
To do that they call `set_config('gnubok.allow_delete', 'true', true)`, which
|
||||
disarms the BFL immutability and 7-year retention triggers for the transaction.
|
||||
That makes them the two most dangerous entry points in the schema, and their
|
||||
authorization model is correspondingly strict.
|
||||
|
||||
### Why SECURITY DEFINER
|
||||
|
||||
The functions must bypass RLS and the enforcement triggers to perform the
|
||||
sanctioned bulk delete atomically. Running as the function owner is what allows
|
||||
the `gnubok.allow_delete` escape hatch to work; the compensating control is the
|
||||
in-function authorization gate described below, which runs before any mutation.
|
||||
|
||||
### Actor resolution
|
||||
|
||||
Each function takes `p_user_id uuid DEFAULT NULL` and resolves the acting user
|
||||
as follows:
|
||||
|
||||
- If `auth.role() = 'service_role'`: the actor is
|
||||
`COALESCE(p_user_id, auth.uid())`. The service-role client is the cookieless
|
||||
server client (`rpcClientForBulkDelete` in `lib/import/sie-import.ts`), used
|
||||
to escape the authenticator role's 8s statement timeout. Inside it
|
||||
`auth.uid()` is NULL, so the application passes the human user it already
|
||||
authenticated as `p_user_id`.
|
||||
- Every other caller is pinned to its own `auth.uid()`, regardless of what it
|
||||
passes as `p_user_id`. This closes the impersonation hole where an
|
||||
authenticated PostgREST caller could pass an owner's UUID and walk through
|
||||
the gate (the pre-fix behavior of `undo_sie_import`).
|
||||
|
||||
This is the same shape as `list_invoice_delivery_summaries_for_service`
|
||||
(migration `20260727100000`); treat it as the house pattern for any
|
||||
SECURITY DEFINER function that must accept a caller-asserted actor.
|
||||
|
||||
### Authorization gate
|
||||
|
||||
The resolved actor must hold the `owner` or `admin` role in
|
||||
`company_members` for `p_company_id`. The gate fails closed:
|
||||
|
||||
- An anon or unauthenticated caller has no membership row, `v_caller_role`
|
||||
resolves NULL, and the function raises before any mutation and before
|
||||
`gnubok.allow_delete` is ever set.
|
||||
- The raise uses `ERRCODE 42501` (insufficient_privilege) so application
|
||||
routes can map it to a 403.
|
||||
|
||||
### Grants
|
||||
|
||||
Supabase's default privileges grant EXECUTE on every new public function to
|
||||
PUBLIC and to anon/authenticated/service_role, and CREATE OR REPLACE
|
||||
re-introduces those grants. Both migrations therefore end with an explicit:
|
||||
|
||||
- `REVOKE EXECUTE ... FROM PUBLIC, anon` (revoking anon alone is not enough;
|
||||
anon is a member of PUBLIC and would stay callable through the PUBLIC grant)
|
||||
- `GRANT EXECUTE ... TO authenticated, service_role`
|
||||
|
||||
`authenticated` retains EXECUTE on purpose: on self-hosted installs without a
|
||||
`SUPABASE_SERVICE_ROLE_KEY`, the application falls back to running these RPCs
|
||||
on the caller's own session client. The in-function owner/admin gate scopes
|
||||
such callers to companies they actually administer, so this is tenant-scoped
|
||||
access, not a privilege escalation.
|
||||
|
||||
### Tenant isolation contract
|
||||
|
||||
Every mutation inside both functions filters on `p_company_id`, and the gate
|
||||
guarantees the actor administers that company. A caller can therefore never
|
||||
reach another tenant's data: the pre-fix `replace_sie_import` (no gate,
|
||||
EXECUTE held by anon) was a cross-tenant data-destruction primitive, and the
|
||||
gate plus the REVOKEs are what closed it.
|
||||
|
||||
### Verification
|
||||
|
||||
The contract is pinned by pg-real tests (run with `npm run test:pg`):
|
||||
|
||||
- `lib/import/__tests__/sie-import.replace.pg.test.ts`
|
||||
- `lib/import/__tests__/undo-sie-import-actor.pg.test.ts` (spoofed
|
||||
`p_user_id` rejection, the 42501 errcode, and the tightened grants)
|
||||
|
||||
Any change to either function's signature, gate, or grants must update these
|
||||
tests and this document in the same change.
|
||||
|
||||
## Company migration reset: `get_company_migration_reset_eligibility` and `reset_company_for_migration`
|
||||
|
||||
Defined in:
|
||||
|
||||
- `supabase/migrations/20260818084050_company_migration_reset.sql`
|
||||
- `supabase/migrations/20260818141018_harden_company_migration_reset_eligibility.sql`
|
||||
- `supabase/migrations/20260818143004_close_migration_reset_archive_gaps.sql`
|
||||
- `supabase/migrations/20260818224000_block_vat_state_migration_reset.sql`
|
||||
- `supabase/migrations/20260818231500_block_external_filing_staging_state.sql`
|
||||
|
||||
These functions support the owner-only archive-and-replace recovery flow for a
|
||||
failed migration. The execution function archives the source company and
|
||||
creates a clean replacement. It does not delete or rewrite source accounting
|
||||
records and never sets a retention-trigger bypass.
|
||||
|
||||
### Why SECURITY DEFINER
|
||||
|
||||
The operation must atomically create a company, copy memberships and settings,
|
||||
move operational provider consent and subscription state, preserve the
|
||||
original entitlement expiry, move inbound document routing, switch active
|
||||
preferences and pending invitations, and insert immutable audit records.
|
||||
Authenticated callers do not have direct write policies for all of those
|
||||
tables. SECURITY DEFINER makes the single transaction possible while the
|
||||
in-function gate below keeps it tenant-scoped.
|
||||
|
||||
The internal `company_migration_reset_snapshot` function is also SECURITY
|
||||
DEFINER so both preview and execution use one fail-closed eligibility
|
||||
implementation. It has no EXECUTE grant for authenticated callers and is only
|
||||
reached through the two guarded entry points.
|
||||
|
||||
The source-mutation trigger functions are SECURITY DEFINER only so their audit
|
||||
lookup cannot be hidden by RLS from an invitation acceptor or a delayed
|
||||
request. They accept no caller-controlled identifiers, expose no rows, and can
|
||||
only return the row unchanged or raise a generic exception.
|
||||
|
||||
### Actor and tenant gate
|
||||
|
||||
Neither entry point accepts an actor parameter. The actor is always
|
||||
`auth.uid()`, so a cookie-session caller cannot assert another user's identity
|
||||
and a service-role call with no user identity cannot pass the gate.
|
||||
|
||||
The actor must have a `company_members.role = 'owner'` row for the requested
|
||||
company. A non-member receives `COMPANY_RESET_NOT_FOUND`; a member with any
|
||||
other role receives `COMPANY_RESET_FORBIDDEN`. The HTTP route also requires the
|
||||
URL company ID to equal the active company resolved by `withRouteContext`.
|
||||
|
||||
Execution locks the active source company row and repeats the exact-name,
|
||||
reason, attestation, and eligibility checks inside the transaction. Any
|
||||
failure returns a structured result before the first write. Unexpected
|
||||
database failures roll the transaction back.
|
||||
|
||||
### Eligibility and retention contract
|
||||
|
||||
Self-service is restricted to active companies created within 30 days. It is
|
||||
blocked by the company lock date, a closed or locked period, any journal entry
|
||||
in any status or source, any voucher-sequence row, any customer or supplier
|
||||
invoice, an incomplete import, a known authority submission, or persisted VAT
|
||||
declaration workflow state. The VAT state closes the historical direct-lock
|
||||
path where the signing lock was stored in `extension_data` without a matching
|
||||
audit row. This prevents a replacement for the same legal
|
||||
entity from restarting voucher numbering after a draft, migrated voucher, or
|
||||
sequence state already exists. Live integrations, bank connections, recurring
|
||||
invoice schedules, pending accrual installments, and non-terminal background
|
||||
jobs also block because they can write after the interactive session moves.
|
||||
The owner must attest that no filing was made outside Accounted and acknowledge
|
||||
that the source remains retained. Accounted cannot independently observe every
|
||||
filing made directly at an authority, so uncertainty must fail closed and be
|
||||
escalated rather than inferred from an empty internal audit log.
|
||||
|
||||
The source company's imports, transactions, periods, documents, journal
|
||||
entries, and voucher sequences are not mutated. The replacement starts with no
|
||||
such rows. An append-only `company_migration_resets` row captures the reason,
|
||||
confirmations, and source counts, and ordinary immutable `audit_log` rows link
|
||||
the source and replacement company IDs. The active inbound email address and
|
||||
custom inbound domain move to the replacement; already received documents do
|
||||
not move. A database trigger also rejects new memberships on the archived
|
||||
source, closing the race with an invitation acceptance that began before the
|
||||
reset transaction. Database mutation guards make the retained source's
|
||||
imports, transactions, periods, documents, journal rows, invoices, and voucher
|
||||
sequences write-closed after the audit row is committed. Filing-adjacent payroll,
|
||||
AGI, annual report, ROT/RUT, bank-connection, authority-audit, and newly arriving
|
||||
VAT workflow rows receive the same archive guard. Team membership sync
|
||||
selects active companies only, so an archived source cannot block a later team
|
||||
member from reaching the replacement.
|
||||
|
||||
### Grants
|
||||
|
||||
The migration explicitly revokes EXECUTE from PUBLIC and anon, grants the two
|
||||
entry points only to authenticated, and revokes authenticated access to the
|
||||
internal snapshot. The audit table grants authenticated SELECT only through an
|
||||
RLS policy based on active membership of the replacement company. It has no
|
||||
user DML policy, and UPDATE, DELETE, and TRUNCATE are blocked by triggers even
|
||||
for elevated callers. An owner-only archive endpoint follows that immutable
|
||||
replacement-to-source link, rechecks current ownership of the active
|
||||
replacement, requires the source archive marker with a service-role client,
|
||||
and exports without activating or mutating the source. Authorization does not
|
||||
depend on retained-source membership because normal team removal and account
|
||||
anonymization can legitimately change those rows; the immutable reset link
|
||||
keeps the statutory archive reachable to the legal entity's current owners.
|
||||
Support inspection follows reset chains with the service-side read-only query
|
||||
in the runbook.
|
||||
|
||||
### Verification
|
||||
|
||||
The contract is pinned by:
|
||||
|
||||
- `tests/pg/company-migration-reset.pg.test.ts`
|
||||
- `app/api/company/[id]/migration-reset/__tests__/route.test.ts`
|
||||
|
||||
Any change to the owner gate, eligibility boundary, source-retention
|
||||
invariant, grants, or audit immutability must update those tests and this
|
||||
document in the same change.
|
||||
@@ -1,58 +0,0 @@
|
||||
# Logging and Observability Pipeline
|
||||
|
||||
This document states what the logging pipeline actually is in production, and
|
||||
the non-negotiable redaction contract for anything that forwards log data to a
|
||||
third party.
|
||||
|
||||
## The pipeline today
|
||||
|
||||
- `lib/logger.ts` writes structured log records to stdout/stderr. On hosted
|
||||
(Vercel) these are collected by the platform and delivered through the
|
||||
configured Vercel log drain, which is the production log delivery path.
|
||||
- `lib/observability/sink.ts` is a provider-agnostic seam for an error
|
||||
tracking vendor. It is a deliberate no-op until an adapter is registered
|
||||
with `registerObservabilitySink()` from a server-side init path. No adapter
|
||||
is registered by default, so self-hosted builds carry no third-party
|
||||
runtime dependency and setting the DSN environment variables alone changes
|
||||
nothing.
|
||||
|
||||
That means: until a vendor adapter is wired, error-level events reach a human
|
||||
only through the log drain. Any production deployment that wants alerting
|
||||
must either configure the log drain with alert rules or register a sink
|
||||
adapter; a no-op sink is not an alerting pipeline on its own.
|
||||
|
||||
## Redaction contract (GDPR, non-negotiable)
|
||||
|
||||
`lib/observability/redact.ts` is the single source of truth for what must
|
||||
never leave the process in clear text: a key denylist (passwords, tokens,
|
||||
IBAN, personnummer, ...), a personnummer regex applied to every string, and
|
||||
substring patterns for emails, Swedish IBANs, and gnubok API keys.
|
||||
|
||||
Structural guarantees, verified in the code:
|
||||
|
||||
- Every public entry point of the sink module (`captureException`,
|
||||
`captureMessage`) runs `redact()` / `redactString()` on the error, the
|
||||
message, and the context BEFORE the registered adapter sees anything. There
|
||||
is no code path from application data to a vendor that skips redaction.
|
||||
- Adapters receive errors already serialized and redacted as plain objects,
|
||||
never live `Error` instances, and must not re-fetch original values.
|
||||
- `redact()` is idempotent, so double-redaction on records the logger already
|
||||
cleaned is safe and is intentionally not "optimised away".
|
||||
|
||||
Rules for anyone adding an adapter or a new emission path:
|
||||
|
||||
1. Never call a vendor SDK directly from application code. Route through
|
||||
`captureException` / `captureMessage` so redaction stays structural.
|
||||
2. A browser-side adapter (one reading `NEXT_PUBLIC_OBSERVABILITY_DSN`) ships
|
||||
data straight from the user's browser to the vendor and bypasses every
|
||||
server-side control. It MUST apply the same redaction module before
|
||||
emitting: import from `lib/observability/redact.ts` and run all payloads
|
||||
through `redact()` / `redactString()` client-side. Do not register a
|
||||
browser adapter that forwards raw console or log payloads.
|
||||
3. Do not add a log emission path (new logger, direct `console.*` forwarding,
|
||||
CI log shipping) that reaches a third party without going through the
|
||||
redact module first.
|
||||
|
||||
The redaction behavior is pinned by unit tests under
|
||||
`lib/observability/__tests__/`; extend them when the denylist or patterns
|
||||
change.
|
||||
@@ -1,264 +0,0 @@
|
||||
# Company migration reset support runbook
|
||||
|
||||
This runbook covers the owner-only self-service flow for redoing a failed
|
||||
company migration. The operation is deliberately an archive-and-replace reset.
|
||||
It is not a deletion or an in-place rewrite.
|
||||
|
||||
## Legal and product boundary
|
||||
|
||||
Swedish Bookkeeping Act (1999:1078) 1 kap. 2 § defines räkenskapsinformation
|
||||
broadly. It includes journal and ledger information, vouchers, supporting
|
||||
systems information, important agreements, and other information needed to
|
||||
understand the postings. Chapter 7 requires electronic accounting information
|
||||
to remain durable, accessible, and preserved through the seventh year after
|
||||
the relevant calendar year. BFNAR 2013:2 also requires treatment history to
|
||||
show added postings and system changes that affect how accounting information
|
||||
is processed.
|
||||
|
||||
Authoritative references:
|
||||
|
||||
- [Bokföringslag (1999:1078), especially 1 kap. 2 § and 7 kap. 1-2 §§](https://www.riksdagen.se/sv/dokument-och-lagar/dokument/svensk-forfattningssamling/bokforingslag-19991078_sfs-1999-1078/)
|
||||
- [BFNAR 2013:2 Bokföring, especially points 2.17 and 9.16](https://www.bfn.se/wp-content/uploads/2020/06/bfnar13-2-grund.pdf)
|
||||
|
||||
Accounted cannot reliably prove that every provider-imported customer,
|
||||
invoice, transaction, or document is disposable test data. Some provider
|
||||
imports do not carry row-level provenance, and Accounted cannot observe every
|
||||
filing made directly at Skatteverket or Bolagsverket. Therefore this feature
|
||||
never deletes or rewrites source data.
|
||||
|
||||
The self-service boundary is intentionally narrow:
|
||||
|
||||
- The company must be active and no more than 30 days old.
|
||||
- Sandbox companies are excluded because they have a separate disposable-data
|
||||
cleanup lifecycle and must not become retained legal archives.
|
||||
- The caller must be an owner, not merely an admin or member.
|
||||
- No company lock date may exist, and no fiscal period may be locked, closed,
|
||||
or marked closed in the previous bookkeeping system.
|
||||
- Journal entries, voucher sequences, and customer or supplier invoices do not
|
||||
block (since migration 20260826150000; the 2026-08-18 rule blocked on the
|
||||
first of any of them). They stay unchanged in the retained source, which is
|
||||
write-closed and downloadable from the replacement. The replacement starts a
|
||||
fresh voucher namespace and continues the invoice and arrival-number
|
||||
counters. The unchecked "Radera företag" path produced the same two
|
||||
companies with none of the retention guards, so blocking here only routed
|
||||
owners into a dead end.
|
||||
- No bank connection may be pending or active. This prevents the service-role
|
||||
sync job from writing new transactions into the retained source after reset.
|
||||
- No SIE, bank-file, or tax-account-file import may be pending or processing.
|
||||
- No commerce, Stripe, or Skatteverket connection, recurring invoice schedule,
|
||||
or pending accrual installment may still be able to write in the background.
|
||||
- No import, OCR, API operation, invoice delivery, payment sync, or messaging
|
||||
worker may still be queued or processing for the company.
|
||||
- No AGI upload, VAT declaration draft, lock or submission, ROT/RUT request,
|
||||
or production annual report submission may exist. Persisted VAT and AGI
|
||||
workflow state blocks even when an older direct action has no audit row.
|
||||
Every generated ROT/RUT payout file blocks because upload and signing happen
|
||||
outside Accounted before the local request can be marked submitted.
|
||||
- The owner must separately attest that nothing was filed outside Accounted.
|
||||
Accounted cannot verify that external fact. If the owner is unsure, support
|
||||
must stop the reset and escalate instead of interpreting silence as consent.
|
||||
- The owner must acknowledge that the source copy is retained, provide an
|
||||
audit reason, and type the exact displayed company name.
|
||||
|
||||
If any condition fails, self-service returns `COMPANY_RESET_INELIGIBLE` and
|
||||
makes no change. Support must not override the result with deletion SQL.
|
||||
|
||||
## What the reset does
|
||||
|
||||
`reset_company_for_migration` executes in one database transaction:
|
||||
|
||||
1. It proves the caller is an owner before taking tenant-wide locks, then locks
|
||||
the source and repeats authorization, confirmation, and eligibility checks.
|
||||
2. It archives the source company by setting `archived_at` and `archived_by`.
|
||||
3. It creates a replacement company with the same legal identity, team, owner
|
||||
and member roles, company settings, and invoice-number counters. Setup state
|
||||
and the company bookkeeping lock date are cleared on the replacement.
|
||||
4. It seeds a fresh chart of accounts and primary `1930` cash account.
|
||||
5. It transfers provider migration consents, subscription state, and existing
|
||||
capability grants. The automatically created fresh trial is removed before
|
||||
the original grants move, so resetting cannot extend a trial.
|
||||
6. It transfers the active inbound email address and any custom inbound domain
|
||||
to the replacement, so future documents are routed to the active company.
|
||||
7. It transfers unexpired pending member invitations. Accepted, revoked, and
|
||||
expired invitation history stays on the source.
|
||||
8. It switches active-company preferences to the replacement.
|
||||
9. It writes an immutable `company_migration_resets` audit record and two
|
||||
append-only `audit_log` records.
|
||||
10. Database guards make the retained source's accounting and import rows
|
||||
write-closed, including bank connections, payroll and AGI records, annual
|
||||
report submissions, ROT/RUT requests, authority audit rows, and VAT or AGI
|
||||
workflow rows from requests that were already waiting on external signing.
|
||||
|
||||
The transaction does not disable a trigger. It does not delete, detach,
|
||||
renumber, recalculate, copy, or mutate any source bookkeeping record.
|
||||
|
||||
The following stay on the archived source company unchanged:
|
||||
|
||||
- SIE, bank-file, and tax-account-file import records
|
||||
- bank transactions and expired or revoked bank connections
|
||||
- fiscal periods and their lock or close state
|
||||
- documents, hashes, version chains, and voucher links
|
||||
- customers and suppliers
|
||||
- journal entries, journal-entry lines, and voucher sequences
|
||||
- customer and supplier invoices
|
||||
- authority and general audit logs
|
||||
- extension runtime state, including any non-blocking provider history
|
||||
|
||||
Their counts are recorded in `company_migration_resets.source_counts`.
|
||||
Those tables remain covered by the immutable-source guards and audit counts as
|
||||
defense in depth. The replacement company intentionally has no fiscal period,
|
||||
journal entry, transaction, document, import record, or voucher sequence. The
|
||||
new migration creates the applicable periods and its first sequence state.
|
||||
Provider migration consent is transferred so the owner can start again from
|
||||
the import workspace. Bank connections are not transferred. Pending or active
|
||||
connections block the reset and must be disconnected first. Reconnect
|
||||
deliberately after the replacement migration is verified. The active inbound
|
||||
email address and custom inbound domain move to the replacement; already
|
||||
received documents do not move.
|
||||
|
||||
## Support checks
|
||||
|
||||
Start with the request ID from the API response or browser network panel. The
|
||||
routes log operations `company.migration-reset.preview`,
|
||||
`company.migration-reset.execute`, and `company.migration-reset.archive`.
|
||||
|
||||
Use read-only checks only. Do not run a reset RPC on behalf of a customer, do
|
||||
not run `scripts/clear-user-data.sql`, and do not disable retention or journal
|
||||
enforcement triggers.
|
||||
|
||||
The retained source is hidden from normal company selection. A current owner
|
||||
of the active replacement can use **Settings > Company > Previous migration >
|
||||
Download archive**. That owner-only route verifies the immutable reset link,
|
||||
current replacement ownership, and the source archive marker before using the
|
||||
read-only archive exporter. It deliberately does not rely on retained-source
|
||||
membership, which can change through team removal or account anonymization. It
|
||||
never makes the source active. If documents push
|
||||
the direct ZIP over the response limit, the owner can download the structured
|
||||
data without documents and support must provide the complete document package
|
||||
through an approved read-only export path. Never unarchive the source merely to
|
||||
reuse ordinary write-capable screens.
|
||||
|
||||
The replacement represents the same legal entity, not a newly formed business.
|
||||
Its `next_invoice_number` and `next_arrival_number` therefore continue from the
|
||||
source settings whether or not invoice rows exist on the source.
|
||||
Those counters can reflect an imported or previously allocated series, and
|
||||
resetting them to 1 could reuse a number or conceal a gap. Do not manually reset
|
||||
either counter as part of migration recovery. Escalate a suspected numbering
|
||||
error for a separate, documented compliance review.
|
||||
|
||||
After deployment, the audit chain can be inspected read-only with:
|
||||
|
||||
```sql
|
||||
select
|
||||
id,
|
||||
source_company_id,
|
||||
replacement_company_id,
|
||||
actor_id,
|
||||
reason,
|
||||
confirmation_snapshot,
|
||||
source_counts,
|
||||
created_at
|
||||
from public.company_migration_resets
|
||||
where source_company_id = '<source-company-id>'
|
||||
or replacement_company_id = '<replacement-company-id>';
|
||||
```
|
||||
|
||||
Confirm the source was retained and the replacement is active:
|
||||
|
||||
```sql
|
||||
select id, name, org_number, archived_at, archived_by, created_at
|
||||
from public.companies
|
||||
where id in ('<source-company-id>', '<replacement-company-id>');
|
||||
```
|
||||
|
||||
Compare source record counts without selecting personal or accounting content:
|
||||
|
||||
```sql
|
||||
select
|
||||
(select count(*) from public.journal_entries where company_id = '<source-company-id>') as journal_entries,
|
||||
(select count(*)
|
||||
from public.journal_entry_lines line
|
||||
join public.journal_entries entry on entry.id = line.journal_entry_id
|
||||
where entry.company_id = '<source-company-id>') as journal_entry_lines,
|
||||
(select count(*) from public.transactions where company_id = '<source-company-id>') as transactions,
|
||||
(select count(*) from public.document_attachments where company_id = '<source-company-id>') as documents,
|
||||
(select count(*) from public.fiscal_periods where company_id = '<source-company-id>') as fiscal_periods,
|
||||
(select count(*) from public.voucher_sequences where company_id = '<source-company-id>') as voucher_sequences;
|
||||
```
|
||||
|
||||
The counts should match `company_migration_resets.source_counts`. A mismatch is
|
||||
an incident requiring investigation. Do not repair it by editing the source.
|
||||
|
||||
## Common blocker interpretation
|
||||
|
||||
- `migration_window_expired`: the company is older than the self-service
|
||||
recovery window. Escalate for a case-specific legal and accounting review.
|
||||
- `sandbox_company`: use the existing sandbox cleanup lifecycle. Do not convert
|
||||
disposable sandbox data into a retained migration archive.
|
||||
- `locked_or_closed_periods`: a company lock date or finalized period exists.
|
||||
Do not clear or unlock it to enable reset.
|
||||
- Journal entries, voucher sequences, and invoices are reported in the retained
|
||||
counts and no longer block (20260826150000). They stay on the source; never
|
||||
delete, reverse, renumber, or detach any of them.
|
||||
- `authority_submission_detected`: Accounted has evidence of an authority
|
||||
interaction, including a persisted VAT draft, an AGI upload awaiting BankID
|
||||
signing, or any generated ROT/RUT payout file. Do not reset even if the owner
|
||||
believes it was a test without first establishing the authority environment
|
||||
and legal status. Remove only a local VAT draft that never left Accounted,
|
||||
and only through the product flow; never clear extension data, payout
|
||||
requests, or audit rows manually. An AGI upload, generated payout file,
|
||||
locked declaration, or possibly signed declaration requires legal escalation,
|
||||
not cleanup.
|
||||
- `live_bank_connections`: disconnect every pending or active bank connection
|
||||
first. Do not bypass the blocker because the sync cron can import without an
|
||||
interactive company session.
|
||||
- `imports_in_progress`: wait until every import completes or fails. Never
|
||||
change an import status manually to bypass this concurrency guard.
|
||||
- `active_integrations_or_schedules`: disable the reported integrations and
|
||||
automatic schedules first. Team-level grants and service credentials can
|
||||
otherwise keep background writers active after the session switches company.
|
||||
- `background_work_in_progress`: wait for every queued or processing import,
|
||||
OCR, API, delivery, payment, or messaging job to reach a terminal state.
|
||||
- `COMPANY_RESET_CONFIRMATION_MISMATCH`: confirm the user typed the displayed
|
||||
name from `company_settings.company_name`, not a stale internal name.
|
||||
|
||||
## Deployment and rollback
|
||||
|
||||
The migration files are
|
||||
`supabase/migrations/20260818084050_company_migration_reset.sql` and
|
||||
`supabase/migrations/20260818141018_harden_company_migration_reset_eligibility.sql`
|
||||
and
|
||||
`supabase/migrations/20260818143004_close_migration_reset_archive_gaps.sql` and
|
||||
`supabase/migrations/20260818224000_block_vat_state_migration_reset.sql` and
|
||||
`supabase/migrations/20260818231500_block_external_filing_staging_state.sql` and
|
||||
`supabase/migrations/20260826150000_allow_migration_reset_with_accounting_records.sql`.
|
||||
Apply them only to the permitted `erpbase` staging branch through the normal
|
||||
migration workflow, then deploy application code. Never deploy the UI/API
|
||||
before all listed migrations exist.
|
||||
|
||||
Before production rollout:
|
||||
|
||||
1. Run the pg-real suite against an approved disposable test database.
|
||||
2. Reconcile every remote migration version with the repository.
|
||||
3. Verify anon has no execute privilege and authenticated has execute only on
|
||||
the preview and execution RPCs. The archive route uses the audit table's
|
||||
replacement-membership RLS policy and repeats owner checks with its
|
||||
service-role export client.
|
||||
4. Exercise the flow with synthetic data in an approved non-production
|
||||
environment, including every blocker and a forced transaction failure.
|
||||
5. Confirm monitoring captures the request ID and structured error code without
|
||||
logging the typed company name or reason.
|
||||
|
||||
Application rollback can hide the UI and route, but it must not drop the audit
|
||||
table or delete reset history. Database rollback is additive only: revoke new
|
||||
RPC execution if necessary and ship a new migration. Never modify or remove the
|
||||
applied migration file.
|
||||
|
||||
## Escalation boundary
|
||||
|
||||
Escalate to Emil and an accounting/legal reviewer when the owner cannot make
|
||||
the external-filing attestation, the company is outside the 30-day window, a
|
||||
period is closed or locked, or a known authority submission exists. A
|
||||
live bank connection is operational, not a legal override case: disconnect it
|
||||
before retrying. The safe fallback is to
|
||||
retain the source company and perform no reset.
|
||||
Reference in New Issue
Block a user