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:
2026-11-10 07:19:45 +01:00
parent 0fda8cae48
commit 08b325a6a2
6135 changed files with 4 additions and 1718997 deletions
-338
View File
@@ -1,338 +0,0 @@
# Self-Hosting Accounted with Docker
## Prerequisites
- Docker and Docker Compose (v2)
- A [Supabase](https://supabase.com) project (free tier works)
You do **not** need Node.js, npm, or anything else installed locally. The pre-built image has everything.
---
## Quick Start
### 1. Download the required files
```bash
mkdir Accounted && cd Accounted
# Compose file + env template
curl -fsSLO https://raw.githubusercontent.com/erp-mafia/accounted/main/docker-compose.yml
curl -fsSLO https://raw.githubusercontent.com/erp-mafia/accounted/main/.env.docker.example
# Cron sidecar (Dockerfile + schedule)
mkdir -p docker
curl -fsSL -o docker/cron.Dockerfile \
https://raw.githubusercontent.com/erp-mafia/accounted/main/docker/cron.Dockerfile
curl -fsSL -o docker/crontab.self-hosted \
https://raw.githubusercontent.com/erp-mafia/accounted/main/docker/crontab.self-hosted
```
### 2. Configure your environment
```bash
cp .env.docker.example .env
```
Open `.env` and fill in the **required** values:
| Variable | Where to find it |
|----------|-----------------|
| `NEXT_PUBLIC_SUPABASE_URL` | Supabase dashboard → Settings → API → Project URL |
| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Supabase dashboard → Settings → API → `anon` `public` key |
| `SUPABASE_SERVICE_ROLE_KEY` | Supabase dashboard → Settings → API → `service_role` key |
| `NEXT_PUBLIC_APP_URL` | The URL where you'll access Accounted (e.g. `https://gnubok.example.com`) |
| `CRON_SECRET` | Any random string: `openssl rand -hex 32` works |
Once `.env` is filled in, **restrict its permissions** so other users on the host can't read your service-role key or cron secret:
```bash
chmod 600 .env
```
### 3. Start
```bash
docker compose up -d
```
The app is now reachable on **loopback only** at `http://127.0.0.1:3000`. This is intentional: direct internet exposure over HTTP is not safe for an accounting app. The next section enables HTTPS.
### 4. Verify
```bash
# Should return {"status":"healthy",...}
curl http://localhost:3000/api/health
```
---
## Synology DSM and Xpenology
Use a **Container Manager Project**, not the single-container wizard. The
project path is the working directory for every relative path in the Compose
file. Create that directory first and put all of these files in it before
deploying the project:
```text
docker-compose.yml
.env
docker/
cron.Dockerfile
crontab.self-hosted
```
Uploading only `docker-compose.yml` is not enough: the cron service is built
from `docker/cron.Dockerfile` and bind-mounts
`docker/crontab.self-hosted`. Keep `.env` readable only by the administrator
and Container Manager because it contains the Supabase service-role key.
Container Manager ships its own Compose build, and supported keys vary by DSM
release. Accounted's base Compose file avoids the optional `cpus` and
`healthcheck.start_interval` keys for compatibility. Set a CPU limit through
Container Manager's resource controls or a local override if needed. When
updating an existing deployment that relied on the previous two-CPU cap,
reapply that limit in the host controls before restarting the project.
If you run Docker Compose 2.20.2 or newer against Docker Engine 25.0 or newer,
the optional resource overlay restores the previous two-CPU cap and faster
startup health checks while keeping the base file compatible. Download the
overlay from the same Accounted tag or full commit as the base Compose file:
```bash
ACCOUNTED_REF=replace-with-the-same-tag-or-full-commit
curl -fsSLo docker-compose.resources.yml \
"https://raw.githubusercontent.com/erp-mafia/accounted/${ACCOUNTED_REF}/docker-compose.resources.yml"
docker compose -f docker-compose.yml -f docker-compose.resources.yml up -d
```
Compose only applies the files named in each invocation. Keep the resource
overlay in every later `up` command, after any other overlay. For example:
```bash
# HTTPS with Caddy
docker compose -f docker-compose.yml -f docker-compose.caddy.yml -f docker-compose.resources.yml up -d
# Local image build
docker compose -f docker-compose.yml -f docker-compose.build.yml -f docker-compose.resources.yml up --build -d
```
Do not use this overlay if Container Manager rejects either key or the Docker
Engine is older than 25.0. The memory and PID limits remain active in the base
file either way.
Accounted itself does not use PostgreSQL port 5432 and does not need a database
data folder when connected to Supabase Cloud. If Supabase is also running on
the NAS, follow the [fully self-hosted notes](SELF-HOSTING.md#synology-dsm-and-xpenology-notes)
for its separate project, bind mounts, ports, and JWKS configuration.
---
## Enable HTTPS (recommended)
Ship a Caddy reverse proxy alongside the app: it auto-provisions Let's Encrypt certificates and renews them forever.
### 1. Point a domain at the host
`gnubok.example.com → <your-public-ip>` (A record). Ports 80 and 443 must be reachable from the internet (Let's Encrypt's HTTP-01 challenge uses port 80).
### 2. Set `DOMAIN` in `.env`
```env
DOMAIN=gnubok.example.com
NEXT_PUBLIC_APP_URL=https://gnubok.example.com
```
### 3. Download the overlay + Caddyfile
```bash
curl -fsSLO https://raw.githubusercontent.com/erp-mafia/accounted/main/docker-compose.caddy.yml
mkdir -p docker
curl -fsSL -o docker/Caddyfile \
https://raw.githubusercontent.com/erp-mafia/accounted/main/docker/Caddyfile
```
### 4. Start with the overlay
```bash
docker compose -f docker-compose.yml -f docker-compose.caddy.yml up -d
```
Caddy obtains a cert on first boot (takes ~10 s). Visit `https://gnubok.example.com`.
If you already have nginx / a managed load balancer / Cloudflare in front, skip Caddy and point your existing proxy at `127.0.0.1:3000`: set `NEXT_PUBLIC_APP_URL` to match the public URL.
---
## Optional Extensions
The self-hosted image ships with a curated set of general extensions, including email, invoice inbox, document extraction, push notifications, calendar, and the MCP server. Enable Banking and Skatteverket are in the preset too: they run on a connector key or on your own credentials (see [SELF-HOSTING.md](SELF-HOSTING.md), "Connector subscription"). Each extension activates when you provide its env vars: without them, the app works normally and the feature is simply unavailable.
### AI Features (document-extraction, invoice-inbox, AI assistant)
All AI runs Claude. Provide either a direct Anthropic API key:
```env
ANTHROPIC_API_KEY=sk-ant-...
```
or AWS credentials with Bedrock model access to Claude, which keeps inference in eu-north-1:
```env
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_REGION=eu-north-1
```
If both are set, Bedrock is used; `AI_PROVIDER=bedrock|anthropic` forces the choice. `OPENAI_API_KEY` from earlier versions is not read by any code path. See [SELF-HOSTING.md](./SELF-HOSTING.md#ai-features) for optional model overrides.
The stock self-hosted image includes both `invoice-inbox` and
`document-extraction`, so the same provider credentials cover emailed invoices
and documents uploaded in the app.
### Email (invoice sending, reminders)
```env
RESEND_API_KEY=re_...
RESEND_FROM_EMAIL=faktura@your-domain.com
RESEND_DELIVERY_WEBHOOK_SECRET=whsec_...
```
Invitations do not need Resend: the accept link is returned to the inviter in the app. See [SELF-HOSTING.md](./SELF-HOSTING.md#email-invoice-sending-invitations-and-reminders).
### Push Notifications
```env
NEXT_PUBLIC_VAPID_PUBLIC_KEY=...
VAPID_PRIVATE_KEY=...
VAPID_SUBJECT=mailto:you@example.com
```
Generate VAPID keys with: `npx web-push generate-vapid-keys`
### Calendar
No env vars needed: always available.
---
## Updating
The default `IMAGE_TAG=latest` follows `main` and updates on every `docker compose pull`. For production, **pin to a specific build** so updates are deliberate. Every merge to `main` publishes the image under two tags: `latest` and the bare 7-character commit SHA (for example `3e4b5dd`), so a pin looks like:
```env
# .env
IMAGE_TAG=3e4b5dd
```
Browse available tags at https://github.com/erp-mafia/accounted/pkgs/container/gnubok (the image name keeps the historical `gnubok` package name on purpose). For maximum integrity, pin by digest; the digest is printed in the `docker-publish` workflow run and by `docker buildx imagetools inspect ghcr.io/erp-mafia/gnubok:<sha>`:
```env
IMAGE_TAG=3e4b5dd@sha256:abcdef...
```
Semver tags (`1.2.3`, `1.2`, `1`) are published only when a `v*.*.*` git tag is cut. No such tag exists yet, so until the first tagged release the commit SHA is the only immutable pin.
Apply updates:
```bash
docker compose pull
docker compose up -d
```
The cron sidecar is a small Alpine image built locally: it rebuilds automatically on `up --build` if you re-download `docker/cron.Dockerfile`. Base-image digests (node, alpine, caddy) are pinned in source and bumped manually when upstream ships security updates.
---
## Building from Source
If you prefer to build locally instead of pulling the pre-built image:
```bash
# Clone the repo
git clone https://github.com/erp-mafia/accounted.git
cd accounted
cp .env.docker.example .env
# Fill in .env
# Build and start
docker compose -f docker-compose.yml -f docker-compose.build.yml up --build -d
```
---
## Architecture
The compose setup runs two containers:
| Container | What it does |
|-----------|-------------|
| `app` | Next.js application server |
| `cron` | Lightweight Alpine sidecar that runs scheduled jobs (deadline checks, invoice reminders, tax deadline sync, document verification) via [supercronic](https://github.com/aptible/supercronic) |
The cron container waits for the app's healthcheck to pass before starting. It calls the app's cron API endpoints over the internal Docker network.
### How NEXT_PUBLIC_* injection works
The image is built with placeholder values (e.g. `__NEXT_PUBLIC_SUPABASE_URL__`) baked into the JavaScript bundles. At container start, `docker-entrypoint.sh` runs as `root`, `sed`-substitutes the placeholders with your runtime env vars, then runs `chmod -R a-w /app/.next/static` and drops privileges with `su-exec nextjs:nodejs` before exec'ing Node. The served JS bundle is owned by `root` and read-only by the time the application starts: a runtime RCE in the Node process cannot rewrite what other users will receive.
---
## Ports
The app listens on port 3000 inside the container. The base compose binds it to `127.0.0.1:3000` on the host: change `PORT` in `.env` to remap. To expose on all interfaces (only do this if you're putting your own reverse proxy in front), override the port binding in a local `docker-compose.override.yml`:
```yaml
services:
app:
ports: !override
- "${PORT:-3000}:3000"
```
---
## Reverse Proxy
The preferred path is the bundled Caddy overlay: see [Enable HTTPS](#enable-https-recommended). If you already run nginx, Traefik, or sit behind Cloudflare, leave the app on `127.0.0.1:3000` and point your existing proxy at it. Set `NEXT_PUBLIC_APP_URL` to the public URL.
Example nginx upstream:
```nginx
server {
server_name gnubok.example.com;
listen 443 ssl http2;
# ssl_certificate / ssl_certificate_key / etc.
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
---
## Troubleshooting
**Container exits immediately**
```bash
docker compose logs app
```
Most common cause: missing required env vars. Check that all 5 required values in `.env` are set.
**Health check fails**
```bash
curl -v http://localhost:3000/api/health
```
The health endpoint tests database connectivity. If it returns `unhealthy`, verify your Supabase URL and service role key are correct.
**Cron container keeps restarting**
```bash
docker compose logs cron
```
The cron container depends on the app being healthy first. If the app never becomes healthy, the cron container will wait indefinitely.
**Port already in use**
Set a different port: `PORT=8080 docker compose up -d`
-835
View File
@@ -1,835 +0,0 @@
# Extension System: Design Document
## The App
Accounted is a Swedish accounting platform for sole traders (enskild firma) and limited companies (aktiebolag). It handles the legally required bookkeeping and financial management that every Swedish business needs.
## Core Functionality
The core is the standard accounting system. It's what every user gets out of the box: the features that exist in any accounting platform like Fortnox, Visma, or Björn Lundén. Nothing more, nothing less:
- Double-entry bookkeeping (journal entries, BAS chart of accounts, voucher numbering)
- Invoicing (create, send, track, payment matching)
- Supplier invoice management
- Bank transaction reconciliation
- Financial reports (income statement, balance sheet, trial balance, VAT declaration, general ledger)
- Tax compliance (SRU export, NE-bilaga, tax deadline tracking)
- Document archive with 7-year legal retention
- Customer and supplier management
That's the core. It doesn't include receipt scanning, AI categorization, AI chat, push notifications, or PSD2 bank connection. Those are not standard accounting features: they're value-adds.
## Extensions
Extensions are **everything beyond the core accounting system**. They are self-contained tools that a user adds to their dashboard. All compiled extensions are active for all users: the operator decides which extensions to include via `extensions.config.json` at build time.
There are two kinds of extensions:
### General Extensions
General extensions are not tied to any specific business sector. They're useful for any business but they go beyond what a standard accounting system offers.
Examples:
- **Receipt OCR**: Scan receipts and extract data automatically
- **AI Categorization**: AI-powered transaction categorization suggestions
- **AI Chat**: AI assistant for tax and bookkeeping questions
- **Push Notifications**: Event notifications for accounting activities
- **Enable Banking**: PSD2 automatic bank transaction sync
These are configured via `extensions.config.json` and only loaded when explicitly enabled by the operator.
### Sector Extensions
Sector extensions are tied to a specific market sector. They're only relevant to businesses operating in that sector. A restaurant owner wants "Food Cost %" but an IT consultant does not.
Examples of what a sector extension could be (design intent, none of these exist):
- **Restaurant:** Food Cost %, Earnings Per Alcohol Liter, POS Z-Report Import, Tip Tracking
- **Construction:** ROT Calculator, Project Cost Tracking
- **Hotel:** RevPAR, Occupancy Tracking
- **IT/Consulting:** Billable Hours Ratio, Project Billing Metrics
- **E-commerce:** Multi-channel Revenue Analytics
**Current state (2026-08-26):** no sector extension has been built. Every shipped extension lives under `extensions/general/`, and `SectorSlug` in `lib/extensions/types.ts` is currently just `'general'`. The sector concept, the marketplace routes (`app/(dashboard)/extensions/[sector]/...`) and the `sector/slug` extension-id format are in place for when the first one arrives. Shopify and WooCommerce order import shipped as general extensions, not e-commerce sector ones.
### The Unified Model
Both general and sector extensions live in the same system:
```
extensions/
general/ ← General extensions (any business); the only sector today
arcim-migration/ ← Systemmigration: import from Fortnox, Visma, Bokio, Björn Lundén, Briox
bolagsverket/ ← Digital årsredovisning filing to Bolagsverket (iXBRL)
calendar/ ← Kalender: month/week/day views
cloud-backup/ ← Molnsynkronisering: sync the säkerhetsbackup to the user's own cloud storage
document-extraction/ ← AI-extrahering av underlag: reads receipts and invoices, fills supplier/amount/VAT/date
email/ ← E-post (Resend or SMTP): invoices and reminders by e-mail
enable-banking/ ← Bankintegration (PSD2): automatic bank transaction sync
invoice-inbox/ ← Dokumentinkorg: forward supplier invoices to a unique address
mail/ ← Brevlådor: lets Kvittojakten (receipt hunt) search the user's mailboxes
mcp-server/ ← MCP-server (API): bookkeeping via Claude, Cursor or any MCP client
push-notifications/ ← Push-notiser: event notifications
shopify/ ← Shopify: paid orders and refunds into the Ordersidan
skatteverket/ ← Skatteverket: VAT declaration submission via BankID, skattekonto
stripe/ ← Stripe-betalningar: payment links on invoices, automatic avprickning
tic/ ← Bolagsuppgifter: company data from public registers via TIC
whatsapp-inbox/ ← WhatsApp-inkorg: receipts as photo or PDF to Accounted's WhatsApp number
woocommerce/ ← WooCommerce: paid orders and refunds into the transaction inbox
_example-branding/ ← Whitelabel branding starter (disabled by default)
example-logger/ ← Minimal example extension (index.ts only, no manifest)
```
Which of these are compiled in is decided by `extensions.config.json`; today that is everything except `bolagsverket`, `push-notifications`, `_example-branding` and `example-logger`.
Each extension directory contains a `manifest.json` declaring metadata, entry point, workspace component path, required env vars, and npm dependencies.
In the marketplace:
- General extensions are shown to everyone, always visible
- Sector extensions are suggested based on the user's primary sector
- But all extensions are browsable by everyone regardless of sector
In the sidebar under "Your Extensions":
- Both general and sector extensions appear together
- Whatever the user has enabled shows up here
---
## Design Decisions (Confirmed)
### 1. Extensions are self-contained: they do NOT write to the core accounting system
Extensions are **independent tools that live on the dashboard**. They are NOT part of the core accounting system. They have their own world, their own data, their own purpose. They never create journal entries, invoices, or modify any accounting records.
There are two one-way data flows into an extension. Data never flows back:
```
Core Accounting Data ──→ Extension (reads it, displays it, uses it in calculations)
User Manual Input ──→ Extension (stores it in extension's own data, processes it)
Extension ──✗──→ Core Accounting (never writes back)
```
An extension may:
- **Be fed core data**: the platform feeds accounting data (journal entries, transactions, invoices) into the extension for it to read and use in calculations
- **Accept user input**: the user submits data directly into the extension for data that doesn't exist in any accounting system (e.g. liters of alcohol sold per day, POS Z-report files, Shopify order exports)
- **Store its own data**: extension-specific data lives in the extension's own storage, separate from core accounting
- **Calculate and display**: combine core data + extension data to produce metrics, reports, insights
An extension may NOT:
- Create journal entries
- Create or modify invoices
- Modify transactions or any core accounting table
- Write back to the core accounting system in any way
This is a critical architectural constraint. Extensions are safe: enabling or disabling one can never corrupt or affect the accounting data. The core bookkeeping is a walled garden that extensions can look into but never modify.
**Important:** Features like POS Z-Report Import and Shopify Order Import are EXTENSIONS. They import data into the extension's own storage and provide analytics on that data. They do not create journal entries from imported data. The bookkeeping of POS data or Shopify orders is a separate activity the user does in the core platform.
### 2. Data source depends on the extension: three patterns
**Pattern A: Fed from core accounting data**
Some extensions are fed existing bookkeeping data. For example, a "Food Cost %" extension reads journal entries for food purchase accounts (4000-series) and food revenue accounts (3000-series), then calculates and displays the metric. The user doesn't enter anything: the data already exists in the bookkeeping. These are extensions for data that Fortnox, Visma, and other accounting systems already have.
**Pattern B: User submits data manually**
Some extensions need data that doesn't exist in any accounting system. No system tracks liters of alcohol sold, or daily staff tips, or room occupancy counts. For these extensions, the user manually submits data into the extension's workspace. The extension stores, processes, and displays this data. This has nothing to do with the core accounting functionality.
**Pattern C: Both**
Some extensions combine core accounting data with user-submitted data. "Earnings Per Alcohol Liter" reads alcohol revenue from the bookkeeping (Pattern A) and takes user-entered liter counts (Pattern B) to calculate revenue per liter.
### 3. Extension marketplace for browsing
Users have a dedicated "Extensions" marketplace page where they can:
- Browse all compiled extensions (general + all sectors)
- Read descriptions and details
- Open extension workspaces
### 4. Primary sector with cross-sector browsing
During onboarding, the user selects a **primary sector** (e.g. "Restaurant & Cafe"). The app then suggests extensions for that sector, plus general extensions. But the user is NOT locked in: they can browse and enable extensions from any sector at any time via the marketplace.
The primary sector serves as a **recommendation filter**, not a restriction.
### 5. First-party now, third-party later
We build all extensions ourselves initially. But the architecture should be clean and well-defined enough that external developers could eventually build extensions too. This means:
- Clear extension interface/contract
- Well-documented data access patterns
- Self-contained extension structure (each extension is a standalone module)
---
## The User Experience
1. User signs up, goes through onboarding
2. On the dashboard, the sidebar shows links to compiled extensions that have a workspace + quickAction
3. Clicking an extension opens its workspace: a dedicated page with the extension's own UI
4. The user interacts with the extension: views data, enters inputs, sees calculations/reports
5. User can browse the marketplace to see all compiled extensions
---
## Extension Definition
### What an Extension Contains
| Part | Required? | Description |
|------|-----------|-------------|
| **Metadata** | Yes | Name, description, sector (or 'general'), category, icon: for marketplace and sidebar |
| **Workspace UI** | Yes | A React component: the main page the user sees when they click the extension |
| **Extension data** | Depends | Storage for user-submitted data and extension state |
| **Configuration** | Optional | Settings panel for customizing the extension's behavior |
| **Core data queries** | Optional | Queries that read from journal entries, transactions, invoices, etc. |
### Marketplace Definition (ExtensionDefinition)
This is the metadata used for the marketplace UI and sector browsing. It comes from each extension's `manifest.json` file and is code-generated into `lib/extensions/_generated/sector-definitions.ts`.
```typescript
interface ExtensionDefinition {
// Identity
slug: string // URL-safe ID, unique within sector (e.g. 'earnings-per-liter')
name: string // Display name (e.g. 'Earnings Per Alcohol Liter')
sector: SectorSlug // 'general' | 'restaurant' | 'construction' | 'hotel' | 'tech' | 'ecommerce' | 'export'
category: ExtensionCategory // 'accounting' | 'reports' | 'import' | 'operations'
// Display (for marketplace and sidebar)
description: string // One-line description
longDescription: string // Detailed description with features
icon: string // Lucide icon name
entityTypes?: EntityType[] // Supported entity types (default: both EF and AB)
// Data patterns
dataPattern: 'core' | 'manual' | 'both' // How the extension gets its data
readsCoreTables?: string[] // Which core tables this extension reads (for pattern A/C)
hasOwnData?: boolean // Whether users submit data into this extension (for pattern B/C)
// Optional
quickAction?: QuickActionDefinition // Dashboard quick action
subscriptionNotice?: string // Notice shown when enabling (e.g. external subscription)
}
```
### Runtime Extension Interface
This is the contract for extension logic at runtime. Extensions are imported and registered by the loader.
```typescript
interface Extension {
id: string
name: string
version: string
sector?: SectorSlug
// Surfaces
routes?: RouteDefinition[]
apiRoutes?: ApiRouteDefinition[] // Dispatched by catch-all at /api/extensions/ext/
sidebarItems?: SidebarItem[]
eventHandlers?: ExtensionEventHandler[]
mappingRuleTypes?: MappingRuleTypeDefinition[]
reportTypes?: ReportDefinition[]
settingsPanel?: SettingsPanelDefinition
taxCodes?: TaxCodeDefinition[]
dimensionTypes?: DimensionDefinition[]
/** Named services this extension provides to core via registry lookup */
services?: Record<string, (...args: any[]) => Promise<any>>
// Lifecycle hooks
onInstall?(ctx: ExtensionContext): Promise<void>
onUninstall?(ctx: ExtensionContext): Promise<void>
}
```
### Sector Definition
```typescript
interface Sector {
slug: SectorSlug // 'general' | 'restaurant' | 'construction' | 'hotel' | 'tech' | 'ecommerce' | 'export'
name: string // 'General' | 'Restaurant & Cafe' | etc.
icon: string // Lucide icon name
description: string // Short tagline
extensions: ExtensionDefinition[]
}
```
### Extension Categories
```typescript
type ExtensionCategory = 'accounting' | 'reports' | 'import' | 'operations'
```
| Category | Color | Purpose |
|----------|-------|---------|
| Accounting & Tax | Red | Calculations related to bookkeeping, VAT, deductions |
| Industry Reports | Blue | KPIs, analytics, metrics |
| Smart Import | Green | Parse and import data from external tools |
| Operational Tools | Gray | Day-to-day business tools |
---
## Concrete Examples
| Extension | Sector | Data Pattern | User Input | Reads Core Data | What it Does |
|-----------|--------|--------------|------------|-----------------|--------------|
| Receipt OCR | General | B (manual) | Uploads receipt images | None | Scans receipts, extracts merchant/amount/VAT data |
| AI Categorization | General | A (core) | None | Uncategorized transactions | Suggests BAS account categories using AI |
| Enable Banking | General | B (manual) | Bank connection setup | None | Syncs bank transactions via PSD2 |
| Earnings Per Alcohol Liter | Restaurant | A + B (both) | Liters sold per day/week | Alcohol revenue from BAS 3001 | Calculates revenue/liter, trends over time |
| Food Cost % | Restaurant | A (core) | None | Food purchases (4000-series), food revenue (3000-series) | Calculates food_cost/food_revenue %, trends |
| Tip Tracking | Restaurant | B (manual) | Tip amounts per shift | Optionally reads staff cost accounts | Total tips, tips/employee, tip % of revenue |
| POS Z-Report Import (not built) | Restaurant | B (manual) | Uploads Z-report CSV/Excel | None | Parses POS data, stores in extension, shows daily sales analytics |
| Shopify / WooCommerce (shipped, general) | General | B (manual) | Store connection | None | Pulls paid orders and refunds into `webshop_orders` for the order and transaction inboxes |
| ROT Calculator | Construction | A + B (both) | Labor hours, material costs per job | Invoice data for customer billing | ROT deduction amounts (30% of labor, max 50k/year per customer) |
| RevPAR | Hotel | A + B (both) | Room count and occupancy | Room revenue accounts | Revenue Per Available Room, occupancy rate |
| Billable Hours Ratio | IT/Consulting | A + B (both) | Hours worked per project | Invoice data for billed amounts | Billable/total hours, effective hourly rate |
---
## Architecture
### Where Things Live
```
extensions/ ← Extension source code (opt-in via config)
general/ ← General extensions (the only sector that exists)
invoice-inbox/
manifest.json ← Metadata, entry point, env vars, workspace path
index.ts ← Extension definition + logic (exports Extension)
lib/
__tests__/
document-extraction/
manifest.json
index.ts
skatteverket/
manifest.json
index.ts
lib/
push-notifications/
manifest.json
index.ts
api-routes.ts
notification-scheduler.ts
notification-sender.ts
enable-banking/
manifest.json
index.ts
lib/
components/
email/ ← Email service extension (registers Resend impl)
manifest.json
index.ts
lib/
calendar/
manifest.json
index.ts
components/
mcp-server/ ← MCP server: server.ts, tools, prompts, resources, skills, widgets
manifest.json
index.ts
server.ts
arcim-migration/ ← Provider migration (Fortnox, Visma, Bokio, BL, Briox)
bolagsverket/ ← Digital årsredovisning (iXBRL)
cloud-backup/ ← Cloud sync of the säkerhetsbackup
mail/ ← Mailbox connections for Kvittojakten
shopify/ ← Shopify order import (api-routes.ts, components/, lib/)
woocommerce/ ← WooCommerce order import (api-routes.ts, components/, lib/)
stripe/ ← Stripe payment links and avprickning
tic/ ← Company data lookup (TIC)
whatsapp-inbox/ ← WhatsApp receipt intake
_example-branding/ ← Whitelabel starter, disabled by default
example-logger/ ← Minimal example, index.ts only
extensions.config.json ← Which extensions are enabled (empty = core-only)
extensions.schema.json ← JSON Schema for extensions.config.json
lib/
extensions/
types.ts ← Extension, ExtensionDefinition, Sector types
sectors.ts ← Sector shells + generated extension definitions
workspace-registry.tsx ← Maps sector/slug → lazy-loaded React component
loader.ts ← Imports from _generated, registers extensions
registry.ts ← Runtime extension registry (get, register)
context-factory.ts ← Builds ExtensionContext for handlers
_generated/ ← AUTO-GENERATED by npm run setup:extensions
extension-list.ts ← FIRST_PARTY_EXTENSIONS array (static imports)
workspace-map.tsx ← Lazy-loaded workspace components
sector-definitions.ts ← ExtensionDefinition[] per sector
enabled-extensions.ts ← ENABLED_EXTENSION_IDS set for build-time checks
email/
service.ts ← EmailService interface + no-op default + getEmailService()
reports/
sru-encoding.ts ← SRU file encoding (core, not an extension)
ne-bilaga/ ← NE tax form attachment (core, not an extension)
scripts/
generate-extension-registry.ts ← Reads config + manifests, writes _generated/ files
app/api/extensions/
ext/[...path]/
route.ts ← Catch-all API dispatcher for extension routes
components/
extensions/
ExtensionWorkspaceShell.tsx ← Shared layout wrapper
shared/ ← Shared UI primitives
KPICard.tsx
DataEntryForm.tsx
DateRangeFilter.tsx
EmptyExtensionState.tsx
ExtensionLoadingSkeleton.tsx
general/ ← General extension workspaces (the only ones that exist)
ReceiptOcrWorkspace.tsx
AiCategorizationWorkspace.tsx
InvoiceInboxWorkspace.tsx
EnableBankingWorkspace.tsx
CalendarWorkspace.tsx
CloudBackupWorkspace.tsx
ArcimMigrationWorkspace.tsx
PushNotificationsWorkspace.tsx
TicWorkspace.tsx
MailConnectionsPanel.tsx
WhatsAppLinkPanel.tsx
app/(dashboard)/
extensions/ ← Marketplace
page.tsx ← Extension hub (browse sectors + general)
[sector]/
page.tsx ← Extensions for a specific sector
[extension]/
page.tsx ← Extension detail + workspace link
e/ ← Extension workspaces
[sector]/
[slug]/
page.tsx ← Renders the workspace component
```
### Data Storage
Extensions store their data in the existing `extension_data` table:
```
extension_data:
user_id: auth user
extension_id: 'restaurant/earnings-per-liter' (sector/slug format)
key: 'settings' | 'entries' | 'config' | custom keys
value: JSONB (flexible)
```
For the "Earnings Per Liter" extension, data might look like:
```
key: 'settings' → { "defaultUnit": "liter", "currency": "SEK" }
key: 'entries' → [{ "date": "2025-01-15", "liters": 42.5, "type": "spirits" }, ...]
key: 'config' → { "revenueAccounts": ["3001"], "trackByType": true }
```
### Extension Enablement
Extensions are enabled at **build time** via `extensions.config.json`. All compiled extensions are active for all users: there is no per-user toggle system. The operator (hosted or self-hosted) decides which extensions to include.
To check if an extension is compiled in at runtime (e.g. for conditional UI), use the build-time constant:
```typescript
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
if (ENABLED_EXTENSION_IDS.has('document-extraction')) {
// Show AI extraction status UI
}
```
> **Note:** The `extension_toggles` database table still exists but is no longer queried by any code. It can be dropped in a future migration.
### API Routes for Extensions
Extensions declare their API routes via the `apiRoutes` array on the `Extension` object:
```typescript
export const myExtension: Extension = {
id: 'my-extension',
// ...
apiRoutes: [
{
method: 'POST',
path: '/',
handler: async (request: Request, ctx?: ExtensionContext) => {
// Handle POST /api/extensions/ext/my-extension/
return new Response(JSON.stringify({ ok: true }))
},
},
{
method: 'GET',
path: '/:id',
handler: async (request: Request, ctx?: ExtensionContext) => {
// :id is extracted and available as ?_id=... search param
const url = new URL(request.url)
const id = url.searchParams.get('_id')
return new Response(JSON.stringify({ id }))
},
},
],
}
```
All extension API routes are served by a single **catch-all dispatcher** at:
```
app/api/extensions/ext/[...path]/route.ts
```
URL scheme: `/api/extensions/ext/{extensionId}/{...routePath}`
The dispatcher handles:
1. **Auth check**: 401 if not logged in
2. **Extension lookup**: 404 if extension not registered or has no apiRoutes
3. **Path matching**: Matches method + path pattern (supports `:param` wildcards)
4. **AI consent check**: 403 if AI extension and user hasn't consented
5. **Param extraction**: Path params like `:id` are added as `_id` search params
6. **Context building**: Creates `ExtensionContext` with supabase, userId, settings, storage, logger
7. **Dispatch**: Calls the matched handler with the request and context
The generic data CRUD routes for `extension_data` still exist alongside:
```
app/api/extensions/[sector]/[slug]/
data/route.ts : GET (read entries), POST (submit new entry), DELETE (remove entry)
settings/route.ts : GET (read settings), PATCH (update settings)
```
### Sidebar Integration
The sidebar (`DashboardNav.tsx`) has a section for extensions. It shows all compiled extensions that have a workspace and a `quickAction` with an `href`:
```
── Your Extensions ──────────
📥 Dokumentinkorg → /e/general/invoice-inbox
📊 Food Cost % → /e/restaurant/food-cost
🍷 Earnings Per Liter → /e/restaurant/earnings-per-liter
```
Each link goes to `/e/{sector}/{slug}` which renders the extension's workspace component.
---
## The Extension Workspace Pattern
Every extension workspace follows the same pattern:
```
┌─────────────────────────────────────────────────┐
│ Extension Workspace Shell │
│ ┌─────────────────────────────────────────────┐ │
│ │ Header: Extension name + settings link │ │
│ ├─────────────────────────────────────────────┤ │
│ │ │ │
│ │ Extension-specific UI │ │
│ │ │ │
│ │ This is where the extension does its thing │ │
│ │ - Data entry forms │ │
│ │ - KPI cards and charts │ │
│ │ - Tables of submitted data │ │
│ │ - Calculation results │ │
│ │ - Date range filters │ │
│ │ │ │
│ └─────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────┘
```
The `ExtensionWorkspaceShell` provides consistent chrome (header, breadcrumbs, settings link). The extension fills in the content area with whatever UI it needs.
### Example: Earnings Per Alcohol Liter
When the user clicks this extension, they see:
1. **KPI cards at top**: Current earnings/liter, trend vs last month, total liters this month
2. **Data entry section**: Form to log daily sales (date, liters sold, alcohol type)
3. **History table**: Past entries with edit/delete
4. **Chart**: Earnings per liter over time (line chart)
5. **Revenue breakdown**: Reads from core journal entries: alcohol revenue by account
The extension reads revenue data from journal_entry_lines (BAS 3001 for 25% alcohol revenue) and combines it with user-submitted liter data to calculate the metric.
---
## Migration from Previous Architecture (Completed)
The previous architecture had extensions "always loaded" via hardcoded static imports in `loader.ts`, with SRU export and NE-bilaga treated as extensions. The system was fully decoupled in "Plan B: Full Decoupling":
### What Changed
1. **Extension opt-in system** -- Extensions are configured via `extensions.config.json`. A generator script (`npm run setup:extensions`) reads manifest files and produces `lib/extensions/_generated/` files. Core compiles and runs with an empty config (zero extensions).
2. **Services pattern** -- Extensions can expose named services via `services?: Record<string, (...args: any[]) => Promise<any>>` on the Extension interface. Core code uses `extensionRegistry.get('ext-id')?.services?.methodName` for runtime lookup instead of direct imports. This is how `skatteverket` exposes declaration submission to core pending-operation commits, and how `stripe` provides invoice payment links.
3. **Catch-all API dispatcher** -- Extension API routes are registered via `apiRoutes: ApiRouteDefinition[]` on the Extension object. The catch-all at `/api/extensions/ext/[...path]/route.ts` handles auth, path param extraction, and dispatches to the handler. URL pattern: `/api/extensions/ext/{extensionId}/{path}`.
4. **SRU/NE-bilaga are core** -- These tax compliance features were moved from `extensions/` into `lib/reports/sru-export/` and `lib/reports/ne-bilaga/`. They are always available regardless of extension configuration.
5. **Email is optional** -- Core defines an `EmailService` interface in `lib/email/service.ts` with a no-op default. The `email` extension registers a Resend implementation at load time. Core callers use `getEmailService()` -- when the email extension is not enabled, email calls silently return `{ success: false }`.
6. **Export sector** -- EU Sales List, Intrastat, VAT Monitor, and Currency Receivables are extensions under `extensions/export/`.
7. **Manifest files** -- Every extension has a `manifest.json` that declares metadata, entry point, workspace component path, required env vars, optional env vars, and npm dependencies.
8. **Generated files** -- Three files in `lib/extensions/_generated/` are produced by the generator:
- `extension-list.ts` -- Static imports and `FIRST_PARTY_EXTENSIONS` array
- `workspace-map.tsx` -- `next/dynamic` lazy-loaded workspace components
- `sector-definitions.ts` -- `ExtensionDefinition[]` per sector for the marketplace UI
---
## Implementation Status
| Item | Status | Notes |
|------|--------|-------|
| Extension types (ExtensionDefinition, Sector, etc.) | Done | `lib/extensions/types.ts` |
| Sector data registry | Done | `lib/extensions/sectors.ts` + generated definitions |
| Database migration (extension_toggles) | Done | Migration 037 (table exists but no longer queried) |
| Build-time extension check | Done | `ENABLED_EXTENSION_IDS` in `_generated/enabled-extensions.ts` |
| Workspace component registry | Done | `lib/extensions/workspace-registry.tsx` + generated map |
| Workspace routing (`/e/[sector]/[slug]`) | Done | `app/(dashboard)/e/[sector]/[slug]/page.tsx` |
| Workspace shell | Done | `components/extensions/ExtensionWorkspaceShell.tsx` |
| Marketplace pages | Done | `app/(dashboard)/extensions/` |
| Sidebar "Your Extensions" | Done | Wired into DashboardNav |
| Onboarding with build-time extension checks | Done | Uses `ENABLED_EXTENSION_IDS` |
| Shared UI components | Done | KPICard, DataEntryForm, DateRangeFilter, etc. |
| Extension API routes (generic CRUD) | Done | `app/api/extensions/[sector]/[slug]/` |
| Catch-all API dispatcher | Done | `app/api/extensions/ext/[...path]/route.ts` |
| Services pattern | Done | Used by skatteverket (declaration submission) and stripe (payment links) |
| Email service interface | Done | `lib/email/service.ts` + email extension |
| SRU/NE-bilaga moved to core | Done | `lib/reports/sru-export/` + `lib/reports/ne-bilaga/` |
| Manifest files for all extensions | Done | 25 manifest.json files |
| Code generator | Done | `scripts/generate-extension-registry.ts` |
| extensions.config.json opt-in | Done | Core runs with empty config |
| General extensions with manifests | Done | All general extensions have manifests |
| Export sector extensions | Done | EU Sales List, Intrastat, VAT Monitor, Currency Receivables |
| Restaurant sector extensions | Done | Food Cost, Earnings Per Liter, POS Import, Tip Tracking |
| Construction sector extensions | Done | ROT Calculator, Project Cost |
| Hotel sector extensions | Done | RevPAR, Occupancy |
| Tech sector extensions | Done | Billable Hours, Project Billing |
| E-commerce sector extensions | Done | Shopify Import, Multichannel Revenue |
---
## Self-Hosting Guide
### Core Setup (No Extensions)
Core runs with zero extensions. This gives you the standard accounting system: bookkeeping, invoicing, bank reconciliation, reports, tax compliance (SRU, NE-bilaga, VAT declaration).
```bash
# 1. Clone and install
git clone <repo-url> && cd Accounted
npm install
# 2. Set environment variables (minimum 4)
export NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
export NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
export SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
export NEXT_PUBLIC_APP_URL=https://your-domain.com
# 3. Run database migrations
# Apply all migrations in supabase/migrations/ to your Supabase project
# 4. Build and run
npm run build # setup:extensions runs automatically (empty config = no extensions)
npm start
```
### Enabling Extensions
```bash
# 1. See available extensions
npx tsx scripts/generate-extension-registry.ts --list
# 2. Edit extensions.config.json: add extension IDs
{
"extensions": ["invoice-inbox", "document-extraction", "email"]
}
# 3. Regenerate (also runs automatically on build/dev)
npm run setup:extensions
# 4. Set extension-specific env vars (check each manifest.json for requiredEnvVars)
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
export AWS_REGION=eu-north-1
export RESEND_API_KEY=...
export RESEND_FROM_EMAIL=...
# 5. Rebuild
npm run build
```
The `extensions.config.json` file is validated against `extensions.schema.json`. The generator will error if you reference an unknown extension ID.
---
## Extension Developer Guide
### Creating a New Extension
**Option 1: Manual creation**
1. Create the extension directory: `extensions/<sector>/<name>/`
2. Create `manifest.json`:
```json
{
"id": "my-extension",
"sector": "general",
"exportName": "myExtension",
"entryPoint": "@/extensions/general/my-extension",
"workspace": "@/components/extensions/general/MyExtensionWorkspace",
"requiredEnvVars": [],
"optionalEnvVars": [],
"npmDependencies": [],
"definition": {
"name": "My Extension",
"category": "reports",
"icon": "BarChart",
"dataPattern": "core",
"readsCoreTables": ["journal_entry_lines"],
"description": "Short description",
"longDescription": "Detailed description with features and use cases."
}
}
```
3. Create `index.ts` exporting the Extension object:
```typescript
import type { Extension } from '@/lib/extensions/types'
export const myExtension: Extension = {
id: 'my-extension',
name: 'My Extension',
version: '1.0.0',
sector: 'general',
// ... surfaces, services, event handlers
}
```
4. Create the workspace component at the path specified in `manifest.workspace`
5. Add the extension ID to `extensions.config.json`
6. Run `npm run setup:extensions`
**Manifest fields:**
| Field | Required | Description |
|-------|----------|-------------|
| `id` | Yes | Unique extension ID (matches config and Extension.id) |
| `sector` | Yes | Sector slug |
| `exportName` | No | Named export from entryPoint (null = metadata-only extension) |
| `entryPoint` | No | Import path for the Extension object (null = no runtime logic) |
| `workspace` | No | Import path for the workspace React component (null = no UI) |
| `requiredEnvVars` | Yes | Env vars that must be set for the extension to work |
| `optionalEnvVars` | Yes | Env vars that enhance but are not required |
| `npmDependencies` | Yes | npm packages the extension depends on |
| `definition` | Yes | Marketplace metadata (name, category, icon, description, etc.) |
Extensions with `exportName: null` and `entryPoint: null` are metadata-only -- they appear in the marketplace and have a workspace UI but no server-side runtime logic (e.g. pure frontend calculators like Food Cost %).
### Services Pattern
Extensions can expose named services for cross-boundary calls. This avoids direct imports from extension code into core:
```typescript
// Extension: stripe/index.ts
export const stripeExtension: Extension = {
id: 'stripe',
name: 'Stripe',
version: '1.0.0',
services: {
createInvoicePaymentLink: async (companyId: string, invoiceId: string) => {
// ... eligibility checks + Stripe API call
return { url, externalId }
},
},
}
```
Core code calls the service via registry lookup:
```typescript
// Core code: no direct import from extensions/
// (real example: lib/extensions/payment-links.ts)
const ext = extensionRegistry.get('stripe')
const link = await ext?.services?.createInvoicePaymentLink(companyId, invoiceId)
if (link) {
// Use link
}
// Gracefully degrades if extension is not loaded
```
This pattern is used for:
- `stripe` providing invoice payment links to the core invoice send routes (`lib/extensions/payment-links.ts`)
- `skatteverket` exposing declaration submission to core pending-operation commits
- Any extension that needs to provide functionality callable by core without a direct dependency
### Event Bus Usage
Extensions subscribe to events emitted by core. Handlers run concurrently via `Promise.allSettled` -- a failing handler never crashes the emitter.
```typescript
export const myExtension: Extension = {
id: 'my-extension',
// ...
eventHandlers: [
{
eventType: 'transaction.categorized',
handler: async (payload, ctx) => {
// React to categorized transactions
// ctx provides supabase, userId, settings, storage, log
},
},
],
}
```
Events are one-way: core services emit, extensions subscribe. Extensions should never emit events back to core. If an extension is not compiled in (not in `extensions.config.json`), its handlers are never registered.
### Workspace Components
Workspace components are React components rendered at `/e/{sector}/{slug}`. They receive `{ userId: string }` as props and are lazy-loaded via `next/dynamic`.
The workspace path is declared in `manifest.json` under the `workspace` field. The generator creates a dynamic import map in `_generated/workspace-map.tsx`.
All workspace components should use the `ExtensionWorkspaceShell` wrapper for consistent layout (header, breadcrumbs, settings link).
### Email Service Interface Pattern
The email extension demonstrates how to make a core capability optional:
1. **Core defines the interface** (`lib/email/service.ts`):
- `EmailService` interface with `sendEmail()` and `isConfigured()`
- `NoopEmailService` as default (returns `{ success: false }`)
- `getEmailService()` getter and `registerEmailService()` setter
2. **Extension registers the implementation** (`extensions/general/email/index.ts`):
- Imports `registerEmailService` from core
- Creates `ResendEmailService` and registers it at load time
3. **Core callers use the getter** -- never import from the extension:
```typescript
const emailService = getEmailService()
if (emailService.isConfigured()) {
await emailService.sendEmail({ to, subject, html })
}
```
This pattern can be reused for any capability that should degrade gracefully when its extension is not loaded.
---
## Summary
**The app** is a Swedish accounting platform.
**Core functionality** is the standard accounting system: bookkeeping, invoicing, reports, tax (SRU, NE-bilaga), bank reconciliation. Every user gets this. Core compiles and runs with zero extensions.
**Extensions** are everything beyond core accounting. They come in three kinds:
- **General extensions** (invoice-inbox, document-extraction, email, etc.) -- useful for any business, not sector-specific
- **Sector extensions** (food cost %, earnings per liter, etc.) -- tied to a specific market sector
- **Export extensions** (EU Sales List, Intrastat, etc.) -- for businesses with international trade
All extensions live in the same system, appear in the same marketplace, and show up in the sidebar when they have a workspace + quickAction. All compiled extensions are active for all users -- the operator chooses which to include in `extensions.config.json` at build time.
Extensions are read-only with respect to the core accounting system. They can be fed accounting data, they can accept manual user input, but they never write back to the bookkeeping. They can expose services to core via the registry lookup pattern, and they can register API routes that are dispatched by the catch-all handler.
-147
View File
@@ -1,147 +0,0 @@
# Peppol invoice foundation
Issue #546 requires two separable capabilities:
1. Produce a correctly structured Peppol BIS Billing 3 invoice from Accounted data.
2. Deliver and receive documents through the Peppol network.
The first slice implemented the invoice profile. The second slice added an immutable staged-delivery and audit foundation. Neither of those two slices claimed network delivery; since 2026-08-21 both sending and receiving run over the Peppol network through Qvalia (see the Qvalia and Receiving (PR2) sections below). The sections up to "Access point: Qvalia" describe the foundation those slices left behind and the requirements the Qvalia work had to meet.
## Implemented scope
`GET /api/invoices/{id}/peppol` produces a UBL 2.1 invoice with the Peppol BIS Billing 3 CustomizationID and ProfileID. It is available to an authenticated member of the active company and applies the same explicit `company_id` isolation as other invoice routes.
`POST /api/invoices/{id}/peppol` now stores the exact generated XML as an immutable staged delivery. Staging assigns a stable UUID idempotency key, stores the recipient, profile identifiers, filename, SHA-256, retention date, and an append-only local audit event. It explicitly returns `network_submitted: false`. Repeating the request for the same invoice and XML returns the existing staged record.
`GET /api/invoices/{id}/peppol/deliveries` returns a minimized status timeline projection without exposing XML, raw webhooks, or provider evidence. The invoice page can prepare a delivery; since 2026-08-21 its send control performs the network send through `POST /api/invoices/{id}/peppol/send` for companies holding a Peppol access grant (aktiebolag senders, standard invoices only; see "Access point: Qvalia" below).
The provider-neutral `PeppolTransport` boundary separates:
- recipient lookup and advertised document/process capabilities;
- idempotent submission and provider correlation;
- cryptographically verified webhook normalization;
- evidence retrieval, including an optional exact transmitted document.
Core registers an adapter only when provider credentials are present in the environment (`lib/init.ts`); no environment value can make an absent adapter appear available.
The export supports:
- numbered standard sales invoices, not credit notes, self-billing, proformas, or delivery notes;
- Swedish limited-company sellers and organization-number buyers identified with scheme `0007`;
- SEK invoices with Swedish standard VAT categories at 6, 12, or 25 percent;
- Bankgiro or Plusgiro credit transfers using payment means code `30` and an OCR reference;
- mixed supported VAT rates, text-line omission, and UNECE unit mappings for Accounted's invoice units;
- Accounted's SEK rounding as `PayableRoundingAmount`;
- buyer reference, address, VAT, F-tax, payment, totals, and line reconciliation checks;
- deterministic UTF-8 XML download from the invoice detail page.
Unsupported input is rejected with structured, field-addressable errors. The generator never emits partial XML after a failed preflight.
Sole-trader sellers and personnummer-derived `0007` identifiers are rejected. They require a separately configured `0088` GLN so the export does not publish personal identity data as a Peppol participant identifier.
The local preflight is not a replacement for the official validation stack. Before network delivery, every document must pass the UBL XSD, EN 16931 Schematron rules, and the Peppol BIS Billing rules for the active release. The selected access-point provider must perform that validation as part of submission. Accounted should also run the same release-pinned artifacts before calling the provider so failures can be explained before transport.
## Remaining architecture
The subsections below are the requirements written before the Qvalia decision. Access-point delivery and the UI send flow shipped on 2026-08-21 and are described under "Access point: Qvalia"; the text is kept as the acceptance criteria that work met. Standards validation (the release-pinned validator run before transport) is still open.
### Standards validation
Pin and execute the official release artifacts from OpenPeppol and the EN 16931 validation artifact registry. The November 2025 release is the active production release at implementation time. The May 2026 release becomes mandatory on 17 August 2026, so provider onboarding and conformance testing must target the May 2026 validator before launch.
Validation must return stable rule identifiers, severity, source path, and localized remediation. Provider validation responses are useful evidence but must not become Accounted's only explanation layer.
### Access-point delivery
Accounted should integrate with a certified Peppol access-point provider. The provider owns AS4 transport, Peppol PKI, service metadata lookup, certificate rotation, and network conformance. Accounted should not implement an access point itself.
A provider adapter needs at least:
- recipient capability lookup by scheme and identifier;
- invoice submission with an Accounted idempotency key;
- a provider document identifier;
- synchronous rejection details;
- authenticated webhooks or polling for final transport status;
- test and production environments with equivalent validation behavior.
The existing email delivery model cannot honestly represent Peppol receipts. The Peppol-specific model therefore records `staged`, recipient lookup, submission acceptance, Corner 3 transport success, recipient acknowledgement, and business acceptance or rejection separately. Every verified raw event remains append-only even when it is duplicated or arrives out of order. The latest normalized status is only a projection.
### Status and audit handling
The Peppol-specific tables now preserve the exact staged XML, its SHA-256 hash, recipient scheme and identifier, provider and tenant correlation, attempt timestamps, normalized status, raw verified event metadata, immutable failure history, and retrieved evidence. A successful API acceptance is not the same as Corner 3 transport, and Corner 3 transport is not the same as buyer acknowledgement or business acceptance.
Provider event and evidence RPCs are service-role only. Future webhook routes must first use the selected adapter to authenticate and normalize the provider payload, then persist the verified event. A public webhook endpoint is intentionally not exposed before its authentication contract is known.
No invoice status should change merely because XML was generated or accepted by a provider. The send workflow must define exactly which provider receipt constitutes delivery, how retries preserve idempotency, and how a permanent rejection is shown without mutating the posted invoice.
### Receiving
Inbound invoices are a separate acceptance slice. It requires provider webhook authentication, raw XML retention, duplicate detection, supplier matching, safe attachment handling, and mapping into the supplier-invoice inbox without treating received content as trusted. The original foundation did not claim inbound support; that slice has since shipped (`peppol_registrations`, `peppol_inbound_documents`, the inbound cron and inbox delivery) and is described under "Receiving (PR2)" below.
### UI and API
The UI downloads a locally checked XML file and can prepare an immutable delivery snapshot. Both actions state that they did not send the invoice. Once an adapter exists, sending must be a distinct confirmation flow that performs recipient lookup, shows the discovered participant and capabilities, and records the resulting timeline. The download remains available for diagnosis and interoperability testing. Shipped 2026-08-21: the confirmation dialog on the invoice page and `POST /api/invoices/{id}/peppol/send` (see "Access point: Qvalia").
### Access point: Qvalia (decided 2026-08-21)
The contract with Qvalia (certified Swedish Access Point + SMP, partner model) was signed on 2026-08-21. The adapter lives in `lib/invoices/transports/qvalia.ts` and implements the `PeppolTransport` boundary:
- recipient lookup: `GET /partner/{partnerRegNo}/peppol/lookup/{scheme:id}?docTypeRoot=Invoice`;
- submission: `POST /partner/{partnerRegNo}/transaction/{accountRegNo}/invoices/outgoing` with the staged UBL XML (`content-type: application/xml`); the returned `integrationId` is the provider submission id; a `409` (same document id and receiver) is recovered to the existing `integrationId` only when Qvalia's stored copy carries the same seller endpoint, otherwise it stays a duplicate error;
- webhooks: `POST /api/webhooks/peppol/qvalia`, authenticated by the shared secret Accounted configures as Qvalia's outbound auth header (Qvalia does not sign webhooks); events are at-least-once and deduplicated on `eventType + globalTransactionId + status.status`; `status.status` is free text, so the mapping is tolerant and unknown wording never advances beyond `submission_accepted`;
- evidence: the message-log status and Qvalia's stored XML copy, recorded as `qvalia_message_record`.
Configuration is environment-only (`PEPPOL_TRANSPORT_PROVIDER=qvalia` plus `QVALIA_API_KEY`, `QVALIA_PARTNER_REG_NO`, `QVALIA_BASE_URL`, `QVALIA_WEBHOOK_SECRET`, optional `QVALIA_ACCOUNT_REG_NO`, `QVALIA_WEBHOOK_HEADER`, `QVALIA_AUTH_SCHEME`; see `.env.example`). `lib/init.ts` registers the adapter when the credentials are present; the product only sends when the provider is also selected. `scripts/peppol/qvalia-probe.ts` is the first-contact probe against the sandbox (auth scheme, child accounts, registered Peppol IDs, lookup, send).
`POST /api/invoices/{id}/peppol/send` performs the send: stage the exact XML, look up the recipient, record `recipient_verified` and `submitting`, submit, record `submission_accepted` with the provider submission id, and only then issue a draft with the mark-sent semantics (`issueAndBookInvoice`: F-number, status, verifikat under faktureringsmetoden, PDF archived as underlag). A synchronous rejection is recorded as a terminal `failed` event so the identical document is never re-sent; an operational failure is `retryable_failure` and a retry is allowed. Resending an exact XML that already carries a provider submission id is an idempotent replay, never a second transmission.
v1 uses Qvalia's consolidated setup (every company's documents under Accounted's partner account, `accountRegNo = partnerRegNo`). Qvalia confirmed (2026-08-21) that the sending account is irrelevant as long as `AccountingSupplierParty` carries a valid endpoint id, so no per-company child accounts are needed.
### Receiving (PR2)
- `peppol_registrations`: one live row per company and per participant; written by `POST/DELETE /api/settings/peppol` (service role after the membership check) through `lib/invoices/peppol-registration.ts`, which publishes `0007:orgnr` with the company's business card and the BIS Billing 3 Invoice + CreditNote document types via `transport.registerRecipient()`. Personnummer-based identifiers are refused (`0088` GLN pending). The switch lives in Settings > Fakturering ("E-faktura via Peppol").
- `peppol_inbound_documents`: every document the Access Point hands us, with the exact XML (immutable, undeletable) and the provider's UBL-JSON; routed to a company by the `AccountingCustomerParty` endpoint through the registrations; states `received`, `routed`, `unrouted`, `converted`, `ignored`, `failed`.
- `GET /api/peppol/inbound/cron` every 10 minutes: `lib/invoices/peppol-inbound.ts` lists unread invoices and credit notes, archives (`archiveInboundPeppolMessage`), routes and delivers; `lib/invoices/peppol-inbox-delivery.ts` archives the XML as a WORM document (`upload_source: 'e_invoice'`, no AI extraction), the embedded PDF when present, and creates the `invoice_inbox_items` row (`source: 'peppol'`) with the extraction filled from the structured UBL (`lib/invoices/peppol-inbound-ubl.ts`, confidence 1). The existing inbox review and convert flows take over from there.
- Outbound status without webhooks: `GET /api/peppol/outbound/status/cron` (four times an hour) asks the Access Point about every open delivery (`transport.pollDeliveryStatus`, Qvalia: `/invoices/outgoing/status`) and records the answer through the same lifecycle RPC a webhook uses, with the same dedupe key, so a later webhook for the same transition is a harmless duplicate. Needed because Qvalia's webhook API answers 404 on its production host (2026-08-21); kept as the safety net afterwards.
- Still open: the Qvalia `new_document` webhook for inbound (today polled), credit-note conversion from the inbox, `0088` GLN for enskild firma, the release-pinned validation stack, and a UI surface for `unrouted` documents.
### Storecove versus Qvalia (historical, pre-contract)
Storecove is the stronger fit for the lifecycle already modeled. Its official API documents recipient discovery, caller-supplied `idempotencyGuid`, a returned submission `guid`, tenant correlation, asynchronous sending webhooks, and a dedicated evidence endpoint. Its sandbox supports webhook simulation and the OpenPeppol test network. A Storecove adapter still requires a commercial contract and credentials; these public semantics do not prove Accounted's tenant is authorized or onboarded.
Qvalia is a Swedish certified Access Point and SMP with an explicit partner and multi-tenant offering. Its public quick start documents production and sandbox endpoints, account registration numbers, and separate keys. Public material does not currently specify a Storecove-equivalent contract for idempotency, signed webhooks, event ordering, or exact transmitted-document evidence. Those points must be obtained from Qvalia Sales or Support before an adapter can be production quality.
Inputs required for either selection:
- multitenant or reseller authorization for Accounted customer companies;
- setup, monthly, per-document, inbound, lookup, and support pricing;
- test and production API credentials and secret rotation;
- sender-only versus searchable participant registration;
- Swedish organization-number and optional GLN onboarding;
- webhook signing, retention, service levels, and data-processing terms;
- support for the mandatory May 2026 Peppol release.
Additional API contract inputs required before implementation:
- the external tenant, legal entity, and account identifiers for every Accounted company;
- exact discovery request and response semantics for `0007` and `0088` participants;
- idempotency retention, duplicate response behavior, and retry guarantees;
- webhook signature or authentication scheme, secret rotation, replay window, event identifiers, retry policy, and ordering guarantees;
- exact meanings of transport, acknowledgement, acceptance, rejection, and terminal events;
- evidence endpoint response, retention, exact-document guarantees, and audit export format;
- sandbox participant IDs, production onboarding checks, and agreed conformance acceptance tests.
Provider credentials and prices are external operational inputs. They are not invented, stored in source, or represented by a fake provider in this change.
## Primary specifications and authority guidance
- [OpenPeppol BIS Billing 3, November 2025](https://docs.peppol.eu/poacc/billing/3.0/2025-Q4/)
- [OpenPeppol BIS Billing 3, May 2026](https://docs.peppol.eu/poacc/billing/3.0/upcoming/)
- [OpenPeppol post-award release schedule](https://peppol.org/documentation/technical-documentation/post-award-documentation/)
- [European Commission EN 16931 validation artefacts](https://ec.europa.eu/digital-building-blocks/sites/display/DIGITAL/Registry+of+supporting+artefacts+to+implement+EN16931)
- [SFTI Peppol BIS Billing 3 guidance](https://www.sfti.se/sfti/standarder/peppolbisochpeppolinfrastruktur/peppolbisbilling3.26609.html)
- [Swedish authority guidance for connecting to Peppol](https://www.upphandlingsmyndigheten.se/inkopsprocessen/e-handel/peppol/anslut-till-peppol/)
- [Storecove API documentation](https://www.storecove.com/docs/)
- [Qvalia API quick start](https://api.qvalia.io/quick-start)
- [Qvalia API environments and formats](https://api.qvalia.io/api-documentation/apis)
- [Qvalia partner API and Peppol infrastructure](https://qvalia.com/help/overview-of-qvalias-partner-api-and-peppol-infrastructure/)
-667
View File
@@ -1,667 +0,0 @@
# Self-Hosting Accounted
This guide walks you through deploying Accounted on your own infrastructure using Docker.
## Prerequisites
- Docker and Docker Compose v2+
- A Supabase project (free tier works: create one at [supabase.com](https://supabase.com))
## 1. Create a Supabase Project
1. Go to [supabase.com](https://supabase.com) and create a new project.
2. Note these values from **Settings > API**:
- `Project URL` (e.g., `https://abcdefgh.supabase.co`)
- `anon` public key
- `service_role` secret key
## 2. Configure Supabase Auth
In the Supabase dashboard under **Authentication > URL Configuration**:
1. Set **Site URL** to your deployment URL (e.g., `https://gnubok.example.com`).
2. Add `https://gnubok.example.com/auth/callback` to the **Redirect URLs** allowlist.
Accounted uses email + password authentication with magic link as a fallback. The default Supabase email auth settings work out of the box. For production, configure a custom SMTP provider under **Authentication > SMTP Settings** to avoid Supabase's built-in rate limits. Keep **Secure email change** enabled (Authentication > Settings, on by default): a login-email change also removes social logins tied to the old address, so the old mailbox must confirm the change before it can lose its access.
MFA (two-factor authentication via TOTP) is **not enforced** for self-hosted deployments: the Docker image sets `NEXT_PUBLIC_SELF_HOSTED=true` by default, which disables MFA enforcement. Users can still optionally enable 2FA in Settings > Säkerhet if they wish. Idle and absolute session timeouts are also off by default for self-hosted installs; operators can opt in with the variables below.
## 3. Apply Database Migrations
The `supabase/migrations/` directory contains the ordered SQL files that set up the full schema, including tables, RLS policies, triggers, and functions.
**Option A: Supabase CLI (recommended):**
```bash
# Install the Supabase CLI
npm install -g supabase
# Link to your project
supabase link --project-ref <your-project-ref>
# Push all migrations
supabase db push
```
**Option B: SQL Editor:**
Run each file in `supabase/migrations/` in order in the Supabase SQL Editor. They must be applied sequentially: later migrations depend on earlier ones.
### PostgreSQL Extensions
The migrations automatically enable these extensions:
| Extension | Migration | Purpose |
|-----------|-----------|---------|
| `uuid-ossp` | 001 | UUID generation |
| `vector` (pgvector) | 033 | Created by an early migration; no current code path stores embeddings, the extension only needs to exist for the migration to apply |
| `btree_gist` | 042 | Fiscal period overlap prevention |
| `pg_cron` | 048 | In-database scheduled jobs |
These are all available on Supabase hosted. `pg_cron` requires a paid plan: if you are on the free tier, migration 048 will fail. You can safely skip it; the cron sidecar container handles the equivalent job via HTTP instead.
## 4. Configure Environment
**Option A: Setup script (recommended):**
```bash
git clone https://github.com/erp-mafia/accounted.git
cd accounted
./setup.sh
```
The script checks prerequisites, prompts for your Supabase credentials, auto-generates `CRON_SECRET`, and writes everything to `.env`.
**Option B: Manual:**
```bash
git clone https://github.com/erp-mafia/accounted.git
cd accounted
cp .env.docker.example .env
```
Edit `.env` with your values:
```bash
# ─── Required ───
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key
NEXT_PUBLIC_APP_URL=https://your-domain.com
CRON_SECRET=<generate with: openssl rand -hex 32>
```
`NEXT_PUBLIC_APP_URL` must match your public-facing URL. It is used in invoice reminder emails, calendar feed links, and PSD2 callbacks. If left as a placeholder, links will be broken.
Automatic logout is opt-in per user: sessions only expire for users who have
enabled "Automatic logout" in Settings > Security (stored on
`user_preferences.auto_logout`, default off). For opted-in users, hosted
Accounted defaults to a 30-minute idle limit, a 12-hour absolute limit, and a
warning 2 minutes before expiry. Self-hosted installations leave both limits
disabled unless you opt in (values are milliseconds):
```bash
NEXT_PUBLIC_SESSION_IDLE_TIMEOUT_MS=1800000
NEXT_PUBLIC_SESSION_ABSOLUTE_TIMEOUT_MS=43200000
NEXT_PUBLIC_SESSION_WARNING_MS=120000
```
Set either timeout to `0` to disable only that limit. To enforce the timeouts
for every user regardless of their per-user preference (the pre-2026-08
behavior), also set:
```bash
NEXT_PUBLIC_SESSION_TIMEOUT_FORCE_ALL=true
```
Timeout state is signed
with `SUPABASE_SERVICE_ROLE_KEY` by default; set `SESSION_TIMEOUT_SECRET` to a
separate random value if you want to rotate it independently. Changing either
signing secret invalidates existing timeout cookies and requires users to sign
in again.
## 5. Start the Application
```bash
docker compose up -d
```
This starts two containers:
| Container | Purpose |
|-----------|---------|
| `app` | Next.js application (`ghcr.io/erp-mafia/gnubok:latest`) |
| `cron` | Scheduled jobs via [supercronic](https://github.com/aptible/supercronic) |
The cron container waits for the app health check to pass before starting.
Verify the deployment:
```bash
curl http://localhost:3000/api/health
# {"status":"healthy","timestamp":"...","version":"1.0.0"}
# `version` is the build commit SHA prefix when VERCEL_GIT_COMMIT_SHA or
# NEXT_PUBLIC_BUILD_ID was set at build time, otherwise "1.0.0".
```
> **Note:** The health check queries the database, so migrations must be applied before it returns healthy.
### Building from Source
To build the Docker image locally instead of pulling from GHCR:
```bash
docker compose -f docker-compose.yml -f docker-compose.build.yml up --build
```
The locally-built image runs **unprivileged** (`USER nextjs`): the entrypoint
populates the `.next`/`public` tmpfs mounts and substitutes the `NEXT_PUBLIC_*`
placeholders as the `nextjs` user, so the container needs no Linux capabilities
and runs as-is under the hardened compose defaults (`cap_drop: ALL`,
`read_only: true`).
### Custom Port
Set `PORT` in your `.env` or environment to change the host port (the container always listens on 3000 internally):
```bash
PORT=8080 docker compose up -d
```
## 6. First Login
1. Open your deployment URL in a browser.
2. Click "Skapa konto" (Create account) and register with email + password.
3. Check your email and click the confirmation link.
4. Complete the 5-step onboarding wizard:
- **Step 1**: Choose entity type (enskild firma or aktiebolag)
- **Step 2**: Company name and org number
- **Step 3**: Fiscal year, VAT registration, accounting method
- **Step 4**: Preliminary tax amount (optional, skip if unsure)
- **Step 5**: Bank details for invoices (optional)
There is no admin account: any email address can sign up (unless you turn public signup off, see the `AUTH_SIGNUPS_DISABLED` note under [Email](#email-invoice-sending-invitations-and-reminders)). You can also use the magic link option on the login page if preferred.
To bring in more users, invite them from **Settings > Company > Members** (company-scoped) or **Settings > Team** (consultant teams). Invitations work without a mail provider: the accept link is returned to the inviter right after the invite is created (shown under the pending list with a copy button), so it can be shared over any channel. Configuring Resend only adds automatic delivery. The link is shown once and cannot be re-sent for company invites: revoke the invitation and invite again to get a fresh link.
## Scheduled Jobs
The cron sidecar runs the schedule in [`docker/crontab.self-hosted`](../docker/crontab.self-hosted). That file is generated from the `crons` array in `vercel.json` (the single source of truth, shared with the hosted service) by `npm run crontabs:generate`, and a test fails CI if it drifts, so this guide does not repeat the table: open the file for the exact jobs and times. They fall into these groups:
- **Every minute / every few minutes**: webhook dispatch, WhatsApp and invoice-inbox sweeps (crash recovery for staged uploads).
- **Hourly**: recurring invoices, cloud-backup auto-sync, idempotency-key cleanup.
- **Nightly (UTC)**: deadline statuses, tax deadlines, document-archive SHA-256 verification, event and pending-operation cleanup, sandbox cleanup, booking-template sync, bank sync, skattekonto sync, accrual posting, receipt hunt, WhatsApp retention.
- **Skatteverket receipts**: AGI every 15 minutes, VAT every two hours.
Extension endpoints are listed unconditionally: one whose extension is not enabled answers a cheap no-op, so enabling it later needs no crontab change.
All cron endpoints are authenticated with `Authorization: Bearer <CRON_SECRET>`. The cron container calls the app over the internal Docker network (`http://app:3000`), so these endpoints are not exposed publicly.
Additionally, migration 048 schedules a `pg_cron` job inside the database that marks overdue supplier invoices daily at 06:00 UTC.
## Optional Features
### AI Features
All AI features (automatic interpretation of uploaded receipts and invoices via the `document-extraction` and `invoice-inbox` extensions, and the in-app AI assistant) run on one configured backend. There are three ways to provide one; pick one. Note that the agent surface most integrations use, the MCP server, needs no AI backend at all: it is your own agent (Claude, Codex, a local model) talking to the ledger, so a deployment without any of the credentials below is still fully usable that way.
The stock self-hosted image includes both extraction extensions, so these credentials cover emailed invoices and documents uploaded in the app.
**Option 1: the direct Anthropic API.** The simplest option for self-hosting, since it needs nothing but a key from [console.anthropic.com](https://console.anthropic.com). Billing is your own, separate from any Claude subscription.
```bash
ANTHROPIC_API_KEY=sk-ant-...
```
**Option 2: AWS Bedrock.** Requires an AWS account with Bedrock model access to Claude. This is what the hosted service runs, because it keeps inference inside the EU (the `eu.` cross-region inference profile; `AWS_REGION` is the API endpoint, not a pin to one region): choose it if you need the AI calls to stay in the EU, which the direct API does not guarantee.
```bash
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_REGION=eu-north-1 # default
```
Set both static AWS keys explicitly. The AI assistant's client can fall back to the standard AWS credential provider chain (instance profile, IRSA) when they are absent, but document extraction requires `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` and silently returns empty results without them.
**Option 3: any OpenAI-compatible endpoint.** Any server that implements the chat-completions API: a Swedish inference provider for a fully sovereign deployment, or a **local model** on the same machine (llama.cpp's `server`, Ollama's `/v1`, LM Studio, vLLM). Document extraction (receipts, invoices, HTML mail invoices), the assistant's question-and-answer (on both `/chat` and the docked assistant sheet, via `/api/agent/ask`), and one-tap transaction categorization run here on any provider. A set of specialized conversational flows still needs an Anthropic-family backend; see **What runs on any model** below.
```bash
AI_BASE_URL=http://localhost:11434/v1 # the endpoint's OpenAI-compatible base URL (here: a local Ollama)
AI_MODEL=qwen3.8 # a model id is required: there is no default for an arbitrary endpoint
# AI_API_KEY=... # OPTIONAL: only when the endpoint needs auth. A local server usually
# # has none, so leave it unset; a hosted provider gives you a key.
# AI_EXTRACTION_MODEL=... # optional: a vision model for document reading, if AI_MODEL is not one
```
Three things about such endpoints are declared rather than probed, because the app cannot tell from the outside:
- `AI_VISION=false` says the configured model cannot read images. Images and PDFs are then skipped honestly (the inbox row lands with the empty skeleton and the "AI-tolkning kördes inte" hint) instead of failing with a 400 on every upload; HTML mail invoices still extract as text on any model.
- `AI_PDF_MODE` defaults to `rasterize` here: most such endpoints have no PDF input, so the first `AI_PDF_MAX_PAGES` pages (default 4) are rendered to images with poppler's `pdftoppm`, which the self-host image installs (`apk add poppler-utils`, the only system package beyond the base image; page images are written to `/tmp`, a tmpfs in `docker-compose.yml`). If the binary is missing, PDFs are skipped with `pdf_rasterizer_missing` rather than failing; `AI_PDF_RASTERIZER_BIN` points at a non-standard install. A provider that accepts the OpenAI `file` content part can use `AI_PDF_MODE=native`.
- `AI_STRICT_JSON=true` asks for `response_format: json_schema` on providers that enforce it. The default (JSON answered in prose, then parsed and validated) works on every model and is what hosted runs.
#### What runs on any model
Most AI surfaces run on any of the three backends above, an OpenAI-compatible or local model included:
- **Document extraction**: receipts, invoices, and HTML mail invoices.
- **The AI assistant's question-and-answer**, on both `/chat` and the docked assistant sheet (`/api/agent/ask`), including its read-only ledger tools.
- **One-tap transaction categorization** (`/api/agent/categorize`): the deterministic-candidates then model-select cascade shown on the transactions page.
A few **specialized conversational flows** still run on the older streaming runtime (`/api/agent/invoke`), which requires an Anthropic-family model (AWS Bedrock or the direct Anthropic API). On an OpenAI-compatible or local backend these specific actions return `503`; everything above keeps working. They are:
- **Operation-staging flows** (they draft a change for you to approve): the invoice-inbox "Fraga assistenten" categorize, bulk-book, invoice draft, supplier-invoice review, and verifikat draft.
- **Context-bound assistant helpers**: VAT review, KPI explanation, settings help, the bokslut step-through, and onboarding.
Migrating these to the single-call surface, so a fully local deployment covers them too, is tracked in [#1800](https://github.com/erp-mafia/accounted/issues/1800).
Optional model overrides, in any setup:
```bash
AI_MODEL=... # default model for every tier (OpenAI-compatible: required)
AI_EXTRACTION_MODEL=... # document extraction model
AI_HEAVY_MODEL=... # assistant model, heavy intents
AI_ASSISTANT_MODEL=... # assistant model, standard intents
AI_EXTRACTION_MAX_TOKENS=8192 # output cap for document extraction
AI_PROVIDER=bedrock|anthropic|openai-compatible # force the backend (see below)
```
The pre-existing names `BEDROCK_MODEL_ID`, `BEDROCK_OPUS_MODEL_ID`, `BEDROCK_SONNET_MODEL_ID` and `BEDROCK_MAX_TOKENS` keep working as the same overrides (extraction, heavy, standard, extraction cap) on every backend; the `AI_*` names take precedence when both are set. Claude deployments default every tier to `claude-sonnet-5`.
When several credential sets are present, Bedrock wins, then the direct Anthropic API, then the OpenAI-compatible endpoint, so that adding a key for an experiment cannot silently move production inference out of the EU. Set `AI_PROVIDER` to say which you mean. A model id written without a provider prefix is adapted to whichever backend is active; an id that already carries one (`eu.anthropic.…`) is used as-is.
Without working credentials the rest of the app runs normally: uploads are stored but not auto-interpreted (the upload UI sees that immediately rather than waiting for a timeout), and the AI assistant answers `503 ai_unconfigured`.
#### Verifying the setup
`scripts/smoke-ai-provider.ts` is the "is AI wired up?" command. It works the same on every backend because it only talks to the app's AI service: it prints the resolved provider, the model per tier, the PDF mode (and whether `pdftoppm` is installed when PDFs are rasterized), then sends real traffic: one small text generation per tier model, one schema-shaped answer, and, when you pass a file, the exact document-extraction path an uploaded receipt takes. It exits non-zero if any step fails, so it works as a post-deploy check. Run it from a checkout next to the env file your deployment uses (`.env.local`, then `.env` are read):
```bash
npx tsx scripts/smoke-ai-provider.ts # provider, models, text + structured calls
npx tsx scripts/smoke-ai-provider.ts ./receipt.pdf # also runs document extraction end to end
```
A skipped extraction is reported as a failure with the reason: a text-only model (`ai_no_vision`, pick a vision model for `AI_EXTRACTION_MODEL`), a missing rasterizer (`pdf_rasterizer_missing`, install poppler-utils or set `AI_PDF_MODE=native`), or no credentials/model at all.
On the Anthropic family, `scripts/smoke-ai.ts` additionally probes the in-app assistant's full parameter set (a streamed turn with a tool, adaptive thinking, effort and the prompt cache), which the assistant still sends through the Anthropic SDK directly:
```bash
npx tsx scripts/smoke-ai.ts # credentials, models, chat loop
# Note: this check only detects static credentials (ANTHROPIC_API_KEY or
# AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY). Bedrock deployments using an
# instance profile or IRSA won't be picked up automatically: set
# AI_PROVIDER=bedrock to run the probes against the AWS credential chain
# anyway.
npx tsx scripts/smoke-ai.ts ./receipt.pdf # also runs document extraction
```
> **Note:** `OPENAI_API_KEY` from earlier versions is not read by any code path. To use OpenAI itself, point Option 3 at `https://api.openai.com/v1`; the app has no provider-specific OpenAI integration, only the OpenAI-compatible one. Background: [#1406](https://github.com/erp-mafia/accounted/issues/1406).
### Email (Invoice Sending, Invitations and Reminders)
Outbound mail (invoices, reminders, payslips) goes through one of two providers. Auth/account mail is sent by Supabase Auth and is not affected.
**Option 1: Resend** (what hosted runs):
```bash
RESEND_API_KEY=re_...
RESEND_FROM_EMAIL=noreply@your-domain.com
```
Requires a [Resend](https://resend.com) account with a verified sender domain.
**Option 2: your own SMTP relay** (a Swedish mail provider, a Microsoft 365 / Google Workspace relay, Postfix on the host):
```bash
EMAIL_PROVIDER=smtp
SMTP_HOST=smtp.example.se
SMTP_PORT=587 # default 587; 465 with SMTP_SECURE=true
SMTP_SECURE=false # true = implicit TLS, false = STARTTLS required (set SMTP_REQUIRE_TLS=false only for a plaintext LAN relay)
SMTP_USER=... # optional for an internal relay
SMTP_PASS=...
SMTP_FROM_EMAIL=faktura@your-domain.se
# SMTP_REQUIRE_TLS=false # only for a plaintext relay on a trusted LAN: without it a relay that cannot STARTTLS fails the send instead of leaking credentials and invoice PDFs in cleartext
# SMTP_TLS_REJECT_UNAUTHORIZED=false # only for a LAN relay with a self-signed certificate
```
`EMAIL_PROVIDER` is optional: with a `RESEND_API_KEY` present Resend is used, otherwise `SMTP_HOST` selects SMTP, so adding SMTP variables next to an existing Resend key never moves mail by accident. Set it explicitly when both are configured. The From header is built identically on both providers (the company or brand name as display name, the platform address from `RESEND_FROM_EMAIL` or `SMTP_FROM_EMAIL` unless the company has a verified sending domain); the delivery-status webhook is Resend-only.
Without either, invoices can still be generated as PDFs but cannot be emailed.
**Invitations do not require Resend.** When no mail provider is configured, the invite is still created and the accept link is returned to the inviter in the app (a copy button under the pending invitations list, plus a warn-level log record whose msg is `email service not configured: invite email skipped`; the Docker image logs JSON, so grep for the message text, not a `WARN` prefix; the token is never logged). Share the link manually; it is valid until the invitation expires. A mail provider (Resend, or your own relay with `EMAIL_PROVIDER=smtp`, both above) is only needed if you want the invitation mailed automatically. There is no re-send for company invitations: revoke and invite again for a new link.
Note the two separate mail paths: this variable drives the app's own mail (invoices, invitations, reminders); account mail from GoTrue (signup confirmation, password reset, and the account-provisioning invite when `AUTH_SIGNUPS_DISABLED=true`) goes through the Supabase **Authentication > SMTP Settings** described in [Configure Authentication](#2-configure-supabase-auth) and [Troubleshooting](#troubleshooting).
```bash
AUTH_SIGNUPS_DISABLED=true
```
Set this when you have turned public signup off in GoTrue (`disable_signup`). The invite route then provisions the invitee's account through the auth admin API before writing the invitation, and GoTrue mails its own set-password link via the Supabase SMTP settings; the in-app accept link is still returned to the inviter.
### Connector subscription (self-hosted instances)
Everything a self-hosted instance runs itself is free (AGPL). Five capabilities depend on services only Accounted operates and are therefore gated on a self-host: bank sync (our PSD2/AISP credentials), Skatteverket API submission and skattekonto sync (our API client registration), Peppol e-invoicing (our contracted access point), company lookup (TIC) and migration from Fortnox/Visma/Bokio/Björn Lundén (the migration gateway). A **connector key** unlocks them for every company on the instance; it is priced per active company at parity with hosted and will be issued manually by Accounted (self-serve later); no keys are issued until the instance-side client wiring described below is complete.
```bash
GNUBOK_CONNECTOR_KEY=gnubok_ck_... # issued by Accounted, shown once
# GNUBOK_CONNECT_URL=https://connect.accounted.se # default: the connector service
```
The cron sidecar calls `/api/connector/sync/cron` hourly (it is listed in `docker/crontab.self-hosted` only): the instance reports its active company count, the hosted service answers with the key's status and scopes, and the instance writes `capability_grants` rows with `source = 'connector'` that expire after **72 hours** (or three days past the paid period, whichever is sooner). Those rows are the offline cache: a hosted outage shorter than that changes nothing, a revoked or lapsed key freezes the connector capabilities within days, and nothing in the instance phones home for permission to run the bookkeeping. An instance without a key answers `not_configured` and stays unaffected. To run the sync once by hand after pasting the key:
```bash
curl -sf -H "Authorization: Bearer $CRON_SECRET" http://localhost:3000/api/connector/sync/cron
```
The **bank** and **Skatteverket** connector proxies are live on the connector service (`connect.accounted.se/api/connect/bank/*` and `/api/connect/skv/*`): with `bank_sync` / `skatteverket` in your key's scopes, the instance connects a bank through Arcim's PSD2 credentials and files VAT/AGI + syncs skattekonto through Arcim's registered Skatteverket client, while all tokens (the bank session id, the SKV BankID tokens) stay encrypted in the instance's own database. Company lookup and migration through the connector ship in following releases. The instance-side client wiring is merged for both upstreams: in connector mode (key set, no own credentials for that upstream) bank sync and Skatteverket carry traffic through the hosted proxy. Keys are not yet issued: Accounted issues none until a staging end-to-end run confirms the full flow, so a key never unlocks a granted capability whose client cannot carry traffic. On the instance, Skatteverket still needs `SKATTEVERKET_ENABLED=true` and `SKATTEVERKET_TOKEN_ENCRYPTION_KEY` (the tokens are stored there, so the encryption key is the operator's).
**Peppol** through the connector works the same way once your key carries the `peppol` scope: leave every `QVALIA_*` variable and `PEPPOL_TRANSPORT_PROVIDER` unset, and the instance sends and receives e-invoices through Arcim's contracted access point (`connect.accounted.se/api/connect/peppol/*`). The hosted side enforces one receiving registration per company (`peppol_connections_per_company` on the key), a shared cap on registrations at the access point, and ownership: an instance can only poll status, fetch evidence and receive documents for registrations and submissions made through its own key. Delivery status arrives by polling (`/api/peppol/outbound/status/cron`), not by webhook. Which participant identifiers (organisation numbers, GLNs) a key may register and send as is recorded on the key when Arcim issues it; the licensee's own organisation number is always allowed, anything else is refused with `CONNECTOR_PEPPOL_PARTICIPANT_NOT_ALLOWED`. Setting `QVALIA_API_KEY` or `QVALIA_PARTNER_REG_NO` switches Peppol out of connector mode onto your own access-point account. Brokered Peppol registers your companies under Arcim's access point, so the `peppol` scope is issued only where Arcim's provider terms allow it.
With this release the self-host image also ships the `enable-banking` and `skatteverket` extensions in its preset: without a key (or own credentials) they show the connector upsell instead of being absent, and `GET /api/connector/status` shows the operator how each upstream would be routed.
#### Own credentials (no connector key)
Both gated upstreams also run on credentials you register yourself. An instance with its own credentials for an upstream provides that service itself and is never connector-gated for it, with or without a key: the app routes that upstream directly and ignores the connector for it.
**Enable Banking (bank sync).** Create an application in the Enable Banking control panel. Production access in restricted mode covers your own company's accounts and needs no AISP licence of your own. It does not cover other parties' accounts: an instance that hosts client companies (a byrå, a consultant team) is connecting accounts it does not own, which is licensed account-information service under PSD2 and lag (2010:751) om betaltjänster. For that instance, use the connector key (Arcim's AISP registration) or register as an AISP yourself. Register the redirect URL `${NEXT_PUBLIC_APP_URL}/api/extensions/enable-banking/callback` on the application, then set:
```bash
ENABLE_BANKING_APP_ID=... # application id from the control panel
ENABLE_BANKING_PRIVATE_KEY=... # the application's private key as base64-encoded PEM (a bare base64 DER body also works; a raw PEM does not)
# ENABLE_BANKING_API_URL=https://api.enablebanking.com # default; https://api.tilisy.com is the sandbox
# ENABLE_BANKING_PSU_TYPE=business # default; enskild firma companies are sent as personal automatically
```
The `_PRODUCTION` variants (`ENABLE_BANKING_APP_ID_PRODUCTION`, `ENABLE_BANKING_PRIVATE_KEY_PRODUCTION`, `ENABLE_BANKING_API_URL_PRODUCTION`) win over the plain names when both are set. Setting any one of the four id/key variables switches the bank upstream out of connector mode, so always set the id and the key as a pair: a lone `ENABLE_BANKING_APP_ID` leaves you with neither the connector nor a working own client.
**Skatteverket (VAT and AGI submission, skattekonto sync).** Apply for API access in Skatteverket's developer portal (Utvecklarportalen): a separate OAuth2 client and API gateway credentials, one integration agreement per API (momsdeklaration, the two arbetsgivardeklaration APIs, skattekonto), and Skatteverket's approval test before production access is granted. Request the scopes the app sends on every authorization: `momsdeklaration inkforetag skahmst skattekonto ska agd agdredovisningperiod` (the two AGI scopes are both required: `agd` for inlämning and `agdredovisningperiod` for kvittenser; a token missing the second one files fine and then fails on the receipt). Register the redirect URI `${NEXT_PUBLIC_APP_URL}/api/extensions/ext/skatteverket/callback` on the client, then set:
```bash
SKATTEVERKET_ENABLED=true
SKATTEVERKET_OAUTH2_CLIENT_ID=...
SKATTEVERKET_OAUTH2_CLIENT_SECRET=...
SKATTEVERKET_APIGW_CLIENT_ID=...
SKATTEVERKET_APIGW_CLIENT_SECRET=...
SKATTEVERKET_TOKEN_ENCRYPTION_KEY=... # openssl rand -base64 32; encrypts the BankID tokens at rest (any string, hashed to the AES key)
SKATTEVERKET_ENV=production # drives payload limits; defaults to test
SKATTEVERKET_OAUTH_BASE_URL=https://peroauth2.skatteverket.se/oauth2/v1/per
SKATTEVERKET_API_BASE_URL=https://api.skatteverket.se/momsdeklaration/v1
SKATTEVERKET_AGD_INLAMNING_API_BASE_URL=https://api.skatteverket.se/arbetsgivardeklaration/inlamning/v1
SKATTEVERKET_AGD_PERIOD_API_BASE_URL=https://api.skatteverket.se/arbetsgivardeklaration/hanteraredovisningsperiod/v1
SKATTEVERKET_SKATTEKONTO_API_BASE_URL=https://api.skatteverket.se/beskattning/skattekonto/v2
```
Set all five base URLs: every default points at Skatteverket's test environment, which only accepts a test BankID, so a production client with a missing URL fails at login. `SKATTEVERKET_DISABLED=true` is the emergency kill switch: every Skatteverket API call fails closed until you remove it (the BankID login itself is not blocked, only what follows it). There is no dual-key rotation for the token encryption key: changing it makes every stored token undecryptable, and every user reconnects with BankID. The `SKATTEVERKET_SYSTEM_*` variables and `SKATTEVERKET_OMBUD_ORG_NUMBER` belong to Accounted's hosted ombud certificate and stay unset on a self-host. Setting either `SKATTEVERKET_OAUTH2_CLIENT_ID` or `SKATTEVERKET_APIGW_CLIENT_ID` switches the Skatteverket upstream out of connector mode.
**Bank sync as a connector operation.** In connector mode the bank paging, the booked-only filter and the normalization run on the hosted service (`POST /api/connect/bank/sync`); the instance sends the session id it holds and receives the rows plus the raw provider pages it archives, and keeps computing its own stored transaction keys, so nothing about dedup changes. `CONNECT_BANK_CANARY_COMPANIES` (comma-separated company ids) routes only those companies through the connector while own credentials remain set, which is how an installation moves a few companies at a time. `CONNECT_SKV_CANARY_COMPANIES` does the same for Skatteverket: the listed companies' user-token data calls (skattekonto, moms, AGI) go through the connector's data proxy while the installation's own OAuth client still refreshes the tokens.
**Connector mode, for comparison.** With a key you set `GNUBOK_CONNECTOR_KEY` and, if you are not on the default hosted origin, `GNUBOK_CONNECT_URL` (https only; plain http is accepted for loopback only, and an invalid URL disables the connector with a warning in the log). Skatteverket in connector mode still needs `SKATTEVERKET_ENABLED=true` and `SKATTEVERKET_TOKEN_ENCRYPTION_KEY`: the BankID tokens are stored in your database, so the encryption key stays operator-side. Leave every other Enable Banking and Skatteverket variable unset.
### Push Notifications
```bash
NEXT_PUBLIC_VAPID_PUBLIC_KEY=...
VAPID_PRIVATE_KEY=...
VAPID_SUBJECT=mailto:you@example.com
```
Generate VAPID keys with `npx web-push generate-vapid-keys`. Push notifications require HTTPS.
### Error Tracking
There is no Sentry integration. `SENTRY_DSN` and `NEXT_PUBLIC_SENTRY_DSN` are not read by the app: setting them changes nothing. Error-level events go to the container logs (structured JSON on stdout/stderr); `lib/observability/sink.ts` is a provider-agnostic seam that stays a no-op until an adapter is registered with `registerObservabilitySink()`, so a self-hosted build carries no third-party error-tracking dependency. If you want alerting, ship the container logs to your log system and alert there. See [docs/security/logging-and-observability.md](security/logging-and-observability.md).
## Storage Buckets
Migration 024 automatically creates the `documents` storage bucket (private, 50 MB limit, WORM, no update/delete). No other buckets need to be created manually.
## Updating
Pull the latest image and restart:
```bash
docker compose pull
docker compose up -d
```
If a new release includes database migrations, apply them before restarting:
```bash
supabase db push
```
Check the [release notes](https://github.com/erp-mafia/accounted/releases) for migration instructions.
## Architecture Overview
```
┌─────────────────────┐ ┌──────────────────┐
│ Docker: app │ │ Docker: cron │
│ (Next.js) │◄────│ (supercronic) │
│ Port 3000 │ │ Bearer auth │
└────────┬────────────┘ └──────────────────┘
│
│ HTTPS
▼
┌─────────────────────┐
│ Supabase │
│ - PostgreSQL + RLS │
│ - Auth (email+pw) │
│ - Storage (docs) │
└─────────────────────┘
```
The Next.js app is stateless: all data lives in Supabase. The Docker entrypoint injects your `NEXT_PUBLIC_*` environment variables into the pre-built JS bundles at container startup, so a single image works with any Supabase project.
## Fully Self-Hosted (No Supabase Cloud)
The setup above relies on a Supabase project at supabase.com. If you also want to host the database, auth, and storage yourself (to keep all data on-premises, avoid the SaaS dependency, or run air-gapped) you can pair Accounted with [Supabase's official Docker self-hosting stack](https://supabase.com/docs/guides/self-hosting/docker) instead. For the fully Swedish variant of this (Swedish hosting, Swedish object storage with retention locks for the 7-year archive, AI on Swedish GPUs, backup/restore runbook) see [SOVEREIGN.md](SOVEREIGN.md); the mechanics below apply there too.
This is a more involved path. You take responsibility for backups, TLS certificates, image upgrades, and Postgres operations. It is intended for operators already running Docker services who are comfortable with PostgreSQL.
### Architecture
```mermaid
flowchart LR
user((User))
proxy["Reverse proxy + TLS<br/>(Caddy / Traefik / nginx)"]
user -- HTTPS --> proxy
subgraph dnet["shared Docker network"]
subgraph app_stack["Accounted stack (this repo)"]
app["app<br/>Next.js · :3000"]
cron["cron<br/>supercronic"]
cron -. Bearer CRON_SECRET .-> app
end
subgraph supabase_stack["Supabase self-host stack"]
kong["kong<br/>API gateway · :8000"]
studio["studio<br/>dashboard"]
db[("postgres<br/>+ pg_cron")]
auth["gotrue"]
rest["postgrest"]
rt["realtime"]
storage["storage-api<br/>(+ imgproxy)"]
kong --- auth & rest & rt & storage & studio
auth & rest & rt & storage --- db
end
app -- "@supabase/supabase-js" --> kong
end
proxy -- app.example.com --> app
proxy -- supabase.example.com --> kong
proxy -- studio.example.com --> studio
```
### Setup outline
1. **Bring up Supabase** following [supabase.com/docs/guides/self-hosting/docker](https://supabase.com/docs/guides/self-hosting/docker). Generate your own `JWT_SECRET`, `ANON_KEY`, and `SERVICE_ROLE_KEY` (Supabase ships `sh utils/generate-keys.sh`). Pick a hostname for the API gateway (e.g. `supabase.example.com`) and point `SUPABASE_PUBLIC_URL` at it and `API_EXTERNAL_URL` at it **including the `/auth/v1` path** (upstream docker 0.7.0, July 2026, changed this). The API gateway depends on the upstream release you check out: `self-hosted/v0.7.x` runs Kong by default and offers Envoy through the `docker-compose.envoy.yml` overlay; `self-hosted/v0.8.0` and later run Envoy by default and keep Kong available through `docker-compose.kong.yml`. The diagram above says `kong`; the role is the same, the container name follows your release and overlays.
2. **Apply the Accounted migrations** directly via `psql`: the Supabase CLI (`db push`) assumes a cloud project, so run the SQL files against the self-hosted database container:
```bash
# From the repo root, stream each migration straight into the supabase-db
# container: glob order is already sorted, and nothing is left behind on the
# host or in the container.
for f in supabase/migrations/*.sql; do
echo "Applying $f..."
docker exec -i supabase-db psql -v ON_ERROR_STOP=1 -U postgres -d postgres < "$f" || exit 1
done
```
3. **Configure `.env`** with your self-hosted endpoints (extract the keys from your Supabase `.env`):
```bash
NEXT_PUBLIC_SUPABASE_URL=https://supabase.example.com
NEXT_PUBLIC_SUPABASE_ANON_KEY=<ANON_KEY from supabase .env>
SUPABASE_SERVICE_ROLE_KEY=<SERVICE_ROLE_KEY from supabase .env>
NEXT_PUBLIC_APP_URL=https://app.example.com
CRON_SECRET=<openssl rand -hex 32>
NEXT_PUBLIC_SELF_HOSTED=true
```
4. **Allowlist the callback URLs** in GoTrue's redirect list (the Supabase stack's `.env`), then recreate the auth container so it picks up the change:
```bash
ADDITIONAL_REDIRECT_URLS=https://app.example.com/auth/callback,https://app.example.com/api/auth/callback
```
```bash
cd <your-supabase-dir> && docker compose up -d auth
```
5. **Reverse proxy** in front of both hosts. The app container and the Supabase `kong` container must share an external Docker network so the proxy can route to them by name.
### Synology DSM and Xpenology notes
Run Accounted and Supabase as two separate Container Manager Projects with two
separate project directories. Accounted owns the Compose files in this
repository. Supabase owns its database, Auth, Realtime, Storage, and pooler
configuration. Choose one upstream release tag or full commit and copy the
complete `docker/` directory from that immutable revision, following the
[official Supabase Docker guide](https://supabase.com/docs/guides/self-hosting/docker).
Do not copy individual snippets into Accounted's Compose file or mix files from
different upstream revisions.
For the **Accounted project**, follow the
[Accounted Container Manager file layout](DOCKER.md#synology-dsm-and-xpenology).
For the **Supabase project**:
1. Copy the entire upstream `supabase/docker/` directory into the project
directory. Do not upload only its `docker-compose.yml`: it bind-mounts SQL,
gateway, function, pooler, and Storage files from the accompanying
`volumes/` tree.
2. Create the two runtime directories that upstream deliberately excludes from
Git before the first deployment. File Station is fine, or from the Supabase
project directory use:
```bash
mkdir -p volumes/db/data volumes/storage
```
Container Manager must be able to write to both directories. Use the
narrowest NAS ACL that works for the container runtime; do not make the
whole shared folder world-writable.
3. Supavisor publishes two host ports. Before starting the project, make sure
both `POSTGRES_PORT` and `POOLER_PROXY_PORT_TRANSACTION` in the **Supabase**
`.env` are unused on the NAS. If the defaults conflict, examples are
`POSTGRES_PORT=5433` for session mode and
`POOLER_PROXY_PORT_TRANSACTION=6544` for transaction mode. Changing only
`POSTGRES_PORT` does not resolve a conflict on the transaction port.
Accounted's `PORT` only changes the web app port and cannot resolve either
database conflict. Do not expose the Supabase `db` container directly just
to solve a conflict: the official stack exposes PostgreSQL through
Supavisor.
Supabase's default Supavisor port mappings listen on every host interface.
Accounted does not need either database port over the network, so on a
shared NAS bind both mappings to loopback in the version-matched Supabase
Compose file:
```yaml
services:
supavisor:
ports:
- "127.0.0.1:${POSTGRES_PORT}:5432"
- "127.0.0.1:${POOLER_PROXY_PORT_TRANSACTION}:6543"
```
If another trusted machine must connect, bind to a specific private NAS
address and restrict both ports to trusted source addresses in the DSM
firewall. Never forward either database port to the public internet.
4. The default Accounted integration uses Supabase's legacy `ANON_KEY` and
`SERVICE_ROLE_KEY`, so asymmetric keys and `JWT_JWKS` are optional. Leave
the upstream JWKS lines commented when using legacy-only mode. If you enable
Supabase's new asymmetric keys, generate them with the upstream
`utils/add-new-auth-keys.sh` script and follow the
[official authentication-key guide](https://supabase.com/docs/guides/self-hosting/self-hosted-auth-keys).
Some older Compose parsers reject the inline JSON fallback in Supabase's
optional Realtime setting:
```yaml
API_JWT_JWKS: ${JWT_JWKS:-{"keys":[]}}
```
After `JWT_JWKS` has been generated and saved in the Supabase `.env`, use the
direct substitution documented by Supabase for limited Compose parsers:
```yaml
# Supabase PostgREST
PGRST_JWT_SECRET: ${JWT_JWKS}
# Supabase Realtime
API_JWT_JWKS: ${JWT_JWKS}
# Supabase Storage
JWT_JWKS: ${JWT_JWKS}
```
Do not invent an empty or placeholder JWKS for a production deployment. Either
keep asymmetric authentication disabled or configure the generated value
consistently for every Supabase service that verifies tokens.
Accounted's base Compose file intentionally omits the optional `cpus` and
`healthcheck.start_interval` settings because older Container Manager Compose
builds can reject them. Operators who need a CPU cap can set one through DSM's
resource controls or a local Compose override. Existing deployments that
relied on the previous two-CPU cap must reapply it before restarting with the
new base file. Command-line deployments on Docker Compose 2.20.2 or newer and
Docker Engine 25.0 or newer can use the version-controlled
`docker-compose.resources.yml` overlay to restore both the cap and faster
startup health checks; older NAS container stacks should keep using the
portable base file alone.
### What you give up vs. cloud Supabase
- **Backups** are entirely your responsibility. The repo ships `scripts/self-host/backup.sh` / `restore.sh` (`pg_dump` custom format with ACLs kept, ACL manifest, storage tar, optional db-config volume, to any S3-compatible bucket with Object Lock; see [SOVEREIGN.md, section 5](SOVEREIGN.md#5-backup-and-restore-ship-it-do-not-improvise-it)); scheduling and monitoring them is still on you. As a portable, vendor-neutral *logical* backup on top of the raw dump, you can also export each fiscal period as a standard **SIE4** file via the API and archive it: any Swedish bookkeeping system can re-import it:
```bash
curl -fsS -H "Authorization: Bearer <reports:read API key>" \
"$NEXT_PUBLIC_APP_URL/api/v1/companies/<companyId>/reports/sie-export?period_id=<periodId>" \
-o "export_<periodId>.se"
```
- **Storage**: the included `storage-api` defaults to the local-filesystem backend. For production durability, use the `docker-compose.s3.yml` overlay and point it at S3 / MinIO.
- **SMTP**: no built-in mailer for auth mail. Either set `ENABLE_EMAIL_AUTOCONFIRM=true` for dev/staging, or wire `SMTP_*` env vars in the Supabase stack to a provider (Resend, Postmark, etc.), the self-hosted equivalent of the **Authentication > SMTP Settings** step in [Configure Authentication](#2-configure-supabase-auth) and [Troubleshooting](#troubleshooting). If you also disable public signup in GoTrue, set `AUTH_SIGNUPS_DISABLED=true` on the app so invites provision accounts through the admin API (see [Email](#email-invoice-sending-invitations-and-reminders)). Inviting users never depends on this: the accept link is always returned in-band to the inviter.
- **Upgrades**: you sync the `supabase/postgres` image yourself; your data lives in the DB volume, so a Postgres image bump needs no migration re-run. When you pull a newer Accounted release, apply only the **new** migration files added since your last deploy (the SQL is not idempotent, so re-running already-applied migrations will error). Track which migrations you've applied, e.g. with a checksum/version table.
### Notes
- **`pg_cron`** is included in the `supabase/postgres` image, so the `pg_cron` migration succeeds (unlike on the Supabase free tier, see the standard self-hosting flow above).
- **MFA**: as on the standard path, `NEXT_PUBLIC_SELF_HOSTED=true` disables enforcement; users may still enable TOTP voluntarily.
## Troubleshooting
**Health check fails with "unhealthy":**
Migrations have not been applied, or the Supabase credentials are wrong. Check that `NEXT_PUBLIC_SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` are correct and that migrations have been pushed.
**Confirmation email not arriving:**
Check the Supabase dashboard under **Authentication > Users** to verify the signup attempt was received. On the free tier, Supabase rate-limits emails to 4/hour. Configure custom SMTP under **Authentication > SMTP Settings** for production use.
**Auth callback redirects to error:**
Ensure `https://your-domain.com/auth/callback` is in the Supabase **Redirect URLs** allowlist and that **Site URL** matches your `NEXT_PUBLIC_APP_URL`.
**`pg_cron` migration fails:**
`pg_cron` requires a paid Supabase plan. On the free tier, you can safely comment out migration 048 or let it fail: the overdue supplier invoice check is non-critical and can be triggered manually.
**Container restarts in a loop:**
Check logs with `docker compose logs app`. The app requires all five core env vars (`NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`, `NEXT_PUBLIC_APP_URL`, `CRON_SECRET`) and will crash on startup if any are missing.
-104
View File
@@ -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.
-171
View File
@@ -1,171 +0,0 @@
# Kör Accounted helt svenskt: the sovereign self-host guide
This guide is for operators who want Accounted on Swedish (or strictly EU) infrastructure end to end: the ledger and its documents on servers in Sweden, AI on GPUs in Sweden, and source code you can audit. It builds on [SELF-HOSTING.md](SELF-HOSTING.md) (the general Docker guide) and its "Fully Self-Hosted" section; read those first, this guide only adds what the sovereign variant changes.
Two honest framings up front:
- **What you get is regulatory-risk elimination, not a legal verdict.** Hosted Accounted runs on Supabase and Vercel in AWS eu-north-1 (Stockholm) with AI inference on AWS Bedrock inside the EU; each of those providers operates under its own GDPR transfer mechanisms and contract terms (Data Privacy Framework participation and/or standard contractual clauses, documented in their DPAs), and whether that combination satisfies your policy is your assessment to make, not a conclusion this guide draws. What a self-host on Swedish providers removes is the *exposure*: no provider in the chain is subject to US extraterritorial law (the CLOUD Act), which is exactly the risk Sweden's national cloud policy of May 2026 names. That holds only for the chain you actually run: a sovereign deployment that keeps a US-dependent service such as Resend for outbound email has that one touchpoint left (section 6 lists them). The policy is principles for the public sector, not a mandate; it is still the document a procurement officer can point at.
- **Not every Swedish accounting vendor runs on US clouds**, so do not buy this guide as a claim that "everyone else does". Buy it because you want to be able to prove, provider by provider, where your books are.
Everything here is free to run under the AGPL. Services that only Accounted can operate (bank sync through our PSD2 licence, Skatteverket API submission, Peppol through our contracted access point, company lookup, provider migration) are hosted-only today; a connector subscription for self-hosted instances is **not yet available**: the infrastructure is merged, but no keys are issued until the instance-side client wiring is complete (see "What is and is not covered" below). Manual filing of VAT and AGI declarations (file generation, you upload at Skatteverket) is always free and works on a self-host.
## 1. What a sovereign deployment looks like
```mermaid
flowchart LR
user((User / byrå))
agent((Your own AI agent<br/>Claude, Codex, local model))
subgraph se["Swedish infrastructure (your account)"]
proxy["Reverse proxy + TLS"]
app["Accounted app + cron<br/>(this repo's Docker image)"]
supa["Self-hosted Supabase stack<br/>Postgres, Auth, Storage"]
s3[("S3-compatible bucket<br/>backups, Object Lock")]
ai["Swedish inference API<br/>(OpenAI-compatible)"]
end
user -- HTTPS --> proxy --> app --> supa
agent -- MCP (API key) --> app
app -- receipts, invoices --> ai
app -. nightly backup.sh .-> s3
```
Three things carry the sovereign claim, in order of how much they matter:
1. **Storage and database**: the self-hosted Supabase stack (Postgres + Auth + Storage) on a Swedish provider, with backups on Swedish S3 under retention locks. This is where the räkenskapsinformation lives.
2. **The agent surface needs no AI provider at all.** Most automation against Accounted runs through the MCP server (100+ tools, scoped API keys, staged approvals) driven by *your* agent: Claude Code, Codex, an OpenClaw setup, or a local model. The MCP server makes zero model calls itself. A deployment with no AI credentials configured is fully usable that way.
3. **In-app AI** (reading receipts and invoices, the assistant) is optional and bring-your-own: point `AI_BASE_URL` at a Swedish OpenAI-compatible endpoint. Document extraction, the assistant's question-and-answer (`/chat` and the docked assistant sheet, via `/api/agent/ask`) and one-tap transaction categorization run on any OpenAI-compatible backend; only the specialized Anthropic-only conversational flows (VAT review, KPI explanation, settings help, the bokslut step-through, the operation-staging inbox flows) answer `503` there, see [SELF-HOSTING.md, What runs on any model](SELF-HOSTING.md#what-runs-on-any-model). The MCP path needs no model at all.
## 2. What is and is not covered
| Free and local on a self-host (AGPL) | Hosted-only or backend-restricted today |
|---|---|
| Double-entry bookkeeping, invoicing, supplier invoices, reports, SIE import/export | Bank sync via Enable Banking (runs on Accounted's PSD2/AISP credentials) |
| VAT and AGI file generation for manual filing at Skatteverket | Skatteverket API submission and skattekonto sync (Accounted's API client registration) |
| Peppol BIS Billing 3 invoice generation (UBL download) | Peppol sending and receiving through the network (Accounted's contracted access point; an own Qvalia account also works) |
| Document archive with SHA-256 integrity and WORM bucket | Company lookup (TIC), migration from Fortnox/Visma/Bokio/Björn Lundén via the Arcim gateway |
| MCP server, API keys, staged approvals | Receipt hunt in a connected mailbox (Accounted's Google OAuth app), WhatsApp intake (Accounted's Meta credentials), Stripe billing |
| AI document extraction, assistant Q&A and one-tap categorization on a BYO endpoint; HTML mail invoices | Specialized conversational flows (VAT review, KPI explanation, settings help, bokslut helpers): Anthropic-family backend only (Bedrock or the direct API), not a BYO OpenAI-compatible endpoint ([#1800](https://github.com/erp-mafia/accounted/issues/1800)) |
| Push notifications (your VAPID keys), invoice email via your own SMTP relay (`EMAIL_PROVIDER=smtp`) or Resend (section 6) | |
The hosted-only rows (everything in the right column except the AI row, which is a backend restriction a connector key would not change) are what a connector subscription for self-hosted instances would unlock (priced at parity with hosted, per active company). The connector-key infrastructure is now merged: `GNUBOK_CONNECTOR_KEY` exists (see SELF-HOSTING.md), the hourly sync validates the key and writes the capability grants, and the bank/Skatteverket proxies are live server-side. The client wiring is merged too: with a key, both bank sync and Skatteverket carry traffic through the hosted proxy. Keys are **not yet issued**: Accounted issues none until a staging end-to-end run confirms the full flow, so a key never unlocks a granted capability whose client cannot carry traffic. When issuance opens it is manual, priced per active company at parity with hosted (see SELF-HOSTING.md). Without a key (or the instance's own upstream credentials) the settings screens show a connector-key note.
## 3. Choosing Swedish infrastructure
Facts below were checked on the providers' own pages in August 2026; verify before you sign, these change.
### Elastx (Stockholm; recommended primary)
- Swedish-owned (Elastx AB), data in Sweden, one region `se-sto` with three availability zones (`sto1`, `sto2`, `sto3`), each a separate data center up to 20 km apart. ISO/IEC 27001:2022, 27017, 27018, ISO 14001. Publishes a DPA with an annual audit right. Trust Center: https://elastx.se/en/trust-center
- What fits this stack: **Kubernetes CaaS** (managed, three-AZ nodes, managed ingress and cert-manager) or plain OpenStack VMs; **DBaaS PostgreSQL** 14 to 17 with optional HA and PITR (one-week default retention); S3-compatible object storage via OpenStack Swift (`swift.elastx.cloud`, SigV4 region must be `us-east-1`). Pricing and SLA: https://elastx.se/en/pricing, https://elastx.se/en/availability-sla
- Fit: the most "managed" Swedish option. Run the Accounted app + cron containers on CaaS or a VM, and either run the full Supabase stack yourself or point the stack's Postgres at DBaaS (self-hosted Supabase expects its own `supabase/postgres` image with extensions; using an external managed Postgres is possible but you take on the extension and role setup yourself, so the VM route with the stock stack is simpler).
### GleSYS (Falkenberg and Stockholm; budget VPS path)
- Own data centers in Falkenberg and Stockholm (plus Finland), ISO/IEC 27001:2022, 9001, 14001. EU jurisdiction; note the company is Swedish-headquartered but majority-owned by a Luxembourg infrastructure fund since 2023, which some buyers' sovereignty criteria distinguish from Swedish-owned. Public DPA (no processing outside EU/EEA). https://glesys.com/compliance-security, https://glesys.com/terms-policies/data-processing-agreement
- What fits: **KVM VPS** for the whole stack on one or two hosts, S3-compatible **Object storage** in Stockholm/Falkenberg, managed PostgreSQL (not needed if you run the stock Supabase stack). No managed Kubernetes. https://glesys.com/products/
- Fit: the cheapest credible path for a single company or a small byrå that is comfortable operating Docker Compose on a VPS.
### Safespring (Stockholm, Oslo; the backup bucket)
- Safespring Storage is Ceph-based, fully S3-compatible, **supports S3 Object Lock in both COMPLIANCE and GOVERNANCE modes plus legal hold and bucket default retention**, and versioning. Sites `sto1`, `sto2` (Stockholm) and `osl2` (Oslo); the cheaper Archive tier is `sto2` only. Endpoints `s3.sto1.safedc.net`, `s3.sto2.safedc.net`. No egress charges. https://docs.safespring.com/storage/object-locking/, https://www.safespring.com/en/price/
- Fit: the place for the backup sets from `scripts/self-host/backup.sh`. Object Lock must be enabled when the bucket is created, it cannot be switched on later. COMPLIANCE mode is the right setting for the yearly archive copy: nobody, including you, can delete it before the retention date, which is what makes it a credible BFL 7 kap archive.
### Swedish AI inference (for in-app extraction)
- **Berget AI** (default in this guide): OpenAI-compatible API at `https://api.berget.ai/v1`; public model list at `/v1/models`. Vision-capable models suitable for receipts as of August 2026 include `google/gemma-4-31B-it` and `mistralai/Mistral-Medium-3.5-128B`; text-only models such as `zai-org/GLM-5.2` work for the assistant's question-and-answer but cannot read images. Markets Swedish data centers; the DPA wording is "within the EEA", so ask for the specific site in writing if your policy needs "Sweden". **The SLA excludes serverless inference**: raise that in procurement. https://docs.berget.ai/models/overview, https://berget.ai/en/dpa, https://berget.ai/en/sla
- **evroc**: OpenAI-compatible "Think Models" API at `https://models.think.evroc.com/v1` with vision models (Gemma 4, Qwen3-VL, Kimi); EU residency, flagship Stockholm data center expected in H2 2026, so confirm where inference runs today. DPA with no sub-processors. https://docs.evroc.com/products/think/think.html, https://evroc.com/legal/data-processing-addendum/
Configure either through the standard variables (details in [SELF-HOSTING.md, AI Features, Option 3](SELF-HOSTING.md#ai-features)):
```bash
AI_BASE_URL=https://api.berget.ai/v1
AI_API_KEY=...
AI_MODEL=google/gemma-4-31B-it # vision-capable: reads receipts and PDFs
# AI_EXTRACTION_MODEL=... # if you want a different model for documents
# AI_VISION=false # only if you chose a text-only model
# AI_PDF_MODE=rasterize # default on these endpoints; the image ships pdftoppm
```
Then prove it end to end before telling users: `npx tsx scripts/smoke-ai-provider.ts ./some-receipt.pdf` from a checkout next to your `.env`.
### Coolify as the deployment tool
If you would rather not hand-write systemd units, [Coolify](https://coolify.io) (Apache-2.0, self-hosted) deploys Docker Compose projects onto any VPS you own over SSH, so it works on Elastx VMs and GleSYS KVM alike. Accounted's `docker-compose.yml` deploys as a compose resource; use Coolify's proxy for TLS instead of the Caddy overlay. Two documented gotchas: a `ports:` mapping in your compose exposes the port on the host *outside* Coolify's proxy (the Accounted file binds to loopback, keep it that way), and Coolify's one-click Supabase template lagged upstream (Postgres 15 while upstream defaults to 17, and a known bug that exposed the database port publicly), so for the sovereign stack run upstream Supabase's own compose rather than the template. https://coolify.io/docs/knowledge-base/docker/compose, https://coolify.io/docs/services/supabase
Managed catalogs that host open-source apps for you (PikaPods, Elestio) are EU-located but not Swedish; they are the middle option, not the headline.
## 4. Self-hosted Supabase: gotchas as of August 2026
These are the things that cost people an afternoon. Source: the upstream Docker self-hosting docs and changelog (https://supabase.com/docs/guides/self-hosting/docker, https://github.com/supabase/supabase/blob/master/docker/CHANGELOG.md).
- **`API_EXTERNAL_URL` now includes the `/auth/v1` path** (docker 0.7.0, July 2026): `API_EXTERNAL_URL=https://supabase.example.com/auth/v1`. Older guides show it without the path; GoTrue then builds wrong links.
- **Postgres 17 is the default image** since docker 0.6.0 (June 2026). Never start the 17 image on a 15 data directory: use upstream's `utils/upgrade-pg17.sh` (needs roughly twice the database size free, and back up the pgsodium root key from the `db-config` volume first). https://supabase.com/docs/guides/self-hosting/postgres-upgrade-17
- **The gateway depends on your release**: `self-hosted/v0.7.x` runs Kong by default (Envoy via the `docker-compose.envoy.yml` overlay), `self-hosted/v0.8.0` and later run Envoy by default (Kong via `docker-compose.kong.yml`). The diagrams in SELF-HOSTING.md say `kong`; the role is the same.
- **Studio is single-project** in self-hosted mode (`STUDIO_DEFAULT_ORGANIZATION` / `STUDIO_DEFAULT_PROJECT`); a byrå hosting many client companies still runs one Supabase project, since Accounted's multi-tenancy is inside the database.
- **No managed backups, no PITR.** Upstream says so plainly. This is why the next section exists.
- **Storage backend**: by default storage-api writes files to `./volumes/storage` (`STORAGE_BACKEND=file`). To put documents straight onto Swedish S3, set `STORAGE_BACKEND=s3` with `STORAGE_S3_BUCKET`, `STORAGE_S3_ENDPOINT`, `STORAGE_S3_REGION`, `STORAGE_S3_FORCE_PATH_STYLE=true` and the bucket's `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` in the storage service. Accounted's `documents` bucket is WORM at the application level either way (migration 024); Object Lock on the S3 side adds the provider-level guarantee.
## 5. Backup and restore (ship it, do not improvise it)
Swedish bookkeeping law requires the ledger and its underlag to be kept for seven years after the end of the fiscal year, and self-hosted Supabase gives you no backups. Two scripts in this repo cover the minimum:
- `scripts/self-host/backup.sh`: logical `pg_dump` (custom format, `--no-owner`, ACLs kept) of the Supabase database, an ACL manifest of the `public` schema (`scripts/self-host/acl-manifest.sql`: what anon, authenticated and service_role may do with every function, relation and sequence), a tar of the storage volume (the documents), optionally the `db-config` Docker volume (the pgsodium root key; without it Vault-encrypted columns are unreadable after a restore), SHA-256 manifest, uploaded to an S3-compatible bucket with optional **COMPLIANCE-mode Object Lock**.
- `scripts/self-host/restore.sh <name> --yes`: downloads a set, verifies checksums, unpacks db-config if asked, restores the database (`pg_restore --clean --if-exists --no-owner`), then re-runs the ACL manifest against the restored database and **stops on any difference**, then unpacks storage.
Why the ACL step exists: the migrations lock SECURITY DEFINER RPCs away from `anon`/`authenticated` with role-specific `REVOKE`s, but `pg_dump` writes ACLs as a diff against PostgreSQL's built-in defaults, so the dump only says "REVOKE FROM PUBLIC; GRANT TO service_role" and never "REVOKE FROM anon". A Supabase stack's `ALTER DEFAULT PRIVILEGES` would then hand `anon` EXECUTE back to every restored function. `restore.sh` resets the restoring role's default privileges to PostgreSQL's built-in ones right before `pg_restore` (the dump's own last section re-creates the source's defaults once every object exists, so later migrations still get the grants PostgREST needs) and the manifest diff proves the result. Reproduced on `supabase/postgres` 15 and `postgres` 17 (without the step, hardened RPCs and tables come back anon-reachable) and drilled with the real scripts against a migrated database: 576 `public` objects identical after the restore, a tampered manifest stops it.
`pg_restore` reports errors on a Supabase target even when the restore is fine, because the restoring `postgres` role is not a superuser and the stack already owns and grants its own objects. Expected classes: "already exists"; "does not exist" from `DROP ... IF EXISTS` of policies and triggers on a fresh target; "must be member of role supabase_*", "must be owner of ...", "permission denied ..." and "grant options cannot be granted back" on `GRANT`/`REVOKE`/`ALTER DEFAULT PRIVILEGES` for objects in `auth`, `storage`, `realtime`, `extensions`, `cron`, `vault`, `graphql*`, `pgbouncer`. Any error on a `public.*` object is **not** expected: investigate it. On errors the script stops before the ACL check and storage (the db-config volume, if requested, is already unpacked at that point); re-run with `RESTORE_TOLERATE_ERRORS=1` once you have read the log. An ACL mismatch has no override: fix the named objects by hand from the printed diff, or restore into a fresh stack.
Requirements on the host running them: `pg_dump`/`pg_restore`/`psql` matching the server major, `tar`, `gzip`, AWS CLI v2 (talks to any S3-compatible endpoint via `--endpoint-url`), and `docker` only if you back up the db-config volume. Uploads go through `aws s3api put-object`, which caps a single object at 5 GB and has no multipart fallback in the script: a dump or storage tar past that size needs splitting or another uploader before the run succeeds.
### Nightly plus yearly
Create the bucket with Object Lock enabled (it cannot be enabled afterwards). Then, on the host that can reach the database (a `.env.backup` you keep out of git):
```bash
export BACKUP_DATABASE_URL='postgresql://postgres:<password>@127.0.0.1:5432/postgres'
export BACKUP_S3_ENDPOINT='https://s3.sto2.safedc.net'
export BACKUP_S3_BUCKET='accounted-backups'
export AWS_ACCESS_KEY_ID='...'; export AWS_SECRET_ACCESS_KEY='...'
export BACKUP_STORAGE_DIR='/opt/supabase/docker/volumes/storage'
export BACKUP_DB_CONFIG_VOLUME='supabase_db-config'
```
```cron
# nightly set, 35 days immutable (covers mistakes, keeps storage bounded)
0 2 * * * . /root/.env.backup && BACKUP_OBJECT_LOCK_DAYS=35 /opt/accounted/scripts/self-host/backup.sh
# yearly archive copy after bokslut, seven years plus margin, COMPLIANCE mode,
# app stopped for the window so database and documents are one consistent set
0 3 15 1 * . /root/.env.backup && BACKUP_LABEL=yearly BACKUP_OBJECT_LOCK_DAYS=2700 BACKUP_QUIESCE_CMD='docker compose -f /opt/accounted/docker-compose.yml stop app cron' BACKUP_RESUME_CMD='docker compose -f /opt/accounted/docker-compose.yml start app cron' /opt/accounted/scripts/self-host/backup.sh
```
Alert on a non-zero exit: the script prints a few progress lines on success and fails loudly; if your cron mails stdout, add `>/dev/null` to the entry and keep stderr. The database dump and the storage tar are taken one after the other, so an upload landing in that window gives a set with a document row but no file (or the reverse); the nightly run accepts that (the next night covers it), and for the yearly archive run set `BACKUP_QUIESCE_CMD` / `BACKUP_RESUME_CMD` to stop and start the app containers around the run so the set is consistent. Storage grows by one dump plus one storage tar per run; the nightly lock expires and a lifecycle rule on the bucket can expire old nightly objects, the yearly ones cannot be deleted before their date by anyone.
### Restore drill (do this once before you need it)
1. Bring up a fresh Supabase stack on a scratch VM with the **same** `JWT_SECRET`, `ANON_KEY` and `SERVICE_ROLE_KEY` as production (or re-issue keys into Accounted's `.env` afterwards).
2. Two passes, because the db-config volume can only be replaced while the database container is stopped and `pg_restore` needs it running:
- Stop the database container, then `RESTORE_DB_CONFIG_VOLUME=<volume> RESTORE_SKIP_DATABASE=1 scripts/self-host/restore.sh <name> --yes` (unpacks the pgsodium root key, touches nothing else). Start the database container again.
- `RESTORE_DATABASE_URL=postgresql://postgres:...@<scratch-db>:5432/postgres RESTORE_STORAGE_DIR=<supabase-dir>/volumes/storage scripts/self-host/restore.sh <name> --yes` (database, ACL check, storage). Expect the first attempt to stop on the Supabase error classes above; read the log, re-run with `RESTORE_TOLERATE_ERRORS=1`. Then restart storage-api.
3. Point a scratch Accounted at it, log in, open a verifikat and its underlag, run the document-archive verification cron once (`/api/documents/verify/cron`): it recomputes SHA-256 over the archive and reports mismatches. The ACL check already ran inside `restore.sh` ("ACL manifest verified"); if you want to see it with your own eyes, `select has_function_privilege('anon', 'public.get_dashboard_nav_flags(uuid)', 'EXECUTE')` must be `false`.
4. Write down how long it took. That number is your recovery time.
## 6. Honest dependency list (what still touches a non-Swedish party)
A sovereign deployment still has these touchpoints. None carries accounting data; list them for your own risk register rather than pretending they are gone.
- **Image distribution**: the app image is pulled from GitHub Container Registry (`ghcr.io/erp-mafia/gnubok`), and the cron sidecar downloads `supercronic` from GitHub Releases at build time. Mirror both into your own registry for an air-gapped setup (build from source: `docker compose -f docker-compose.yml -f docker-compose.build.yml up --build`).
- **Fonts**: `next/font/google` downloads Geist and Hedvig Letters Serif **at build time** and self-hosts them; browsers never call Google. The GitHub-built image therefore has no runtime font dependency; a source build fetches them once during `next build`.
- **Invoice email**: the email extension sends through Resend (US) or, with `EMAIL_PROVIDER=smtp`, through your own relay: a Swedish mail provider, an M365/Workspace relay, Postfix on the host (variables in SELF-HOSTING.md, Email section; TLS is required unless you set `SMTP_REQUIRE_TLS=false` for a plaintext relay on a trusted LAN). Pick SMTP for a sovereign deployment, or leave invoice email unconfigured (invoices download as PDF). Resend, if you choose it, carries invoice PDFs to your customers but no ledger data.
- **Telemetry**: none. Analytics (PostHog) and Vercel Speed Insights are hosted-only and switched off by `NEXT_PUBLIC_SELF_HOSTED=true`; there is no error-tracking integration at all (SELF-HOSTING.md, Error Tracking: errors go to the container logs); there is no call-home licence check, by design.
- **Upstream services you opt into**: Enable Banking, Skatteverket, TIC, the migration gateway, Google OAuth for receipt hunt, Meta for WhatsApp are hosted-only today (section 2) and simply stay unconfigured.
## 7. Checklist
- [ ] Provider chosen for compute (Elastx CaaS/VM or GleSYS VPS) and a DPA on file.
- [ ] Supabase stack up with `API_EXTERNAL_URL` including `/auth/v1`, Postgres 17 image on a fresh data dir, `ADDITIONAL_REDIRECT_URLS` for the app's callbacks.
- [ ] Accounted migrations applied via `psql` (SELF-HOSTING.md, Fully Self-Hosted step 2).
- [ ] `NEXT_PUBLIC_SELF_HOSTED=true`, `CRON_SECRET` set, cron sidecar healthy (`docker compose ps`), `/api/health` green.
- [ ] Backup bucket created **with Object Lock**, `backup.sh` scheduled nightly + yearly, one restore drill completed and timed.
- [ ] AI: either none (MCP-only deployment) or `AI_BASE_URL`/`AI_API_KEY`/`AI_MODEL` set and `npx tsx scripts/smoke-ai-provider.ts receipt.pdf` green.
- [ ] Decide on invoice email (your own SMTP relay with `EMAIL_PROVIDER=smtp`, Resend, or none) and record it in your register.
- [ ] Read the national cloud policy yourself before quoting it to a buyer: it is principles, not mandates. https://www.regeringen.se/informationsmaterial/2026/05/en-molnpolicy-for-sverige--for-okad-sakerhet-effektivitet-och-innovation-i-den-offentliga-forvaltningen/
-192
View File
@@ -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.
-218
View File
@@ -1,218 +0,0 @@
# Whitelabel fork checklist
Accounted is whitelabel-friendly: every user-visible brand reference reads from a single `BrandingService` (`lib/branding/service.ts`). If you don't override anything, the app behaves exactly like upstream gnubok. To run your own brand on top of Accounted, fork the repo and override the values you care about.
## Quick start
```bash
# 1. Fork erp-mafia/gnubok on GitHub → you/your-brand
# 2. Clone and add upstream remote (one-time)
git clone https://github.com/you/your-brand
cd your-brand
git remote add upstream https://github.com/erp-mafia/gnubok
# 3. Copy the example branding extension
cp -r extensions/general/_example-branding extensions/general/your-brand
# Edit extensions/general/your-brand/index.ts with your brand values
# 4. (Optional) Set env vars instead of / in addition to the extension. See "Env vars" below.
# 5. Enable the extension
# Edit extensions.config.json and add "your-brand" to the array.
# 6. Run locally
npm run setup:extensions
npm run dev
# 7. Deploy to your hosting (Vercel, Docker, etc.)
```
## Env vars
All branding can be set via env vars. Public ones use `NEXT_PUBLIC_BRANDING_*` (build-time inlined, available in client components). Server-only ones use `BRANDING_*`.
| Env var | Field | Default |
|---|---|---|
| `NEXT_PUBLIC_BRANDING_APP_NAME` | `appName` | `Accounted` |
| `NEXT_PUBLIC_BRANDING_APP_DESCRIPTION` | `appDescription` | `Ekonomihantering` |
| `BRANDING_LEGAL_ENTITY` | `legalEntity` | `Arcim` |
| `BRANDING_SUPPORT_EMAIL` | `supportEmail` | `support@gnubok.se` |
| `BRANDING_PRIVACY_EMAIL` | `privacyEmail` | `privacy@gnubok.se` |
| `BRANDING_SECURITY_EMAIL` | `securityEmail` | `security@arcim.io` |
| `NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM` | `authEmailFrom`: From address Supabase Auth sends verification / reset emails from. Used to pre-populate the `from:` query on the "open in Gmail" button after signup. Set to whatever you configured in your Supabase Auth SMTP. | `noreply@gnubok.se` |
| `NEXT_PUBLIC_APP_URL` | `appUrl` | `https://app.gnubok.se` |
| `NEXT_PUBLIC_BRANDING_LOGO_PATH` | `logoPath` | `/gnubokiceon-removebg-preview.png` |
| `NEXT_PUBLIC_BRANDING_FAVICON_PATH` | `faviconPath` | `/favicon.ico` |
| `NEXT_PUBLIC_BRANDING_APPLE_ICON_PATH` | `appleTouchIconPath` | `/icons/icon-192.png` |
| `NEXT_PUBLIC_BRANDING_PWA_ICON_BASE` | `pwaIconBasePath` | `/icons` |
| `NEXT_PUBLIC_BRANDING_THEME_COLOR` | `themeColor` | `#304D83` |
| `NEXT_PUBLIC_BRANDING_MANIFEST_THEME_COLOR` | `manifestThemeColor` | `#1a1a1a` |
| `NEXT_PUBLIC_BRANDING_MANIFEST_BG_COLOR` | `manifestBackgroundColor` | `#ffffff` |
| `NEXT_PUBLIC_BRANDING_HIDDEN_NAV` | `hiddenNavHrefs` (comma-separated, e.g. `/salary,/customers`) | `` (none hidden) |
Resolution order (last wins): **defaults → env vars → extension override**.
`NEXT_PUBLIC_*` env vars are inlined at build time. Changing them requires a fresh `npm run build` to propagate.
`NEXT_PUBLIC_BRANDING_APP_NAME` also stamps the service worker push-notification fallback title in `public/sw.js`. This happens at build time for Vercel/local builds (via `scripts/inject-public-branding.mjs`, run from `prebuild`) and at container start for Docker (via `docker-entrypoint.sh`).
### Email / Resend (when `email` or `invoice-inbox` extensions are enabled)
| Env var | Purpose |
|---|---|
| `RESEND_API_KEY` | Resend API key: required for both outbound mail and the inbox webhook |
| `RESEND_FROM_EMAIL` | Default `From` address (e.g. `noreply@your-brand.se`); also used as the address you From-spoof through Resend |
| `RESEND_INBOUND_DOMAIN` | Domain used to compose per-company invoice-inbox addresses: `{local-part}@{RESEND_INBOUND_DOMAIN}` |
| `RESEND_INBOUND_WEBHOOK_SECRET` | Verifies the `/inbound` webhook signature from Resend |
| `RESEND_DELIVERY_WEBHOOK_SECRET` | Verifies the `/delivery-status` webhook signature from Resend. Optional: without it, invoice delivery history shows "sent" but never the delivery outcome |
### WhatsApp (when the `whatsapp-inbox` extension is enabled)
| Env var | Purpose |
|---|---|
| `WHATSAPP_ACCESS_TOKEN` | Meta system-user permanent token (`whatsapp_business_messaging` scope only) |
| `WHATSAPP_PHONE_NUMBER_ID` | Graph object id of your WhatsApp Business number |
| `WHATSAPP_APP_SECRET` | Verifies `X-Hub-Signature-256` on the `/webhook` POST |
| `WHATSAPP_VERIFY_TOKEN` | Shared secret for the GET subscription handshake (also entered in the Meta app dashboard) |
| `WHATSAPP_PHONE_HASH_KEY` | Random pepper for phone lookup hashes (`openssl rand -hex 32`) |
| `WHATSAPP_PHONE_ENCRYPTION_KEY` | 32-byte hex AES-256-GCM key for phone numbers at rest (`openssl rand -hex 32`) |
| `WHATSAPP_PUBLIC_NUMBER` | Optional: the public number as E.164 digits (e.g. `46766867041`) for the wa.me deep link in settings; unset = resolved from the Graph API |
## Things you MUST NOT change
These are stable contracts. Renaming them breaks existing data, sessions, or external clients (npm package consumers, MCP connectors, browser sessions, invite links). Leave them alone in your fork:
| Identifier | Where | Why |
|---|---|---|
| `gnubok-company-id` | cookie | Active company context: renaming breaks logged-in sessions |
| `gnubok-invite-token` | cookie | Pre-auth invite token holding: renaming drops in-flight invites |
| `gnubok_sk_` | API key prefix | All issued API keys; existing clients fail validation |
| `gnubok_inv_` | invite token prefix | All sent invite links break |
| `gnubok_*` | MCP tool names (`gnubok_list_invoices`, etc.) | Published MCP API: Claude clients have these cached |
| `gnubok-mcp` | npm package name | Whitelabel users still install `npx gnubok-mcp`. Document `GNUBOK_URL=https://app.your-brand.se/api/extensions/ext/mcp-server/mcp` so they hit your endpoint |
| `GNUBOK_API_KEY` | env var read by `gnubok-mcp` package | Same reason: npm consumer expects this name |
## What's outside this branding service
A few things that look brand-related but are configured elsewhere:
- **Supabase auth emails** (password reset, magic link): set in the Supabase dashboard for your project, not in code.
- **Resend sending domain**: verify `noreply@your-brand.se` (or wherever) in Resend, set `RESEND_FROM_EMAIL`.
- **DNS / domain**: point `app.your-brand.se` at your Vercel deployment.
- **OAuth redirect allowlist for MCP**: `lib/auth/oauth-allowlist.ts` has built-in entries for Claude (`claude.ai/api/*`, `claude.com/api/*`), ChatGPT, Grok, Cursor and localhost; anything else is registered per user under Settings > API & MCP > OAuth clients. Your domain is the OAuth issuer, not a redirect target: no change needed unless you're integrating with new MCP clients.
- **iCal feed PRODID** (`lib/calendar/ics-generator.ts`): defaults to `erp-base.se`, callers may pass their domain.
- **`NEXT_PUBLIC_APP_URL`**: used as the OAuth issuer and safe auth-link fallback. For a dedicated one-brand deployment, set this to your domain (e.g. `https://app.your-brand.se`). For a shared hosted deployment, keep the canonical main app URL here; additional hosts are the `brands.domain` rows (see below).
- **Skatteverket submission identity**: `extensions/general/skatteverket/lib/api-client.ts` does not set a custom `User-Agent`; submissions go out with the Node/Vercel runtime default. If your deployment needs to identify itself to Skatteverket under a different brand, that's a future enhancement (env var + header), not something the current branding service covers.
## Shared hosted deployment with custom domains
Use this checklist when several white-label domains point at one hosted Accounted deployment:
Accounted's hosted product serves its customers from the `accounted.se` zone: `app.accounted.se` plus one `<brand>.accounted.se` host per white-label byra. Every one of those hosts must be served by the production Supabase project `pwxtzglxptnnvjrpixpg`. The request proxy asserts that pairing instead of enumerating the hosts to protect: when the build answering a customer-facing production host is wired to any other backend (the staging project, a third project, or a URL it cannot parse), it emits an alerting structured error and returns an empty, non-cacheable `503` before session handling. The event records only the hostname and the `non_production` classification, never the configured backend URL or credentials.
Because the rule is stated as "this namespace belongs to the production project", a newly launched `<brand>.accounted.se` host is protected as soon as it resolves. There is no list to remember to update. The first version of the guard did the opposite: it enumerated seven approved hostnames, and on 2026-08-26 it failed open on `improveone.accounted.se`, a customer host nobody had added, which a feature-branch preview served from the staging project for hours. Vercel preview domains (`*.vercel.app`) and local development names stay out of scope. A host inside the namespace that is deliberately not production has to be excluded explicitly in `lib/domains/production-white-label-backend.ts`, in the same change that creates it.
Two kinds of host are not derivable from the namespace, so they are still classified by hand in `CUSTOMER_PRODUCTION_WHITE_LABEL_HOSTS` (`lib/domains/production-white-label-backend.ts`): Accounted's legacy canonical host `app.gnubok.se`, and a customer that brings its own domain (step 1 below). Add those as part of the same reviewed rollout. The set also still lists the `accounted.se` hosts the namespace rule already covers: there they are a checked-in inventory the tests pin host by host, not what makes those hosts protected. Do not derive the set from the `brands` table: that is the auth-link registry, not an authoritative production inventory, and it can also hold demo, pilot, or staging-only brands.
The guard contains a misrouted deployment. It does not classify domains outside the hosted namespace, prove cross-tenant isolation, or replace the operational work of placing customer environments under production ownership and controls. Its `alert: true` flag also pages nobody on its own: middleware never registers the observability sink, so the alerting rule is configured on the hosting side and matches `operation=white_label_backend_guard` in the emitted log line.
1. Register the exact custom hostname on the hosting deployment and finish its DNS verification.
2. Create the brand row with that hostname as `brands.domain` (exact hostname such as `portal.partner.se`, no wildcards). This row is the only application-side registry: password reset, invite, email change and signup links, Stripe billing return URLs and Enable Banking consent callbacks all resolve the request host against it (`lib/domains/trusted-app-origin.ts`), so no environment variable and no redeploy is involved. An Enable Banking consent started from an unregistered host returns to the canonical login instead.
3. Make sure GoTrue accepts the callback. GoTrue matches allowlist entries against the FULL `redirect_to`, query string included, and a single `*` stops at `.` and `/`, so an entry must end in `**` to accept `/auth/callback?next=/reset-password` or `?flow=email_change`. Hosts under `accounted.se` are covered by the two wildcard entries `https://*.accounted.se/auth/callback**` and `https://*.accounted.se/invite/**` in the Supabase Auth Redirect URLs allowlist. A partner that brings its own domain needs `https://portal.partner.se/auth/callback**` and `https://portal.partner.se/invite/**` added there explicitly. Keep the canonical `NEXT_PUBLIC_APP_URL` callback there too. A host missing from this allowlist is the one remaining way to get a canonical-branded mail: GoTrue silently replaces an unlisted `redirect_to` with the Site URL before the Send Email hook runs.
4. Test a new-user invitation, an existing-user invitation, a password reset (signed out and signed in), and an email change from the custom domain, and check the landing domain of each real mail.
The request `Host` header is an input, not a trust anchor. Accounted uses it only when the hostname exactly matches the canonical app host, one of the deployment's own Vercel hostnames, or a registered `brands.domain`. Unknown or spoofed hosts fall back to `NEXT_PUBLIC_APP_URL`, so they cannot become invite links or GoTrue redirect targets.
## Staying in sync with upstream
Add this workflow at `.github/workflows/sync-upstream.yml` to your fork. It runs weekly and opens a PR with upstream changes:
```yaml
name: Sync from upstream
on:
schedule:
- cron: '0 3 * * 1' # Mondays 03:00 UTC
workflow_dispatch:
jobs:
sync:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
token: ${{ secrets.GITHUB_TOKEN }}
- name: Configure git
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
- name: Add upstream and fetch
run: |
git remote add upstream https://github.com/erp-mafia/gnubok
git fetch upstream main
- name: Create sync branch and merge
id: merge
run: |
BRANCH="sync/upstream-$(date +%Y-%m-%d)"
git checkout -b "$BRANCH"
if git merge --no-edit upstream/main; then
echo "status=clean" >> "$GITHUB_OUTPUT"
else
echo "status=conflict" >> "$GITHUB_OUTPUT"
git merge --abort || true
fi
echo "branch=$BRANCH" >> "$GITHUB_OUTPUT"
- name: Push and open PR (clean merge)
if: steps.merge.outputs.status == 'clean'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
if git diff --quiet origin/main..HEAD; then
echo "Up to date with upstream: nothing to do."
exit 0
fi
git push origin "${{ steps.merge.outputs.branch }}"
gh pr create \
--base main \
--head "${{ steps.merge.outputs.branch }}" \
--title "Sync from upstream Accounted" \
--body "Automated weekly sync from \`erp-mafia/gnubok@main\`."
- name: Report conflict
if: steps.merge.outputs.status == 'conflict'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh issue create \
--title "Upstream sync conflict ($(date +%Y-%m-%d))" \
--label sync-conflict \
--body "Automated upstream merge hit a conflict. Resolve manually: \`git fetch upstream && git merge upstream/main\`."
```
## Conflict avoidance
The fork-friendliness of this design depends on you keeping changes confined to your branding extension folder. Every file you edit in `lib/`, `app/`, or `components/` becomes a potential conflict on the next upstream merge. If you find yourself wanting to override something the branding service doesn't expose, prefer:
1. **Open an upstream issue**: the branding service is intentionally minimal; missing fields can be added.
2. **PR a hook upstream**: extending the service or adding a registry pattern keeps your fork clean.
## Verifying your whitelabel
After deploying:
- [ ] Visit `/`: browser tab title shows your brand.
- [ ] Visit `/login` and `/register`: your logo renders.
- [ ] View source of `/manifest.webmanifest`: `name`, `short_name`, `theme_color` reflect your overrides.
- [ ] Trigger an invite email: From line says `<your-brand> <noreply@...>`, body uses your name.
- [ ] Visit `/dpa` and `/privacy`: legal entity and contact email are yours.
- [ ] Open OAuth flow (`/api/mcp-oauth/authorize?...`) from a test MCP client: consent page references your brand.
- [ ] Submit support form (Settings → Support): internal subject prefix is `[<your-brand> support]`.
-74
View File
@@ -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.
-47
View File
@@ -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`._
+4 -4
View File
@@ -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`._
-36
View File
@@ -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`._
-26
View File
@@ -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`._
-35
View File
@@ -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`._
-21
View File
@@ -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`._
-110
View File
@@ -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/)
-211
View File
@@ -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.
-264
View File
@@ -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.