resolve: README adopts main (newer, fail-closed auth docs)
CI (SIAX Cloud) / security (push) Successful in 17s
CI (SIAX Cloud) / quality (push) Successful in 39s
CI (SIAX Cloud) / security (pull_request) Successful in 20s
CI (SIAX Cloud) / quality (pull_request) Successful in 46s

This commit is contained in:
SIAX Ops
2026-08-09 11:30:18 +02:00
10 changed files with 717 additions and 109 deletions
+7 -5
View File
@@ -65,11 +65,13 @@ INTERNAL_TOKEN=change-me-internal-token
#
# Fleet Zitadel issuer (OIDC). Default when unset: https://id-customers.siax.io
ZITADEL_ISSUER=https://id-customers.siax.io
# Flag-gated enforcement. When != "true" (DEFAULT) auth is non-breaking:
# a present Bearer token is best-effort verified and attached, but never
# rejected. Set to "true" to REQUIRE a valid token on /api/0pt/* (401 on
# missing/invalid, 403 when X-Tenant-Id disagrees with the token tenant).
AUTH_ENFORCE=false
# Enforcement is FAIL-CLOSED. Leave this UNSET (or set it to "true") and a
# valid, verified Bearer token is REQUIRED on /api/0pt/* -- 401 on
# missing/invalid, 403 when X-Tenant-Id disagrees with the token tenant.
# ONLY the literal value "false" disables authentication, and that value is
# REFUSED when NODE_ENV=production: the app throws at startup instead of
# serving openly. Use "false" for local development only.
AUTH_ENFORCE=true
# Optional override for the claim key that carries the SIAX tenant id. When
# unset, tenant derivation uses the documented precedence:
# urn:zitadel:iam:org:id -> urn:zitadel:iam:user:resourceowner:id -> tenant_id -> tenant.
+18
View File
@@ -0,0 +1,18 @@
name: Health Check (SIAX Cloud)
on:
workflow_dispatch:
schedule:
- cron: "0 6 * * 1"
jobs:
health:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Required files
run: |
for f in README.md LICENSE .gitignore; do [ -f "$f" ] || echo "::warning file=$f,title=Missing::$f is missing"; done
[ -f .gitea/workflows/ci.yml ] || echo "::warning title=No CI::No CI workflow found"
- name: Install Trivy
run: curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
- name: Secret scan
run: trivy fs --scanners secret --exit-code 0 .
+21 -59
View File
@@ -7,6 +7,13 @@ confidence; nothing is guessed.
**Live:** https://0pt.app · **Contract:** [`CLAUDE.md`](CLAUDE.md) + [`docs/`](docs/)
> **Architecture (verified against code, not aspirational):**
> [`docs/architecture/ARCHITECTURE.md`](docs/architecture/ARCHITECTURE.md).
> It documents the real API surface, the real persistence story, and the known
> security gaps — including several places where this README is optimistic. Read
> it before trusting any capability claim below. Repo identity + estate
> classification: [`siax.config.json`](siax.config.json).
## Two planes (see [docs/02-architecture.md](docs/02-architecture.md))
- **Edge (Vercel, this app)** — marketing, catalog, the order lifecycle, customer portal,
@@ -16,16 +23,6 @@ confidence; nothing is guessed.
Never on Vercel (long jobs). Bypass/stealth/proxy-rotation/fake-account paths are excluded
by design (CLAUDE.md §1).
> ⚠️ **The exclusion above is the POLICY, not the current state of this tree.**
> `services/scrapers/` still contains 64 files implementing exactly what CLAUDE.md §1
> prohibits — curl_cffi TLS impersonation, cloudscraper, Tor rotation, `WAFBypass`,
> `ProxyRotator` — plus committed `__pycache__/*.pyc`. They arrived on the Gitea line on
> 2026-07-13 and are documented in [docs/06-data-engine.md](docs/06-data-engine.md).
> [PR #1](https://git.siax.io/sax3l/0pt/pulls/1) exists to delete them and has been open
> since 2026-07-19. Nothing in the TypeScript tree imports them and they are not copied
> into the runner stage, so they do not execute — but they are present, and this README
> previously read as if they were not.
## Routes
| Area | Routes |
@@ -33,11 +30,10 @@ confidence; nothing is guessed.
| Marketing | `/` (hero, filosofi, katalog, motorn, visualiseringar, täckning, editorial, bevis, priser, footer) |
| Catalog | `/katalog`, `/katalog/[id]` |
| Sourcing map | `/kallor` |
| Order lifecycle | `/bestall` → `/bestall/beskriv` → `/bestall/forskott` → `/order/[id]` → `/order/[id]/validera` |
| Order lifecycle | `/bestall` → `/bestall/forskott` → `/order/[id]` → `/order/[id]/validera` |
| Customer portal | `/portal`, `/portal/subscriptions`, `/portal/files`, `/portal/integrationer`, `/portal/settings` |
| Admin portal | `/admin`, `/admin/sources`, `/admin/jobs`, `/admin/customers`, `/admin/verktyg` |
| API | `/api/{health,estimates,catalog,sources,vehicles,screen,orders,orders/[id],subscriptions,admin/metrics,uploads,auth/*,ai/parse,payments/*,webhooks/stripe,connections/db-grant}` |
| Data platform (P0) | `/api/0pt`, `/api/0pt/documents/capture`, `/api/0pt/documents/[documentId]/extraction`, `/api/0pt/lakehouse/mappings[/[mappingId]/writes]`, `/api/0pt/sources/[sourceId]/query`, `/api/0pt/sources/rate-policies[/[id]]` — ⚠ these read `tenant_id`/`project_id` from the request body or query string, not a server session. See **Known issues** below. |
| Admin portal | `/admin`, `/admin/sources`, `/admin/jobs`, `/admin/customers` |
| API | `/api/{health,estimates,catalog,sources,orders,orders/[id],subscriptions,admin/metrics,uploads,auth/*,payments/*,webhooks/stripe,connections/db-grant}` |
## Design system
Mono/editorial, light, radius 0, Inter + JetBrains Mono, single red `#e40014`, animated grain,
@@ -56,54 +52,20 @@ cd services/api && pip install -r requirements.txt && uvicorn orchestrator.main:
## Deploy
- **Frontend** → Vercel (project `0pt`, scope *Simon Axelsson's projects*), domain `0pt.app`.
- **Engine + DB + embeds** → one VPS via [`infra/docker-compose.yml`](infra/docker-compose.yml) (Postgres+pgvector, Redis, api, worker, NocoDB, Metabase, Caddy).
- Env inventory: `.env.example` — **not on `main` yet.** It exists on branch/PR
[`feature/0pt-env-example`](https://github.com/sax3l/0pt/pull/3) (github.com/sax3l/0pt PR #3, unmerged as of
this pass), added after discovering `.gitignore`'s blanket `.env*` rule had silently kept it out of every
commit despite `docs/09-build-plan.md` Phase 0 requiring it. Until that PR merges, use
[`docs/08-infrastructure.md`](docs/08-infrastructure.md) as the source of truth for env var names.
- Env inventory: [`.env.example`](.env.example).
- **Auth on `/api/0pt/*` is fail-closed**: with `AUTH_ENFORCE` unset the middleware
REQUIRES a verified Zitadel Bearer token (401 without one). Only the literal
`AUTH_ENFORCE=false` disables it, and that is refused when `NODE_ENV=production`
(the process throws at startup rather than serving anonymously).
## Status
Frontend (marketing, catalog, order lifecycle UI, customer + admin portals) and the edge API route
handlers build and typecheck green. That is a statement about the code compiling and running, **not**
about the platform being production-ready — read **Known issues** below before relying on any of this
against real tenants or real money.
Frontend, full order lifecycle, customer + admin portals, edge API, payment/auth/embed
infrastructure, the compliant data engine, schema and infra are all in place and building green.
Integrations are env-guarded and activate when their keys/DB are provided:
1. **Database** — Vercel → Storage → Postgres (sets `POSTGRES_URL`) → durable persistence (schema in [`sql/001_init.sql`](sql/001_init.sql)). Without it, orders fall back to an in-memory, non-durable store (`lib/orders-store.ts`).
2. **Stripe** keys → payments (`app/api/payments/*`, `app/api/webhooks/stripe`) — this is wired code, not just a plan. **Resend** is documented as the email provider (`docs/08-infrastructure.md`) but has no call site anywhere in this repo yet — treat "+ email" as not-yet-implemented, not merely unconfigured.
3. **VPS** for the engine (`services/api`) → set `ENGINE_URL` so edge routes defer to it (`lib/engine.ts`). Unset, several routes (`/api/screen`, `/api/vehicles`, `/api/ai/parse`) fall back to calling public sources directly or computing locally instead.
4. **`AUTH_SECRET` + `DEV_LOGIN_KEY`** → a guarded **dev-only** login (`app/api/auth/login/route.ts`): an HMAC-signed session cookie (`lib/auth.ts`), not a real auth system. Full OAuth via Auth.js is Phase 3 of `docs/09-build-plan.md` and has not been built — see Known issues.
## Known issues
Blunt on purpose, per `CLAUDE.md`'s own house rule ("flag conflicts ... and propose the reconciliation
rather than guessing"). These are open, real gaps as of this pass — not silently patched, not guessed at.
1. **No authentication or tenant scoping is wired anywhere in this repo.** The only thing that exists is
the `DEV_LOGIN_KEY` dev gate described above. There is no session-to-org/tenant binding at all —
`app/api/orders/route.ts`'s own `GET` handler carries the literal comment `// GET /api/orders — list
(org scoping added with auth).`, i.e. not yet. As a direct consequence, the newer P0 data-platform
routes read `tenant_id`/`project_id` **from the client-supplied request body or query string** instead
of a server-bound session:
- `app/api/0pt/lakehouse/mappings/route.ts` and `.../[mappingId]/writes/route.ts`
- `app/api/0pt/sources/rate-policies/route.ts` and `.../[sourceRatePolicyId]/route.ts`
- `app/api/0pt/sources/[sourceId]/query/route.ts`
- `src/services/document-capture-service.ts` (called from `app/api/0pt/documents/capture/route.ts`)
This violates the platform-wide hard rule that `tenant_id` must be server-bound to an authenticated
session and never read from client input. It is not a deliberate two-tier design — it exists because no
auth/session system has been built yet. Do not expose these routes to untrusted callers before Phase 3
(`docs/09-build-plan.md`) lands.
2. **The CL0UD/N0D/AUD0/ST0RE platform clients are real code, but mock-only.** `src/clients/{cl0ud,n0d,aud0,st0re,st0re-lakehouse}-client.ts` are genuine, typechecked TypeScript with real tests — but every one of them runs against an in-memory mock today. **Corrected this pass:** `CL0UD_URL`/`N0D_URL`/`AUD0_URL`/`ST0RE_URL` are never read via `process.env` anywhere in this repo — verified by grepping the whole tree; the only hits are a code comment and a `TODO`/`it.todo` in `tests/p0/iceberg-write-service.test.ts` describing `ST0RE_URL` as future work, not an actual read. Every client only accepts an optional constructor `baseUrl` (`st0reBaseUrl`, `cl0udBaseUrl`, `n0dBaseUrl`, `aud0BaseUrl`), and every service that instantiates one (`src/services/*.ts`) is called from its route handler with no options, so all of them resolve to the in-memory mock today. Read this as "real code, mock-only, not live-verified, no env wiring at all yet" wherever it comes up — not "integrated" or "connected."
3. **0pt's data-quality/QA enforcement code does not exist in this repo.** `src/services/quality-check-service.ts`, `src/services/quality-report-service.ts`, `src/types/quality-check.ts`, `src/types/quality-report.ts`, `src/data-platform/services/catalog-service.ts`, `sql/002_p0_dataset_quality.sql`, and `sql/003_*.sql` were at one point described, in `docs/ICEBERG_WRITE_BOUNDARY.md`, `docs/11-lakehouse-write-plan.md`, and `docs/P0_QUERY_SOURCE_FLOW.md`, as if they were already built and tested. `git log --all` for every one of those paths returns zero commits, on any branch, ever — they have never existed in this repository; the `sql/` directory today holds only `001_init.sql` and `004_iceberg_write_boundary.sql`. 0pt's QA/quality-check stage is **spec/target only** right now. **Corrected as of this pass:** all three of the docs above, plus `docs/12-edge-capability-api.md`, now consistently state this — each carries its own "fabricated, not built" callout, and `docs/P0_DATASET_QUALITY_FLOW.md` (added by an earlier parallel pass) is the explicit, clearly-labeled target-spec doc for what this stage should look like once built. Treat any *other* doc that asserts the QA stage already exists as wrong until it actually lands.
4. **Two diverged git remotes both claim to be "the 0pt repo."** `origin` in this checkout is `github.com/sax3l/0pt`. A separate Gitea remote, `git.siax.io/sax3l/0pt`, shares at least part of the same history — `services/api/workers/adaptive_router.py` is byte-for-byte identical between GitHub's current `main` and a Gitea post-fix PR branch — but Gitea's `main` independently accumulated three 2026-07-13 commits adding a real WAF-bypass/proxy-rotation/fake-identity scraper stack (`services/scrapers/*`, since removed via a Gitea PR) that never touched GitHub's `main`. Which remote is authoritative, which is deployed to `0pt.app`, and whether the two should be kept in sync is **unresolved — Simon's decision**, not something this pass or any doc should silently assume.
5. **0pt is registered as API-only in the platform's six-surface capability model, not "api/cli/mcp/ui/job/sdk" across the board.** 14 `0pt.*` capabilities are registered in `cl0ud`'s `packages/capability-registry/src/registry.ts` today (verified by name: `query_source`, `document_ocr`, `write_external_record`, `lakehouse_mapping_manage`, `lakehouse_write`, `source_rate_policy_manage`, `screen_sanctions`, `estimate_compute`, `vehicle_lookup`, `catalog_list`, `source_registry_list`, `order_create`, `order_payment`, `write_iceberg_table`). None has `cliEnabled`/`mcpEnabled` true. Surfaces, checked per-entry: 11 have `['api']` only, `lakehouse_write` and `write_iceberg_table` have `['api', 'job']`, and `write_external_record` has `['job']` only (no `api` surface at all) — so it is not quite "api everywhere plus job for the two heaviest," one capability is job-only. If any doc anywhere describes a live `siax 0pt ...` CLI or an 0pt MCP tool, it is describing a target, not current reality.
6. **No evidence a "t_0pt" dedicated-node N0D auth pattern is built.** `sax3l/n0d` was searched in full (all branches, all commits, all files) — zero references to `t_0pt` exist anywhere in that repo. Treat any claim that this is already built/tested as unconfirmed.
1. **Database** — Vercel → Storage → Postgres (sets `POSTGRES_URL`) → durable persistence (schema in [`sql/001_init.sql`](sql/001_init.sql)).
2. **Stripe + Resend** keys → payments + email.
3. **VPS** for the engine → set `ENGINE_URL`.
4. **`AUTH_SECRET` + `DEV_LOGIN_KEY`** → login (full OAuth via Auth.js lands with the DB).
© 2026 SIAX Technology AB. Not affiliated with Protosell.
+31
View File
@@ -144,6 +144,37 @@ in the desired priority, and the rank dict is currently dead code (documentation
in-memory dicts (`_ORDERS`, `_JOBS`) that reset on every restart. The schema exists; the wiring from
pipeline output → Postgres rows does not yet.
### Network-layer provenance: `1p` (not yet in use)
`bridge_provenance` answers *which source a field came from*. It does not answer *what
actually happened on the wire* — which policy authorized the fetch, whether `robots.txt` was
read and what it said, or whether the bytes we parsed were the page or a bot wall served with
HTTP 200. **[`1p`](https://git.siax.io/sax3l/1p)**, the SIAX egress measurement point, closes
that gap and extends the provenance chain all the way down to the network layer.
1p owns four things: a per-destination policy as code (default DENY; rate, robots/ToS stance,
allowed methods), a single egress choke point, block detection, and one provenance record per
fetch written to AUD0. Everything else is composed (AUD0, ST0RE, CL0UD).
Why this matters for 0pt specifically — three facts that are hard to assert without it:
| Claim 0pt makes | What 1p adds |
|---|---|
| "acquired from an authorized public page, respecting `robots.txt`" | The record carries the robots decision **plus a sha256 of the `robots.txt` it was taken from**. A policy that says `respect` and cannot read robots denies the fetch — silence is not permission. |
| "these are the bytes we parsed" | `body_sha256` per fetch, so a delivered field can be tied back to the exact response at the exact time. |
| "level 1/2/3 corroboration from independent sources" | Responses are classified `ok` / `rate_limited` / `forbidden` / `captcha` / `blocked_soft` / `error`. `blocked_soft` is the expensive one: **HTTP 200 whose body is a block page**. Without it, a bot wall gets parsed and scored as corroborating data. |
**It is a measurement point, not a bypass.** This is consistent with, not an exception to,
the prohibitions above and in `CLAUDE.md` §1: 1p exists to *detect* blocking and *prove*
provenance, never to evade. Its purchased-residential egress pool is an interface with a stub
that throws — wiring it up would be a separate, explicit decision. Block detection also
alarms on a rising *trend*, never on single events, and deliberately excludes `error`
(their 5xx, our timeouts) from the blocking measure.
**Status: not in use.** 1p is Phase 0 — code, contracts, tests; not deployed, no credentials
set. No 0pt worker routes through it today, and `bridge_provenance` remains the only
provenance 0pt writes. Adopting it is a later, separate step.
## `sources.yaml` (machine-readable registry)
Single registry that drives the router, the `/sources` API, and the (still-to-be-built) public sourcing-map
+417
View File
@@ -0,0 +1,417 @@
# 0PT — Arkitektur
**Kategori:** PLATTFORM **Underkategori:** Data OS **Status:** under utveckling (deployad frontend i drift, capability-lagret ej produktionsklart)
**Senast verifierad mot kod:** 2026-08-07 (commit `6531384`, main)
> **Läsanvisning.** Detta dokument beskriver vad koden i repot **gör**, inte vad
> `README.md`, `CLAUDE.md` eller `docs/01–11` säger att den borde göra. Där de
> avviker står avvikelsen utskriven — se §7. Påståenden märkta *(live-verifierat
> 2026-08-07)* är kontrollerade mot den körande instansen på `https://0pt.app`.
> Allt annat är läst ur källkoden. Där något inte gick att belägga står **OKÄNT**.
---
## 1. Syfte
0pt är SIAX Clouds **Data OS**: plattformen som skaffar, strukturerar, härleder
och levererar företags-, kontakt- och fordonsdata för Norden/Europa, med
proveniens (källa, färskhet, konfidens) per fält.
Repot innehåller i praktiken **två separata system** i samma träd:
| Plan | Var | Vad koden faktiskt är |
|---|---|---|
| **Webbkonsol + edge-API** | repo-roten (`app/`, `lib/`, `components/`) | Next.js 16.0.10 App Router. 20 sidor (svensk UI-copy), 28 API-routehandlers. Marknadsföring, katalog, orderflöde, kund-/adminportal. |
| **Capability-lager** | `src/` + `app/api/0pt/*` | TypeScript-tjänster för `0pt.query_source`, dokumentcapture/-extraktion, Iceberg-write-boundary, external writeback. **All state ligger i `Map`-objekt i minnet** (`src/services/*.ts`), inte i databas. |
| **Data-engine** | `services/api/` | FastAPI-orkestrator, 12 endpoints, 162 rader. Workers (`adaptive_router`, `pipeline`, `queue`, `resolve`, `run`). |
| **Skrapmotor** | `services/scrapers/` | Python. `engine.py`, `engine_v2.py`, `waf_bypass.py`, ClickHouse-pipeline. |
### Vad 0pt uttryckligen INTE gör
- **Ingen egen IdP.** Bearer-tokens verifieras mot Zitadel (`src/auth/zitadel.ts`),
utfärdas aldrig här. Cookie-sessionen i `lib/auth.ts` är ett HMAC-scaffold med
dev-login bakom `DEV_LOGIN_KEY`, uttryckligen inte produktionsauth.
- **Ingen BigQuery.** Ingen referens till BQ finns i koden (verifierat med grep).
- **Ingen egen policymotor.** Beslut delegeras till CL0UD (`src/clients/cl0ud-client.ts`).
- **Ingen tung batch i webblagret.** Långa jobb ska gå till engine/N0D.
### Uttryckligt förbud som koden BRYTER MOT
`CLAUDE.md` §1 och `README.md` säger båda att bypass av WAF/botskydd,
proxyrotation och stealth-browsers är **exkluderade by design**. Det stämmer inte:
`services/scrapers/waf_bypass.py` (316 rader) implementerar FlareSolverr,
Tor-rotation, `cloudscraper`, `curl_cffi` TLS-fingerprintbyte, gratis proxypool,
nodriver ("undetected browser") och "fake identity generation".
`services/infra/docker-compose.data-stack.yml` startar `flaresolverr` och
`tor-proxy` som tjänster. Commit `4a164c5` (Simon Axelsson, 2026-07-13) heter
ordagrant *"refactor: remove compliance restrictions"*. Se §7 lucka **S9**.
---
## 2. Plats i estatet
### Beroenden uppåt (0pt anropar)
| Beroende | Klient | Env-var | Beteende när env saknas |
|---|---|---|---|
| Zitadel (IdP) | `src/auth/zitadel.ts` | `ZITADEL_ISSUER` (default `https://id-customers.siax.io`) | Använder default-issuern; JWKS hämtas via OIDC-discovery, fallback `<issuer>/oauth/v2/keys` |
| CL0UD (policy) | `src/clients/cl0ud-client.ts` | `CL0UD_URL` | **Fail-open** — returnerar alltid `allow` utan nätanrop (§7 S5) |
| AUD0 (audit) | `src/clients/aud0-client.ts` | `AUD0_URL` | **No-op** — inga auditevent skrivs (§7 S6) |
| ST0RE (artefakter/lakehouse) | `src/clients/st0re-client.ts`, `st0re-lakehouse-client.ts` | `ST0RE_URL` | Returnerar deterministisk mockartefakt |
| N0D (jobb) | `src/clients/n0d-client.ts` | `N0D_URL` | Returnerar deterministiskt mockjobb |
| Egen data-engine | `lib/engine.ts` | `ENGINE_URL`, `INTERNAL_TOKEN` | `engineFetch` returnerar `null`, edge räknar lokalt |
| Stripe | `lib/stripe.ts` | `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` | Betalroutes svarar `501` |
| Azure Document Intelligence | `src/adapters/document-intelligence-adapter.ts` | `DOC_INTELLIGENCE_*` | Extraktion svarar "not configured" |
| Cloudflare R2 | `app/api/uploads/route.ts` | `R2_ENDPOINT`, `R2_BUCKET`, `R2_ACCESS_KEY_ID` | `501`, fallback `OPT_LOCAL_BLOB_DIR` |
| OpenSanctions (extern, publik) | `app/api/screen/route.ts` | — | Anropas direkt utan nyckel |
| Odoo | `src/adapters/odoo-bills-adapter.ts` | `ODOO_BASE_URL` | Adapter inaktiv |
Mönstret är genomgående: **saknad env ⇒ tyst degradering, inte fel.** Det är
bekvämt lokalt och farligt i produktion (§7 S5, S6).
### Beroenden nedåt (vem konsumerar 0pt)
Enligt `CLAUDE.md` matar 0pt interna produkter (Protosell/FiveCRM, VehIQ). **Inga
sådana anrop finns i det här repot** — ingen inkommande integration är verifierad
här. Betrakta konsumentlistan som odokumenterad tills motparten visats.
### Vad 0pt inte får bero på
- **BigQuery** — hård estate-regel. Ej överträdd.
- **Hogia** — skrivning förbjuden. Ingen referens finns.
- **Protosell-tenantdata** — tenantisolering, se §7 S2.
- Nya SaaS-beroenden utan dokumenterat skäl (`CLAUDE.md` §4, "one tool per job").
---
## 3. API-yta
Risknivå = SIAX L0–L5-taxonomin, bedömd av mig utifrån vad handlern gör.
"Kräver godkännande" = huruvida koden **faktiskt** kräver auth/godkännande idag.
### 3.1 `/api/0pt/*` — capability-lagret (bakom `middleware.ts`-matchern)
| Operation | Metod/sökväg | Risknivå | Kräver godkännande |
|---|---|---|---|
| Capability-index | `GET /api/0pt` | L0 | Nej — *(live-verifierat: 200 anonymt)* |
| Registrera dataset↔Iceberg-mappning | `POST /api/0pt/lakehouse/mappings` | L3 | Nej i kod; `tenant_id` läses ur body |
| Lista mappningar | `GET /api/0pt/lakehouse/mappings` | L2 | Nej; `tenant_id` ur query |
| Hämta mappning | `GET /api/0pt/lakehouse/mappings/{mappingId}` | L2 | Nej |
| Utför Iceberg-write | `POST /api/0pt/lakehouse/mappings/{mappingId}/writes` | **L4** | Nej i kod (CL0UD fail-open, §7 S5) |
| Registrera rate-policy | `POST /api/0pt/sources/rate-policies` | L2 | Nej |
| Lista/hämta rate-policy | `GET /api/0pt/sources/rate-policies[/{id}]` | L1 | Nej |
| Kör källfråga | `POST /api/0pt/sources/{sourceId}/query` | **L4** | Nej; `connection_config` tas ur body (§7 S10) |
| Ta emot dokument | `POST /api/0pt/documents/capture` | L3 (PII) | Nej |
| Lista dokument | `GET /api/0pt/documents/capture` | L3 (PII) | Nej |
| Extrahera dokument | `POST /api/0pt/documents/{documentId}/extraction` | L3 (PII) | Nej |
### 3.2 Övriga API-routes — **helt utanför middleware-matchern**
`middleware.ts` har `matcher: ['/api/0pt/:path*']`. Allt nedan har därför
**noll autentisering i koden**.
| Operation | Metod/sökväg | Risknivå | Kräver godkännande |
|---|---|---|---|
| Liveness | `GET /api/health` | L0 | Nej (avsiktligt) |
| Prisestimat | `POST /api/estimates` | L1 | Nej |
| Katalog / källor / fordon | `GET /api/{catalog,sources,vehicles}` | L1 | Nej |
| Sanktions-/PEP-screening | `GET /api/screen?q=` | L2 | Nej — proxar mot OpenSanctions |
| AI-parsning av fritext | `POST /api/ai/parse` | L2 | Nej |
| Skapa order | `POST /api/orders` | L2 | Nej |
| **Lista alla ordrar** | `GET /api/orders` | **L3** | **Nej** — ingen org-scoping *(live: 200, `[]`)* |
| Läs/ändra order | `GET,PATCH /api/orders/{id}` | L3 | Nej |
| **Adminmetrik (orderpipeline, belopp)** | `GET /api/admin/metrics` | **L3** | **Nej** *(live-verifierat: 200 anonymt)* |
| Deposition (Stripe checkout) | `POST /api/payments/{order_id}/deposit` | **L4** | Nej |
| **Frigör escrow-slutbetalning** | `POST /api/payments/{order_id}/release` | **L4** | **Nej** — sätter dessutom status `delivered` (§7 S4) |
| Stripe-webhook | `POST /api/webhooks/stripe` | L3 | Signaturkontroll via `STRIPE_WEBHOOK_SECRET` |
| Prenumerationer | `GET,POST /api/subscriptions` | L2 | Nej |
| Filuppladdning | `GET,POST /api/uploads` | L3 | Nej (`501` utan R2) |
| Ta emot kund-DB-grant | `POST /api/connections/db-grant` | **L4** | Nej (`501` utan `GRANT_ENC_KEY`; §7 S7) |
| Dev-login | `POST /api/auth/login` | L2 | Ja — kräver `AUTH_SECRET` + matchande `DEV_LOGIN_KEY` |
| Logout / me | `POST /api/auth/logout`, `GET /api/auth/me` | L1 | Cookiebaserat |
### 3.3 FastAPI-engine (`services/api/orchestrator/main.py`)
12 endpoints: `GET /health`, `/sources`, `/sources/{market}`, `/vehicles/{plate}`,
`/screen`, `POST /estimates`, `POST /orders`, `GET /orders`, `GET /orders/{oid}`,
`PATCH /orders/{oid}`, `POST /orders/{oid}/run`, `GET /orders/{oid}/status`.
**Ingen autentisering alls** — grep efter `Depends`, `auth`, `token`,
`X-Internal-Token` i filen ger noll träffar, trots att `lib/engine.ts` skickar
`X-Internal-Token`. Se §7 S8.
---
## 4. Datamodell
### 4.1 Postgres-schema (DDL finns, används inte av `/api/0pt/*`)
`sql/001_init.sql` definierar 13 tabeller:
- **Dataentiteter:** `dim_source`, `dim_company`, `dim_contact`, `dim_ubo`,
`dim_vehicle`, `fact_financials`
- **Proveniens:** `bridge_provenance` (`entity_type`, `entity_key`, `field_name`,
`source_id`, `freshness`, `confidence`, `level` 0–3, `agreed_sources`) — unikt
index per fält. Detta är produktens kärnsignatur.
- **Plattform:** `orgs`, `users`, `orders`, `jobs`, `deliveries`, `subscriptions`,
`files`, `db_grants`, `payments`, `audit_log`
- Kräver `pgvector` + `pgcrypto`. Belopp i **öre** (integer).
`sql/004_iceberg_write_boundary.sql` + `005_..._gap_closure.sql` lägger till
`opt_dataset_iceberg_mappings` och `opt_source_rate_policies`.
**Migrationskedjan har hål:** `sql/002_*` och `sql/003_*` **saknas i repot** men
refereras av tre filer (`app/api/0pt/sources/[sourceId]/query/route.ts:14`,
`src/services/source-service.ts:8`, `docs/P0_QUERY_SOURCE_FLOW.md:98`) som
"`sql/002_p0_dataset_quality.sql` definierar redan `opt_sources`". Tabellen
`opt_sources` har alltså ingen migration här. Det finns heller ingen
migrationsrunner — SQL:en appliceras manuellt. **OKÄNT** var/om den körts.
### 4.2 Var data faktiskt ligger
| Data | Faktisk lagring i kod |
|---|---|
| Ordrar, jobb, betalningar | `lib/orders-store.ts`: Postgres **om** `getSql()` ger en klient, annars `const mem = new Map()` per instans |
| Sources, datasets, mappningar, rate-policies, dokument, extraktioner, writebacks | `Map` i minnet, en per tjänsteinstans (`src/services/*.ts`, 10 st) |
| Dokumentbytes | R2 om konfigurerat, annars `LocalBlobStore` mot `OPT_LOCAL_BLOB_DIR` |
| Auditspår | AUD0 om `AUD0_URL` satt, annars ingenstans |
Två konsekvenser, båda dokumenterade i koden själv:
1. **Ingen delad state mellan routemoduler.** Varje route-fil instansierar sin
egen tjänst, så en källa registrerad via `POST /api/0pt/sources` är inte
synlig för `POST /api/0pt/sources/{id}/query`. Detta står utskrivet i
route-filens egen kommentar.
2. **Ingen durabilitet.** *(live-verifierat 2026-08-07: `GET /api/0pt/lakehouse/mappings`
och `/api/0pt/sources/rate-policies` svarar `[]`, och `GET /api/health` på
0pt.app rapporterar `"db":"not_configured"`.)* Produktionsinstansen har alltså
**ingen databas** — all state försvinner vid varje kallstart.
### 4.3 Persondata
- `dim_contact`: namn, roll, e-post, telefon, LinkedIn — persondata under GDPR.
- `dim_ubo`: verklig huvudman — persondata, potentiellt känslig.
- `db_grants.conn_encrypted`: kunds DB-anslutningssträng (se §7 S7).
- Dokumentcapture (`app/api/0pt/documents/capture`) tar emot godtyckliga
dokument, inkl. fakturor/mailbilagor via Graph-adaptern — persondata.
### 4.4 Retention
**Ingen retention är implementerad.** `CLAUDE.md` §5 utlovar "deletion-after-job";
inget sådant jobb, ingen TTL, ingen `DELETE`-väg och ingen radering finns i koden.
`audit_log`-tabellen finns men skrivs aldrig av TypeScript-lagret.
---
## 5. Deploy
| Fält | Verifierat läge |
|---|---|
| **Nod** | Ingen SIAX-nod. *(live-verifierat 2026-08-07: `https://0pt.app/api/health` → `Server: Vercel`, `X-Vercel-Id: arn1::iad1::…`)* Frontenden körs alltså på **Vercel**, inte på flottan. |
| **Coolify-app** | Ingen verifierad. `Dockerfile` är skriven för Coolify (node:24-alpine, multistage, `HEALTHCHECK` mot `/api/health`, kör som `node`-användare) men **OKÄNT** om någon Coolify-app pekar på repot. |
| **Domän** | `0pt.app` (live). Docs nämner även `api.0pt.app`, `data.0pt.app`, `dash.0pt.app` via Caddy — **ej verifierade**. |
| **Bygg** | `next build` via pnpm@9. `next.config.mjs` sätter `typescript.ignoreBuildErrors: true` — bygget typkontrollerar alltså **inte** `app/`, `components/`, `lib/` eller `middleware.ts`. |
| **Engine-deploy** | `infra/docker-compose.yml` (postgres, redis, api, worker, nocodb, metabase, caddy) och `services/infra/docker-compose.data-stack.yml` (clickhouse, trino, flaresolverr, tor-proxy, superset, postgres). **Ingen av dem är verifierad som körande.** |
| **Hemligheter** | Rena miljövariabler (`.env.example` listar 20+). **Infisical är inte inkopplat** — ingen referens till Infisical/vault finns i repot. Vercel-projektets env är källan för webblagret. |
| **CI** | `.gitea/workflows/ci.yml`. `quality`-jobb: typecheck (blockerande, endast `src/` + `tests/`), vitest (blockerande, 17 testfiler), eslint (rådgivande), `next build` (blockerande). `security`-jobb: Trivy `--exit-code 0` (rådgivande). Kör på `ubuntu-latest`. |
> **Konflikt att fatta beslut om:** estate-projektet *GCP/Vercel-exit* säger att
> flottan ska bort från Vercel. 0pt:s enda körande instans ligger på Vercel. Se §8.
---
## 6. Drift
### Hälsokontroll
`GET /api/health` → `{ok, service:"0pt-web", db, queue, ts}`. Den svarar **alltid
`ok:true`** oavsett om databasen finns — den rapporterar bara `"not_configured"`
i ett fält. En uptime-monitor som tittar på HTTP 200 kommer därför visa grönt
för en instans utan databas, vilket är exakt vad som gäller idag. Engine har ett
separat `GET /health`.
### Loggar
Ingen strukturerad loggning. `console.warn` i `src/auth/context.ts` är den enda
avsiktliga loggpunkten. Ingen korrelation-id-propagering till logg (ett
`requestId` skapas i `readRequestContext` men loggas aldrig). Ingen
Sentry/GlitchTip/OTel-koppling.
### Backup + senast testad restore
**Ingen backup.** Det finns ingen databas i produktion att säkerhetskopiera
(§4.2), inget backupskript, ingen dumproutine. **Restore har aldrig testats.**
Om/när Postgres provisioneras måste detta lösas separat — jfr estate-blockeraren
"ingen offsite backup".
### Kända fällor
1. **`pnpm install` kräver `--ignore-workspace`.** `pnpm-workspace.yaml` är en
v0-exportartefakt med bara `allowBuilds:` och inget `packages:`-fält, vilket
får pnpm att avbryta. `Dockerfile` skickar flaggan; **`.gitea/workflows/ci.yml`
gör det inte** — CI:s `pnpm install --frozen-lockfile` kan alltså falla på
samma sak som Dockerfilen redan fått ett workaround för. Ej verifierat vilken
pnpm-version som räddar CI idag.
2. **Node-versionsglapp:** CI kör Node 22, Dockerfile bygger på Node 24.
3. **In-memory-state** (§4.2) gör att varje kallstart och varje ny Vercel-lambda
nollställer capability-lagret. Testresultat i CI säger ingenting om detta.
4. `next.config.mjs` sätter `images.unoptimized: true` — inte en bugg, men
förklarar varför bildoptimering saknas.
5. `services/scrapers/output/*.json` innehåller committad skrapdata (brreg-sidor)
i repot.
6. `__pycache__/*.pyc` är committade i `services/`.
---
## 7. Säkerhet
### Vad som faktiskt finns
- **Riktig kryptografisk tokenverifiering.** `src/auth/zitadel.ts` gör äkta
JWKS-baserad `jwtVerify` med issuer-kontroll och `exp`/`nbf` via `jose`.
Tenanthärledning har dokumenterad precedens
(`urn:zitadel:iam:org:id` → `urn:zitadel:iam:user:resourceowner:id` →
`tenant_id` → `tenant`), och ett token utan tenantclaim underkänns.
- **Fail-closed default i koden.** `authEnforced()` returnerar `true` för allt
utom literalen `"false"`, och `assertAuthConfigSafe()` kastar vid
`NODE_ENV=production` + auth av. Designen är korrekt.
- **Stripe-webhooken** verifierar signatur mot `STRIPE_WEBHOOK_SECRET`.
- `SECURITY.md` finns med rapporteringsväg (`security@siax.io`).
### KÄNDA LUCKOR
**S1 — `/api/0pt/*` svarar anonymt i produktion, trots "fail-closed". 🔴**
*(live-verifierat 2026-08-07)* `GET https://0pt.app/api/0pt` returnerar **200**
utan `Authorization`-header. Samma sak med ett medvetet ogiltigt token
(`Bearer aaa.bbb.ccc`) → **200**. `GET /api/0pt/lakehouse/mappings` och
`/api/0pt/sources/rate-policies` returnerar **200 + `[]`** anonymt. Eftersom
lakehouse-routen bara finns i nyare kod är deployen **inte** gammal — middlewaren
kör helt enkelt inte. `README.md` rad 49–52 och merge-commit `6531384`
("make the AUTH_ENFORCE default fail-closed — 0pt.app was answering anonymously")
påstår motsatsen. **Orsaken är OKÄND.** Ej uteslutna hypoteser, ingen verifierad:
(a) `middleware.ts` plockas inte upp av Next 16 i den här filplaceringen när ett
`src/`-träd finns, (b) Vercel-projektet har ingen middleware i sin
build-output, (c) något annat. **Detta måste rotorsaksanalyseras innan repot
beskrivs som skyddat någonstans.**
**S2 — Ingen handler läser den verifierade tenanten. 🔴**
`middleware.ts:56-57` sätter `x-0pt-verified-sub` / `x-0pt-verified-tenant` på
den vidarebefordrade requesten. En grep över hela repot visar att **ingen fil
utanför `middleware.ts` läser de headrarna**. Samtliga `/api/0pt/*`-handlers tar
i stället `tenant_id` från request-body eller querysträng
(`app/api/0pt/sources/[sourceId]/query/route.ts:49`,
`documents/capture/route.ts:27`, `lakehouse/mappings/route.ts:27,49`,
`sources/rate-policies/route.ts:26`, m.fl.). Även med fungerande middleware kan
alltså en innehavare av ett giltigt token för tenant A skicka
`{"tenant_id": "t_b"}` och arbeta i tenant B. Middlewarens 403 vid
`X-Tenant-Id`-konflikt hjälper inte — den kontrollerar bara *headern*, inte
*bodyn*. **Tenantisolering är inte implementerad.**
**S3 — Hela det icke-`/api/0pt`-prefixade API:t saknar auth.**
Matchern täcker bara `/api/0pt/:path*`. Ordrar, adminmetrik, betalningar,
prenumerationer, uppladdningar, AI-parsning och DB-grants är oskyddade i koden.
*(live-verifierat: `GET /api/admin/metrics` och `GET /api/orders` svarar 200
anonymt.)* De är tomma idag enbart för att produktionsinstansen saknar databas.
**S4 — Anonym anropare kan trigga escrow-slutbetalning och flagga leverans.**
`POST /api/payments/{order_id}/release` kräver ingen identitet. Den skapar en
Stripe-checkout på `order.balance_ore` och kör därefter
`setStatus(order_id, "delivered")` **oavsett om betalningen genomförs**.
Statusövergången sker alltså på begäran, inte på betalning. (Skyddas i praktiken
idag bara av att `getOrder` inte hittar något utan databas.)
**S5 — CL0UD-policyklienten är fail-open utan produktionsspärr.**
`src/clients/cl0ud-client.ts:45` — saknas `CL0UD_URL` returneras alltid
`{decision: "allow"}` utan nätanrop. Till skillnad från auth finns **ingen**
`assertAuthConfigSafe`-motsvarighet, ingen `NODE_ENV`-kontroll och ingen varning.
En produktionsdeploy som tappar variabeln godkänner tyst varje
sidoeffektsbärande capability, inklusive Iceberg-writes (L4).
**S6 — AUD0-audit är no-op utan produktionsspärr.**
`src/clients/aud0-client.ts` — saknas `AUD0_URL` skrivs inga auditevent och inga
lineage-event, tyst. Kombinerat med S5 innebär det: inga beslut fattas, inga
spår lämnas. `sql/001_init.sql` har en `audit_log`-tabell som TypeScript-lagret
aldrig skriver till.
**S7 — `db-grant`-routen påstår kryptering som inte finns.**
`app/api/connections/db-grant/route.ts` kommenterar att anslutningssträngen
"lagras KRYPTERAT (AES-GCM via `GRANT_ENC_KEY`), aldrig i klartext". Koden gör
ingenting av detta: utan `GRANT_ENC_KEY` returneras `501`, och **med** nyckeln
returneras ett slumpat `grant_id` — ingen validering av read-only, ingen
kryptering, ingen lagring, ingen audit. Kommentaren beskriver en oimplementerad
funktion i presens.
**S8 — FastAPI-engine har ingen autentisering.**
`services/api/orchestrator/main.py` (12 endpoints, inkl. `POST /orders`,
`PATCH /orders/{oid}`, `POST /orders/{oid}/run`) saknar varje form av
auth-dependency. `lib/engine.ts` skickar `X-Internal-Token`, men servern läser
den aldrig. Var engine än exponeras är den öppen för alla som når porten.
**S9 — Compliance-koden motsäger produktlöftet. 🔴**
`services/scrapers/waf_bypass.py` implementerar FlareSolverr, Tor-rotation,
cloudscraper, TLS-fingerprintbyte, gratis proxypool, "undetected browser"
(nodriver) och "fake identity generation".
`services/infra/docker-compose.data-stack.yml` startar `flaresolverr` och
`tor-proxy`. `services/api/workers/adaptive_router.py` inleds med
`"""Adaptive router — all methods, no compliance restrictions."""`.
Detta står i direkt konflikt med `CLAUDE.md` §1, `README.md` ("Bypass/stealth/
proxy-rotation/fake-account paths are excluded by design") och med hela den
juridiska positionering som säljs på `0pt.app`. Det är samtidigt en
**affärsrisk**: att marknadsföra laglig sourcing medan bypass-kod ligger i repot
är svårt att försvara vid en granskning.
**S10 — Godtycklig anslutningskonfiguration från request-body.**
`POST /api/0pt/sources/{sourceId}/query` tar `connection_config` direkt ur bodyn
och skickar den till adapterbygget (`src/services/source-query-service.ts:95`).
Utan fungerande auth (S1) innebär det att en anonym anropare kan få tjänsten att
öppna utgående anslutningar mot en angiven värd — SSRF-liknande primitiv, och en
väg att låta 0pt-instansen agera proxy.
**S11 — Typkontrollen täcker inte auth-koden.**
`next.config.mjs` sätter `typescript.ignoreBuildErrors: true`, och
`tsconfig.check.json` inkluderar endast `src/**/*.ts` + `tests/**/*.ts`.
**`middleware.ts` ligger i roten och typkontrolleras därför i praktiken inte i
CI** — trots att det är hela authseamen. `eslint` är dessutom rådgivande
(`continue-on-error: true`).
**S12 — Sessions-scaffoldet är svagt.**
`lib/auth.ts` signerar `{email, iat}` med HMAC-SHA256 mot `AUTH_SECRET`, utan
`exp`-kontroll vid verifiering (bara cookiens `maxAge`), utan rotation och utan
bindning till en användarpost. Kommentaren erkänner att det är ett scaffold; det
är ändå den mekanism `GET /api/auth/me` litar på.
---
## 8. Öppna frågor
1. **Varför kör inte middlewaren i produktion (S1)?** Måste rotorsaksanalyseras.
Ingen dokumentation får påstå att `/api/0pt/*` är skyddat innan en anonym
request faktiskt får 401 från `0pt.app`.
2. **Ska `waf_bypass.py`, FlareSolverr och tor-proxy raderas (S9)?**
`CLAUDE.md` säger uttryckligen "remove or disable it". Commit `4a164c5` gick
åt motsatt håll. Detta är ett Simon-beslut med både juridisk och
marknadsföringsmässig innebörd — inte något en session ska avgöra ensidigt.
3. **Vercel eller flottan?** 0pt:s enda körande instans ligger på Vercel medan
estate-projektet *GCP/Vercel-exit* pekar bort därifrån. `Dockerfile` är redan
Coolify-anpassad men ingen nod är tilldelad. `siax.config.json` i det här
repot deklarerar därför `target: "vercel"`, `node: null` — det är dagens
sanning, inte målbilden.
4. **Ska capability-lagret vara i drift alls?** Det är exponerat publikt men helt
in-memory och utan delad state mellan routemoduler (§4.2). Antingen backas det
av Postgres, eller så bör routes stängas tills dess.
5. **Var är `sql/002_*` och `sql/003_*`?** Tre filer refererar dem. Fanns de
någonsin, eller är referenserna aspirationella? `opt_sources` har ingen
migration här.
6. **Ingen databas i produktion.** Är `0pt.app` avsedd att vara en publik
marknadsföringssajt tills vidare, eller är det ett driftfel att
`POSTGRES_URL` aldrig satts? Ordrar som skapas idag försvinner.
7. **`package.json` heter fortfarande `"my-v0-project"`** — v0-exportartefakt.
Byte påverkar inget bygge men bör göras för spårbarhet.
8. **Designsystem:** repot har ett eget dokumenterat mono/editorial-system
(`docs/05-design-system.md`) + shadcn/ui och konsumerar **inte** `@siax/ui`.
Ska 0pt konvergera mot estate-standarden eller är avvikelsen medveten?
`siax.config.json` sätter därför `designSystem: null` snarare än att påstå
något osant.
9. **Tenantmodell:** är en 0pt-tenant 1:1 med en Zitadel-org? Koden antar det i
`deriveTenantId` men det är inte bekräftat mot CL0UD:s tenantregister.
10. **Infisical:** hemligheter ligger i Vercel-env, inte i credential-SSOT.
Behöver bootstrappas.
11. **`GET /api/screen`** proxar mot OpenSanctions utan avtal — kommentaren i
koden säger själv "VERIFY commercial terms before production volume".
12. **Konsumentledet är odokumenterat.** `CLAUDE.md` säger att 0pt matar
Protosell/FiveCRM och VehIQ. Inget i repot visar en sådan integration.
+17 -10
View File
@@ -2,23 +2,30 @@
* `middleware.ts` -- Next.js request middleware = 0pt's framework-level auth
* seam (the Next analog of a Fastify `onRequest` hook).
*
* Wave 2 hardening: this runs the flag-gated Zitadel verification
* (src/auth/context.ts -> src/auth/zitadel.ts) in front of every 0pt
* capability route (/api/0pt/*). It does NOT touch the v0-generated UI routes
* or the unrelated payment/order APIs.
* This runs the Zitadel verification (src/auth/context.ts ->
* src/auth/zitadel.ts) in front of every 0pt capability route (/api/0pt/*).
* It does NOT touch the v0-generated UI routes or the unrelated
* payment/order APIs (see the matcher below and the note in the PR that
* introduced the fail-closed default).
*
* AUTH_ENFORCE != "true" (default): never rejects; if a verified token is
* present the verified principal is forwarded to the handler as
* `x-0pt-verified-sub` / `x-0pt-verified-tenant` request headers.
* AUTH_ENFORCE == "true": a valid verified token is required; 401 on
* missing/invalid, 403 when X-Tenant-Id disagrees with the token tenant.
* AUTH_ENFORCE unset, or anything except "false" (DEFAULT, enforced):
* a valid verified token is required; 401 on missing/invalid, 403 when
* X-Tenant-Id disagrees with the token tenant. On success the verified
* principal is forwarded to the handler as `x-0pt-verified-sub` /
* `x-0pt-verified-tenant` request headers.
* AUTH_ENFORCE == "false" (explicit local-dev escape hatch): never rejects.
* REFUSED in production -- `assertAuthConfigSafe()` below throws at module
* load, so a production instance cannot boot with auth switched off.
*
* Health/metrics are exempt (they are also outside the matcher below, but the
* exemption is kept explicit for robustness).
*/
import { NextResponse, type NextRequest } from 'next/server';
import { resolveAuthContext } from '@/src/auth/context';
import { assertAuthConfigSafe, resolveAuthContext } from '@/src/auth/context';
// STARTUP GATE: fail to boot rather than serve /api/0pt/* openly in production.
assertAuthConfigSafe();
// Only guard the 0pt capability surface. The matcher keeps this middleware off
// the UI, auth, and payment routes entirely.
+6
View File
@@ -0,0 +1,6 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:recommended"
]
}
+17
View File
@@ -0,0 +1,17 @@
{
"name": "0PT",
"category": "PLATTFORM",
"subcategory": "Data OS",
"owner": "SIAX Technology AB",
"packageName": "@siax/0pt",
"capabilityPrefix": "0pt",
"deploy": {
"target": "vercel",
"node": null,
"domain": "0pt.app",
"healthPath": "/api/health"
},
"consumes": ["CL0UD", "AUD0", "ST0RE", "N0D"],
"decoupled": false,
"designSystem": null
}
+92 -26
View File
@@ -3,26 +3,31 @@
* seam the framework layer (Next.js middleware.ts) calls.
*
* ==========================================================================
* WAVE 2 HARDENING STATUS
* AUTH DEFAULT: FAIL-CLOSED
*
* 0pt now performs REAL, cryptographic Zitadel (OIDC) Bearer-token
* verification (src/auth/zitadel.ts), gated behind the AUTH_ENFORCE env flag
* so it can ship to the deployed console WITHOUT breaking existing callers:
* 0pt performs REAL, cryptographic Zitadel (OIDC) Bearer-token verification
* (src/auth/zitadel.ts). Enforcement is controlled by AUTH_ENFORCE, and the
* DEFAULT IS ENFORCED -- an absent, empty, or misspelled value authenticates:
*
* AUTH_ENFORCE != "true" (DEFAULT, non-breaking):
* Preserves the historical behavior (no token was ever required; tenant
* came from the X-Tenant-Id header / request body). ADDITIONALLY, if a
* Bearer token is present and JWT-shaped, we ATTEMPT `verifyBearer` and
* attach the verified principal to the resolved context -- but we NEVER
* reject on failure in this mode (a warning is logged). This lets tokens
* start flowing and being verified with zero caller migration.
*
* AUTH_ENFORCE == "true" (enforced):
* AUTH_ENFORCE unset, or any value except "false" (DEFAULT, enforced):
* REQUIRES a valid, verified token on every non-exempt route. The tenant
* is derived from the TOKEN (not the X-Tenant-Id header). Missing/invalid
* token -> 401 (OPT_UNAUTHENTICATED). If an X-Tenant-Id header is present
* and disagrees with the token's tenant -> 403 (OPT_ACCESS_DENIED).
*
* AUTH_ENFORCE == "false" (explicit local-development escape hatch):
* No token is required; the tenant comes from the X-Tenant-Id header /
* request body. A present, JWT-shaped Bearer token is still best-effort
* verified and attached, but never rejected. This mode is REFUSED in
* production: {@link assertAuthConfigSafe} throws when NODE_ENV=production,
* so an instance that loses (or mis-sets) the variable cannot serve
* openly -- it fails to start, and fails the request, instead.
*
* WHY THE INVERSION: the predicate previously read `AUTH_ENFORCE === 'true'`,
* so every fresh container, local run, DR restore, or redeploy that dropped
* the variable ran with NO authentication at all, and `.env.example` shipped
* `AUTH_ENFORCE=false`. Absence now means enforced.
*
* This module is framework-neutral: it takes a minimal header-lookup (the Web
* `Headers` interface satisfies it, as does Next's `NextRequest.headers`) and
* returns a decision object. It does NOT import next/*, so it is fully
@@ -38,7 +43,7 @@ export interface HeaderLookup {
}
export interface OptRequestContext {
/** Tenant id: from the token in enforce mode, else from X-Tenant-Id header. */
/** Tenant id: from the token when enforced, else from the X-Tenant-Id header. */
tenantId: string;
/** Actor id: from X-Actor-Id header, falling back to the token subject. */
actorId: string;
@@ -61,9 +66,57 @@ export type AuthDecision =
ctx: OptRequestContext;
};
/** True when hard auth enforcement is switched on (AUTH_ENFORCE=="true"). */
export function authEnforced(): boolean {
return process.env.AUTH_ENFORCE === 'true';
/** Name of the environment variable that can switch enforcement off. */
export const AUTH_ENFORCE_VAR = 'AUTH_ENFORCE';
/** The only two environment values this module reads; injectable for tests. */
export interface AuthEnvView {
AUTH_ENFORCE?: string;
NODE_ENV?: string;
}
/**
* Snapshot the auth-relevant environment. `process.env.NODE_ENV` is written
* literally so bundlers (Next's edge compiler) inline it.
*/
function currentEnv(): AuthEnvView {
return { AUTH_ENFORCE: process.env.AUTH_ENFORCE, NODE_ENV: process.env.NODE_ENV };
}
/**
* True unless enforcement was EXPLICITLY disabled with AUTH_ENFORCE="false".
*
* FAIL-CLOSED: unset, empty, "flase", "0", or any other value => ENFORCED.
*/
export function authEnforced(env: AuthEnvView = currentEnv()): boolean {
return env.AUTH_ENFORCE?.trim().toLowerCase() !== 'false';
}
/** Thrown when the process is configured to run without auth in production. */
export class AuthMisconfigurationError extends Error {
constructor(message: string) {
super(message);
this.name = 'AuthMisconfigurationError';
}
}
/**
* Refuse to run open in production. Throws {@link AuthMisconfigurationError}
* when NODE_ENV=production and enforcement resolved to OFF.
*
* Called at module scope by middleware.ts (startup) AND on the env-driven
* request path below, so a misconfigured production instance can neither boot
* nor serve a single unauthenticated request.
*/
export function assertAuthConfigSafe(env: AuthEnvView = currentEnv()): void {
if (env.NODE_ENV === 'production' && !authEnforced(env)) {
throw new AuthMisconfigurationError(
`0pt refuses to run with authentication disabled in production: ` +
`${AUTH_ENFORCE_VAR} is explicitly set to "${env.AUTH_ENFORCE}" while NODE_ENV=production. ` +
`Unset ${AUTH_ENFORCE_VAR} (absent = enforced) or set ${AUTH_ENFORCE_VAR}=true. ` +
`${AUTH_ENFORCE_VAR}=false is a local-development escape hatch only.`,
);
}
}
function firstHeader(headers: HeaderLookup, name: string): string | undefined {
@@ -111,23 +164,34 @@ export interface ResolveAuthOptions {
}
/**
* Resolve and (in enforce mode) enforce the request auth context. Returns an
* {@link AuthDecision}; the caller (middleware) turns a `!ok` decision into an
* HTTP response and an `ok` decision into forwarded principal headers.
* Resolve and (when enforced -- the default) enforce the request auth context.
* Returns an {@link AuthDecision}; the caller (middleware) turns a `!ok`
* decision into an HTTP response and an `ok` decision into forwarded principal
* headers.
*
* Throws {@link AuthMisconfigurationError} when the enforcement decision comes
* from the environment and that environment is "production with auth off".
*/
export async function resolveAuthContext(
headers: HeaderLookup,
opts: ResolveAuthOptions = {},
): Promise<AuthDecision> {
const verify = opts.verify ?? verifyBearer;
const enforce = opts.enforce ?? authEnforced();
let enforce: boolean;
if (opts.enforce !== undefined) {
enforce = opts.enforce;
} else {
// Never serve openly in production, even if the startup check was bypassed.
assertAuthConfigSafe();
enforce = authEnforced();
}
const logger: AuthLogger = opts.logger ?? {
warn: (o, m) => console.warn(m ?? 'auth warning', o),
};
const ctx = readRequestContext(headers);
if (enforce) {
// --- ENFORCED: a valid verified token is mandatory ----------------------
// --- ENFORCED (DEFAULT): a valid verified token is mandatory ------------
if (!ctx.bearerToken) {
return {
ok: false,
@@ -168,19 +232,21 @@ export async function resolveAuthContext(
return { ok: true, ctx };
}
// --- NON-ENFORCE (default): never reject, best-effort verify --------------
// --- EXPLICIT OPT-OUT (AUTH_ENFORCE=false, non-production only) -----------
// Never rejects; a present token is best-effort verified so tokens can start
// flowing in local development.
if (ctx.bearerToken && looksLikeJwt(ctx.bearerToken)) {
try {
const principal = await verify(ctx.bearerToken);
ctx.principal = principal;
// Do NOT overwrite the header/body tenant in non-enforce mode; only
// fill it in when the caller supplied none, to stay non-breaking.
// Do NOT overwrite the header/body tenant in this mode; only fill it in
// when the caller supplied none.
if (!ctx.tenantId) ctx.tenantId = principal.tenantId;
if (!ctx.actorId) ctx.actorId = principal.sub;
} catch (err) {
logger.warn(
{ err: err instanceof Error ? err.message : String(err) },
'0pt: bearer verification failed (AUTH_ENFORCE off, ignoring)',
`0pt: bearer verification failed (${AUTH_ENFORCE_VAR}=false, ignoring)`,
);
}
}
+91 -9
View File
@@ -1,12 +1,24 @@
/**
* Unit tests for src/auth/context.ts `resolveAuthContext` -- the flag-gated
* auth seam. Verification is injected (opts.verify) so these tests are pure
* and network-free; they exercise the decision logic in both AUTH_ENFORCE
* modes.
* Unit tests for src/auth/context.ts -- the auth seam. Verification is
* injected (opts.verify) so these tests are pure and network-free.
*
* Three groups:
* 1. the ENV DEFAULT (the fail-closed contract: absent AUTH_ENFORCE means
* an unauthenticated request is REJECTED, and production refuses to run
* with auth switched off),
* 2. enforced-mode decision logic,
* 3. the explicit `AUTH_ENFORCE=false` local-development escape hatch.
*/
import { describe, it, expect, vi } from 'vitest';
import { resolveAuthContext, type OptRequestContext } from '@/src/auth/context';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
resolveAuthContext,
authEnforced,
assertAuthConfigSafe,
AuthMisconfigurationError,
AUTH_ENFORCE_VAR,
type OptRequestContext,
} from '@/src/auth/context';
import type { VerifiedPrincipal } from '@/src/auth/zitadel';
const principal: VerifiedPrincipal = {
@@ -24,7 +36,77 @@ function h(init: Record<string, string>): Headers {
return new Headers(init);
}
describe('resolveAuthContext -- enforce mode', () => {
describe('auth default -- fail-closed (no AUTH_ENFORCE in the environment)', () => {
const saved = { auth: process.env.AUTH_ENFORCE, node: process.env.NODE_ENV };
beforeEach(() => {
delete process.env.AUTH_ENFORCE;
});
afterEach(() => {
if (saved.auth === undefined) delete process.env.AUTH_ENFORCE;
else process.env.AUTH_ENFORCE = saved.auth;
if (saved.node === undefined) delete process.env.NODE_ENV;
else process.env.NODE_ENV = saved.node;
});
it('REGRESSION: with the variable unset, an unauthenticated request is REJECTED (401)', async () => {
// No `enforce` option -> the decision comes from the environment, which is
// exactly the fresh-container / DR-restore / dropped-env-var case.
const d = await resolveAuthContext(h({ 'x-tenant-id': 'tenant_attacker' }), { verify: okVerify });
expect(d.ok).toBe(false);
if (!d.ok) {
expect(d.status).toBe(401);
expect(d.code).toBe('OPT_UNAUTHENTICATED');
}
});
it('with the variable unset, an invalid token is REJECTED (401) rather than ignored', async () => {
const d = await resolveAuthContext(h({ authorization: 'Bearer bad.tok.en' }), { verify: failVerify });
expect(d.ok).toBe(false);
if (!d.ok) expect(d.status).toBe(401);
});
it('authEnforced() is true when the variable is absent, empty, or misspelled', () => {
expect(authEnforced({})).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: '' })).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: 'flase' })).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: '0' })).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: 'no' })).toBe(true);
expect(authEnforced({ AUTH_ENFORCE: 'true' })).toBe(true);
});
it('only the literal string "false" opts out', () => {
expect(authEnforced({ AUTH_ENFORCE: 'false' })).toBe(false);
expect(authEnforced({ AUTH_ENFORCE: 'FALSE' })).toBe(false);
expect(authEnforced({ AUTH_ENFORCE: ' false ' })).toBe(false);
});
it('assertAuthConfigSafe throws in production when enforcement is off, naming the variable', () => {
expect(() => assertAuthConfigSafe({ NODE_ENV: 'production', AUTH_ENFORCE: 'false' })).toThrow(
AuthMisconfigurationError,
);
expect(() => assertAuthConfigSafe({ NODE_ENV: 'production', AUTH_ENFORCE: 'false' })).toThrow(
new RegExp(AUTH_ENFORCE_VAR),
);
});
it('assertAuthConfigSafe is silent when production enforces, or when off outside production', () => {
expect(() => assertAuthConfigSafe({ NODE_ENV: 'production' })).not.toThrow();
expect(() => assertAuthConfigSafe({ NODE_ENV: 'production', AUTH_ENFORCE: 'true' })).not.toThrow();
expect(() => assertAuthConfigSafe({ NODE_ENV: 'development', AUTH_ENFORCE: 'false' })).not.toThrow();
});
it('a production process with AUTH_ENFORCE=false cannot serve a request at all (throws)', async () => {
process.env.NODE_ENV = 'production';
process.env.AUTH_ENFORCE = 'false';
await expect(
resolveAuthContext(h({ 'x-tenant-id': 'tenant_attacker' }), { verify: okVerify }),
).rejects.toBeInstanceOf(AuthMisconfigurationError);
});
});
describe('resolveAuthContext -- enforced mode (the default)', () => {
it('401s when no bearer token is present', async () => {
const d = await resolveAuthContext(h({ 'x-tenant-id': 'tenant_x' }), { enforce: true, verify: okVerify });
expect(d.ok).toBe(false);
@@ -78,7 +160,7 @@ describe('resolveAuthContext -- enforce mode', () => {
});
});
describe('resolveAuthContext -- non-enforce (default) mode', () => {
describe('resolveAuthContext -- explicit AUTH_ENFORCE=false escape hatch (local dev only)', () => {
it('never rejects when no token is present', async () => {
const d = await resolveAuthContext(h({ 'x-tenant-id': 'tenant_header' }), {
enforce: false,
@@ -111,7 +193,7 @@ describe('resolveAuthContext -- non-enforce (default) mode', () => {
expect(d.ok).toBe(true);
if (d.ok) {
expect(d.ctx.principal).toEqual(principal);
// non-breaking: caller-supplied header tenant is preserved
// the caller-supplied header tenant is preserved in this mode
expect(d.ctx.tenantId).toBe('tenant_header');
}
});