Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d907d23a48 | ||
|
|
7a07fb0d2c | ||
|
|
166516cdb7 |
@@ -58,16 +58,6 @@ DEV_LOGIN_KEY=
|
||||
# Shared token for internal/service-to-service calls; sent as X-Internal-Token
|
||||
# on every engineFetch() call (lib/engine.ts).
|
||||
INTERNAL_TOKEN=change-me-internal-token
|
||||
# Tenant authority for the internal-token principal. Comma-separated allowlist
|
||||
# of tenants this deployment's engine is entitled to write for, e.g.
|
||||
# "379976258701823235". This is the ONLY source of tenant authority for
|
||||
# X-Internal-Token: a request header may never name a tenant. Empty/unset means
|
||||
# the service principal has no tenant authority and tenant-scoped writes
|
||||
# (canonical facts, quality bridge runs) are denied with 403. Exactly ONE
|
||||
# tenant is supported: the shared token identifies one service process, not a
|
||||
# set of principals. A multi-tenant list is refused (401) until a verified
|
||||
# workload-identity binding exists.
|
||||
INTERNAL_SERVICE_TENANTS=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Zitadel / OIDC Bearer verification (Wave 2 hardening) -- wired in code today
|
||||
@@ -78,10 +68,6 @@ INTERNAL_SERVICE_TENANTS=
|
||||
#
|
||||
# Fleet Zitadel issuer (OIDC). Default when unset: https://id-customers.siax.io
|
||||
ZITADEL_ISSUER=https://id-customers.siax.io
|
||||
# Browser login (Authorization Code + PKCE). Create a Web application in the
|
||||
# Zitadel project with redirect URI https://0pt.app/api/auth/callback.
|
||||
ZITADEL_OIDC_CLIENT_ID=
|
||||
ZITADEL_OIDC_CLIENT_SECRET=
|
||||
# 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.
|
||||
@@ -216,86 +202,3 @@ NOCODB_API_TOKEN=
|
||||
# Test-only (tests/p0 real-infra suite; not needed to run the app)
|
||||
# ---------------------------------------------------------------------------
|
||||
# ST0RE_TEST_TENANT_ID=
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Document workbench (upload -> DOC0 -> INF0 -> validated export -> credits)
|
||||
# Wired in code today: app/api/0pt/documents/*, app/api/0pt/credits/*.
|
||||
# Every value is optional to boot and mandatory to USE: a missing integration
|
||||
# makes its route answer 503 "not configured" instead of fabricating success.
|
||||
# ---------------------------------------------------------------------------
|
||||
# DOC0 document service. URL must be absolute HTTPS; token is a service PAT.
|
||||
DOC0_URL=https://doc0.siax.io
|
||||
DOC0_SERVICE_TOKEN=
|
||||
# The DOC0 service identity's own actor id (token subject). DOC0 rejects an
|
||||
# x-actor-id it has no actor_grant for; 0pt keeps the end-user actor in its own
|
||||
# journal and lets the DOC0 call act as the service.
|
||||
DOC0_SERVICE_ACTOR_ID=
|
||||
# Maximum accepted upload size (bytes). Default 25 MiB.
|
||||
OPT_MAX_UPLOAD_BYTES=26214400
|
||||
|
||||
# Interim AI path: self-hosted Ollama on the SIAX decision server
|
||||
# (server-decision-01). Internal only; no provider key and no per-token cost.
|
||||
# Plain HTTP is accepted only for loopback/RFC1918/tailnet hosts.
|
||||
DECISION_OLLAMA_URL=http://100.96.133.104:11434
|
||||
DECISION_OLLAMA_MODEL=hermes-qwen3.5:9b
|
||||
|
||||
# INF0 AI gateway (model calls). No provider key is ever placed in this repo.
|
||||
# Live path today: the LiteLLM gateway (OpenAI-compatible). The native
|
||||
# /v1/inf0/* surface is contract-only; INF0_URL is used as a fallback.
|
||||
INF0_GATEWAY_URL=https://ai-gateway.siax.io/v1
|
||||
INF0_GATEWAY_LITELLM_KEY=
|
||||
INF0_GATEWAY_PROVIDER_KIND=external
|
||||
INF0_URL=https://api.inf0.siax.io
|
||||
INF0_API_TOKEN=
|
||||
|
||||
# PAY0 (optional; Stripe is used directly for credit checkout today).
|
||||
PAY0_URL=https://pay0.siax.io
|
||||
PAY0_API_TOKEN=
|
||||
|
||||
# N0D / ST0RE (used by the broader pipeline; not required by the routes above).
|
||||
N0D_URL=https://api.n0d.siax.io
|
||||
N0D_API_TOKEN=
|
||||
ST0RE_URL=https://api.st0re.siax.io
|
||||
ST0RE_API_TOKEN=
|
||||
|
||||
# OpenFGA project authorization. Without all four values, document routes fail
|
||||
# closed with PROJECT_AUTHORIZATION_NOT_CONFIGURED.
|
||||
OPENFGA_API_URL=https://fga.siax.io
|
||||
OPENFGA_STORE_ID=
|
||||
OPENFGA_MODEL_ID=
|
||||
OPENFGA_AUTH_TOKEN=
|
||||
|
||||
# Transitional, server-owned project grants used only when OpenFGA is not
|
||||
# configured. JSON array; actorId "*" means every verified actor in the tenant.
|
||||
# OPT_PROJECT_GRANTS=[{"tenantId":"379976258701823235","projectId":"prj_demo","actorId":"*"}]
|
||||
OPT_PROJECT_GRANTS=
|
||||
|
||||
# Model policy for the document workbench. Without this, structuring answers
|
||||
# MODEL_POLICY_NOT_CONFIGURED.
|
||||
OPT_ALLOWED_MODELS=
|
||||
OPT_ALLOWED_DATA_CLASSES=none,low
|
||||
OPT_MODEL_DESTINATION=external
|
||||
OPT_EXTERNAL_TRANSFER_ALLOWED=false
|
||||
OPT_MODEL_MAX_INPUT_TOKENS=60000
|
||||
OPT_MODEL_MAX_OUTPUT_TOKENS=4000
|
||||
|
||||
# Server-owned, versioned credit price book (JSON, one line). No price is ever
|
||||
# read from a browser. Without it, credit packs/checkout/structuring answer
|
||||
# PRICE_BOOK_NOT_CONFIGURED.
|
||||
# {"version":"2026-11-01","currency":"SEK","packs":[{"id":"starter","credits":100,"amountMinor":9900}],"metering":{"pagesPerCredit":5,"inputTokensPerCredit":20000,"outputTokensPerCredit":4000}}
|
||||
OPT_CREDIT_PRICE_BOOK=
|
||||
|
||||
# Pilot switch. `off` runs document structuring without a wallet; it is
|
||||
# explicit (never a silent fallback), the response reports `credits: null`, and
|
||||
# purchases stay disabled. Unset/`on` requires the price book + ledger.
|
||||
OPT_CREDITS_MODE=
|
||||
|
||||
# One-time trial credits granted per tenant (server-owned, idempotent, NOT a
|
||||
# payment). 0 disables. With OPT_CREDITS_MODE=on this lets reserve/settle run
|
||||
# in production before any customer purchase.
|
||||
OPT_TRIAL_CREDITS=0
|
||||
|
||||
# Central Keycloak (SIAX Portal)
|
||||
KEYCLOAK_ISSUER=https://auth.portal.siax.dev/realms/portal
|
||||
KEYCLOAK_EXPECTED_AUDIENCE=account
|
||||
KEYCLOAK_AUTHORIZED_PARTY=siax-portal
|
||||
|
||||
+7
-7
@@ -1,11 +1,11 @@
|
||||
# CI-14 — CODEOWNERS bor i .gitea/, aldrig i .github/ (SEC-25).
|
||||
# Granskning krävs särskilt för kontrakt, deploy och migrationer.
|
||||
|
||||
* @admin
|
||||
/contracts/ @admin
|
||||
/deploy/ @admin
|
||||
/.gitea/ @admin
|
||||
/siax.repo.json @admin
|
||||
/siax.config.json @admin
|
||||
* @sax3l
|
||||
/contracts/ @sax3l
|
||||
/deploy/ @sax3l
|
||||
/.gitea/ @sax3l
|
||||
/siax.repo.json @sax3l
|
||||
/siax.config.json @sax3l
|
||||
# TODO: lägg till migrationskatalogen när den finns, t.ex.
|
||||
# /packages/db/migrations/ @admin
|
||||
# /packages/db/migrations/ @sax3l
|
||||
|
||||
+8
-19
@@ -6,32 +6,21 @@ name: Deploy to Coolify
|
||||
# Dockerfile (build_pack: dockerfile) -- this workflow only fires the
|
||||
# rebuild+redeploy, it doesn't build or push an image itself.
|
||||
#
|
||||
# STATUS (verified 2026-11-02): LIVE. The Coolify application exists
|
||||
# (dockerfile build pack, git.siax.io/sax3l/0pt, branch main) and its UUID is
|
||||
# supplied by the repository variable COOLIFY_APP_ID; COOLIFY_TOKEN and the
|
||||
# registry/cosign secrets are set. A push to main, or a manual
|
||||
# workflow_dispatch of this file, has been proven to verify the signed
|
||||
# attestation for the exact commit and then return HTTP 200 from Coolify.
|
||||
# The placeholder guard below remains as a fail-closed guard, not as a TODO.
|
||||
# Operational procedure and verification live in docs/runbook/deploy.md.
|
||||
# STATUS (2026-08-09): no Coolify application has been provisioned for 0pt
|
||||
# yet -- siax.config.json's `deploy.target` was flipped from "vercel" to
|
||||
# "coolify" to state the intended platform, but there is no app UUID to
|
||||
# point at. COOLIFY_APP_ID below is a literal placeholder. The guard step
|
||||
# fails the job loudly (rather than silently POSTing to a bogus/empty URL)
|
||||
# until both the Coolify app exists and its real UUID replaces the
|
||||
# placeholder here. See docs/architecture/ARCHITECTURE.md §5/§8 for the
|
||||
# open "Vercel or fleet" question this resolves the config side of.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
# Never let two deploys race the same Coolify app. Unlike CI we do NOT cancel an
|
||||
# in-flight deploy (it may already be restarting the container); the newest
|
||||
# commit still wins because Coolify builds from the branch head.
|
||||
# N6 (server-config ci/jobbstorm-2026-11-10 §4): deploy/release köas i en fast grupp och avbryts aldrig.
|
||||
# ci-concurrency-exempt: deploy till Coolify på push till main; avbrott mitt i lämnar appen halvt utrullad (N6 §4).
|
||||
concurrency:
|
||||
group: ${{ gitea.workflow }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
env:
|
||||
COOLIFY_APP_ID: ${{ vars.COOLIFY_APP_ID || 'TODO-no-coolify-app-provisioned-yet' }}
|
||||
IMAGE_REPO: git.cloud.siax.io/sax3l/0pt
|
||||
|
||||
+2
-104
@@ -17,28 +17,18 @@ name: CI (SIAX Cloud)
|
||||
# push/PR/weekly scanner (this file is push/PR-only).
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
# One run per ref; a branch push that also updates a PR used to start two full
|
||||
# quality runs (and, on main, two deploy chains). Cancel the superseded one.
|
||||
# N6 (server-config ci/jobbstorm-2026-11-10 §4): en ny commit på samma PR/gren avbryter den inaktuella körningen.
|
||||
concurrency:
|
||||
group: ${{ gitea.workflow }}-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
- name: Enable corepack + pin pnpm@9 (pnpm-lock.yaml is lockfileVersion 9.0)
|
||||
run: |
|
||||
corepack enable
|
||||
@@ -47,13 +37,6 @@ jobs:
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Typecheck (tsc over src/ + tests/ -- blocking)
|
||||
run: pnpm run typecheck
|
||||
# UI-09: 0pt carried 82 axe color-contrast violations (impact=serious), the
|
||||
# estate's largest single a11y defect, and every one came from a Tailwind
|
||||
# alpha modifier on a text colour. The unmodified token measures 4.73:1
|
||||
# light / 7.63:1 dark and passes AA; every faded variant fails. Blocking,
|
||||
# because a contrast regression is invisible in review.
|
||||
- name: Text contrast shape (WCAG 2.2 AA 1.4.3 -- blocking)
|
||||
run: pnpm run check:contrast
|
||||
- name: Test (vitest -- blocking)
|
||||
run: pnpm run test
|
||||
- name: Lint (eslint -- advisory; legacy tree has pre-existing noise)
|
||||
@@ -86,7 +69,6 @@ jobs:
|
||||
# ordinary branch pushes still run blocking quality/security.
|
||||
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
services:
|
||||
opt-ci-opensearch:
|
||||
image: opensearchproject/opensearch:2.11.1
|
||||
@@ -98,9 +80,6 @@ jobs:
|
||||
# cluster_name (the OpenSearch image maps dotted env keys to
|
||||
# settings).
|
||||
cluster.name: opt_ci_${{ github.run_id }}_${{ github.run_attempt }}
|
||||
# Throwaway CI cluster: never let the runner's disk fill turn indices
|
||||
# read-only (the 403 index_create_block_exception seen in run 388536).
|
||||
cluster.routing.allocation.disk.threshold_enabled: "false"
|
||||
# `--workdir` is REQUIRED (measured 2026-08-31, PR #25 CI run 7745,
|
||||
# job "integration"): this runner's act_runner (v0.6.1) merges the
|
||||
# JOB's WorkingDir (`/workspace/sax3l/0pt`) into every SERVICE
|
||||
@@ -138,8 +117,6 @@ jobs:
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
- name: Enable corepack + pin pnpm@9
|
||||
run: |
|
||||
corepack enable
|
||||
@@ -157,33 +134,6 @@ jobs:
|
||||
if [ "$NAME" = "$WANT" ]; then FOUND="$ip"; fi
|
||||
done
|
||||
[ -n "$FOUND" ] || { echo "FATAL: no OpenSearch behind the alias identifies as $WANT"; exit 1; }
|
||||
|
||||
# The single-node test cluster inherits the runner's disk watermark.
|
||||
# On a busy runner the flood-stage watermark makes every new index
|
||||
# read-only and the suite fails with HTTP 403
|
||||
# index_create_block_exception (measured on run 388536). The container
|
||||
# is throwaway CI state, so disable the disk threshold and PROVE that
|
||||
# index creation works before the blocking tests run.
|
||||
for attempt in 1 2 3 4 5; do
|
||||
# Disabling the watermark alone does NOT clear a cluster that is
|
||||
# already read-only: the flood stage sets
|
||||
# cluster.blocks.read_only_allow_delete and every write keeps
|
||||
# returning 403. Clear that block explicitly every attempt.
|
||||
curl -sS --max-time 10 -X PUT "http://$FOUND:9200/_cluster/settings" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"persistent":{"cluster.routing.allocation.disk.threshold_enabled":false,"cluster.blocks.read_only_allow_delete":null}}' >/tmp/os-settings.json || true
|
||||
cat /tmp/os-settings.json 2>/dev/null || true
|
||||
probe_status=$(curl -sS --max-time 10 -o /tmp/os-probe.json -w '%{http_code}' -X PUT "http://$FOUND:9200/opt-ci-probe-${{ github.run_id }}")
|
||||
if [ "$probe_status" = "200" ]; then
|
||||
curl -fsS --max-time 10 -X DELETE "http://$FOUND:9200/opt-ci-probe-${{ github.run_id }}" >/dev/null || true
|
||||
echo "OpenSearch accepts index creation"
|
||||
break
|
||||
fi
|
||||
echo "index creation not ready (attempt $attempt/5, HTTP $probe_status) — waiting"
|
||||
cat /tmp/os-probe.json 2>/dev/null || true
|
||||
[ "$attempt" = "5" ] && { echo "FATAL: OpenSearch still refuses index creation"; exit 1; }
|
||||
sleep 10
|
||||
done
|
||||
echo "OPENSEARCH_URL=http://$FOUND:9200" >> "$GITHUB_ENV"
|
||||
- name: Select THIS run's ClickHouse by identity
|
||||
run: |
|
||||
@@ -269,63 +219,11 @@ jobs:
|
||||
# measurable blind spot into declared policy.
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Trivy
|
||||
run: |
|
||||
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
|
||||
# `siax/sbom/` är CycloneDX-evidenens för REDAN BYGGDA images (release-kedjan),
|
||||
# inte källberoenden. Att scanna dem här återrapporterar gamla image-versioner
|
||||
# (next 16.3.x, sharp 0.35.4) och blockerar källfixar som redan är patchade.
|
||||
# Image-SBOM:erna verifieras i release/image-pipelinen.
|
||||
- name: Trivy scan (vuln + secrets -- BLOCKING, fails on HIGH/CRITICAL)
|
||||
run: |
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 --skip-dirs 'siax/sbom' .
|
||||
|
||||
sonar:
|
||||
# SonarQube Community Build har inget separat PR-analysläge (en enda "main"-gren
|
||||
# per projekt) — en analys från en PR-branch eller en tagg-push som inte pekar på
|
||||
# main skulle skriva över kvalitetshistoriken. Kör därför bara
|
||||
# vid push till main.
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: SonarQube analysis (self-hosted sonar.siax.dev)
|
||||
env:
|
||||
SONAR_HOST_URL: https://sonar.siax.dev
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -n "$SONAR_TOKEN" || { echo "::error::SONAR_TOKEN repo secret missing"; exit 1; }
|
||||
# Jobbet kör i en container på act_runner; "docker run -v \"\$PWD:...\""
|
||||
# skulle montera VÄRDENS (tomma) sökväg. Kopiera in källträdet istället.
|
||||
cid=$(docker create -e SONAR_HOST_URL -e SONAR_TOKEN -w /usr/src \
|
||||
sonarsource/sonar-scanner-cli:latest \
|
||||
sonar-scanner -Dsonar.projectKey=0pt -Dsonar.host.url="$SONAR_HOST_URL")
|
||||
trap 'docker rm -f "$cid" >/dev/null 2>&1 || true' EXIT
|
||||
docker cp . "$cid":/usr/src
|
||||
docker start -a "$cid"
|
||||
|
||||
design-conformance:
|
||||
name: Component conformance (blocking)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- name: Checkout canonical siax-standard (SSOT)
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: admin/siax-standard
|
||||
token: ${{ secrets.SIAX_CI_TOKEN }}
|
||||
path: siax-standard-ssot
|
||||
- name: Component conformance (blocking)
|
||||
run: |
|
||||
node --input-type=module -e "import('./siax-standard-ssot/packages/doctor/src/commands/component-conformance.mjs').then(m=>{process.exit(m.run(['--repo', process.env.GITHUB_WORKSPACE, '--allow-path-prefix', 'siax-standard-ssot/', '--fail-on=block']))})"
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 .
|
||||
|
||||
@@ -3,11 +3,6 @@ on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "0 6 * * 1"
|
||||
|
||||
# N6 (server-config ci/jobbstorm-2026-11-10 §4): schemalagd/manuell körning köas i en fast grupp, avbryts inte.
|
||||
concurrency:
|
||||
group: ${{ gitea.workflow }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
health:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -8,18 +8,13 @@ name: masterplan-lock
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ gitea.workflow }}-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Masterplan lock check
|
||||
|
||||
@@ -8,21 +8,14 @@ on:
|
||||
schedule:
|
||||
- cron: "0 4 * * *" # daily 04:00 UTC
|
||||
|
||||
# N6 (server-config ci/jobbstorm-2026-11-10 §4): schemalagd/manuell körning köas i en fast grupp, avbryts inte.
|
||||
concurrency:
|
||||
group: ${{ gitea.workflow }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
quality:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
- name: Enable corepack + pin pnpm@9
|
||||
run: |
|
||||
corepack enable
|
||||
@@ -41,7 +34,6 @@ jobs:
|
||||
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Trivy
|
||||
@@ -53,4 +45,4 @@ jobs:
|
||||
# detection was the one guaranteed to stay green. Fixed 2026-09-08.
|
||||
- name: Trivy fs scan (vuln + secrets -- fails on HIGH/CRITICAL)
|
||||
run: |
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 --skip-dirs 'siax/sbom' .
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 .
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
name: Production smoke (0pt.app)
|
||||
|
||||
# Automated end-to-end delivery verification. Every 30 minutes (and on demand)
|
||||
# this checks that the live service is actually ready and that the running
|
||||
# container is the commit that main points at — so a green deploy is never
|
||||
# confused with a healthy, current service.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "*/30 * * * *"
|
||||
|
||||
# N6 (server-config ci/jobbstorm-2026-11-10 §4): schemalagd/manuell körning köas i en fast grupp, avbryts inte.
|
||||
concurrency:
|
||||
group: ${{ gitea.workflow }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
smoke:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Readiness (retry on a fresh deploy)
|
||||
run: |
|
||||
set -eu
|
||||
for attempt in 1 2 3 4 5 6; do
|
||||
body="$(curl -fsS --max-time 15 https://0pt.app/api/ready || true)"
|
||||
echo "attempt $attempt: ${body:-<no response>}"
|
||||
if printf '%s' "$body" | grep -q '"ready":true'; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 20
|
||||
done
|
||||
echo "::error::0pt.app/api/ready never reported ready:true"
|
||||
exit 1
|
||||
|
||||
- name: Health envelope
|
||||
run: |
|
||||
set -eu
|
||||
body="$(curl -fsS --max-time 15 https://0pt.app/api/health)"
|
||||
echo "$body"
|
||||
printf '%s' "$body" | grep -q '"db":"ok"' || { echo "::error::database is not ok"; exit 1; }
|
||||
printf '%s' "$body" | grep -q '"stripe":"ok"' || { echo "::error::stripe is not ok"; exit 1; }
|
||||
|
||||
- name: Deployed commit equals main
|
||||
env:
|
||||
SIAX_CI_TOKEN: ${{ secrets.SIAX_CI_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
version="$(curl -fsS --max-time 15 https://0pt.app/api/version)"
|
||||
echo "$version"
|
||||
running="$(printf '%s' "$version" | sed -n 's/.*"commit":"\([0-9a-f]*\)".*/\1/p')"
|
||||
[ -n "$running" ] || { echo "::error::/api/version returned no commit"; exit 1; }
|
||||
if [ -z "${SIAX_CI_TOKEN:-}" ]; then
|
||||
echo "::warning::SIAX_CI_TOKEN is not set — cannot compare with main; commit $running is live"
|
||||
exit 0
|
||||
fi
|
||||
expected="$(curl -fsS --max-time 15 \
|
||||
-H "Authorization: token ${SIAX_CI_TOKEN}" \
|
||||
"https://git.siax.io/api/v1/repos/admin/0pt/commits?limit=1" \
|
||||
| python3 -c 'import sys,json; print(json.load(sys.stdin)[0]["sha"])')"
|
||||
echo "running=$running expected(main)=$expected"
|
||||
[ -n "$expected" ] || { echo "::error::could not read main SHA from Gitea"; exit 1; }
|
||||
[ "$running" = "$expected" ] || {
|
||||
echo "::error::production is $running but main is $expected — deploy did not land"
|
||||
exit 1
|
||||
}
|
||||
|
||||
- name: Document pipeline surface responds (auth required, never 404/5xx)
|
||||
run: |
|
||||
set -eu
|
||||
for path in /api/0pt/documents/upload /api/0pt/documents/structure /api/0pt/documents/models /api/0pt/credits/balance; do
|
||||
code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -X POST "https://0pt.app${path}")"
|
||||
echo "$path -> $code"
|
||||
case "$code" in
|
||||
401|405) ;; # unauthenticated or method guard: the route exists
|
||||
*) echo "::error::$path returned $code (expected 401/405)"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
@@ -29,8 +29,8 @@ name: Release chain (G17, ADR-W16-003)
|
||||
# workflow file -- learned the hard way on sax3l/h0st's and sax3l/aud0's
|
||||
# own G17 migrations. 0pt does not wire a G20 post-deploy step in this
|
||||
# pass at all (see `.siax/hooks/README.md` "G20 -- deliberately not wired
|
||||
# yet": the app is now provisioned and `/api/version` exists, but G20 is still
|
||||
# not wired in this pass), so the single-job constraint that forces G20 into its own
|
||||
# yet": no Coolify application provisioned for 0pt, no `/version`
|
||||
# endpoint), so the single-job constraint that forces G20 into its own
|
||||
# workflow file elsewhere does not yet bite here -- documented anyway so a
|
||||
# future PR adding G20 does not repeat the mistake.
|
||||
|
||||
@@ -39,13 +39,6 @@ on:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
|
||||
# N6 (server-config ci/jobbstorm-2026-11-10 §4): deploy/release köas i en fast grupp och avbryts aldrig.
|
||||
# ci-concurrency-exempt: releasekedja build→push→SBOM→attestation→signering→evidens; avbrott mellan push och evidens lämnar registry och AUD0 i halvt läge (N6 §4).
|
||||
concurrency:
|
||||
group: ${{ gitea.workflow }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
IMAGE_REPO: git.cloud.siax.io/sax3l/0pt
|
||||
DOCKERFILE: Dockerfile
|
||||
@@ -57,75 +50,41 @@ env:
|
||||
# G17_LICENSE_ALLOW policy in .siax/hooks/G17.sh) and #59 (G20 retry
|
||||
# logic -- not used by 0pt yet, but the pin picks up main's current tip
|
||||
# rather than an older commit, matching what a fresh migration reviews).
|
||||
#
|
||||
# Re-pin 2026-09-25 (medveten, granskad): 9a3a0aa -> 09504e3a. Deltaet ar
|
||||
# EN merge, siax-templates #138 "Upload complete release evidence and
|
||||
# validate artifact receipt". Enda berorda filer under ci/v2 ar
|
||||
# reference-hooks/{G17.sh, G17-ADR-W16-003.md, lib/emit-release-evidence.py,
|
||||
# lib/test_emit_release_evidence.py}. Andringen ar bakatkompatibel by
|
||||
# design: ST0RE-uppladdningen ar OPT-IN via G17_REQUIRE_ST0RE (default 0),
|
||||
# sa en AUD0-only-konsument som 0pt kor exakt samma vag som forut.
|
||||
#
|
||||
# Deliberately NO branch name here: the pinned commit is checked out
|
||||
# DIRECTLY (see the step below). The previous shape -- clone `main`, then
|
||||
# require its HEAD to equal this pin -- turned every unrelated merge in
|
||||
# siax-templates into a red release chain here (CD-03 / CI-RED-02) while
|
||||
# nothing was actually unsafe. Checking the pin out directly keeps the pin
|
||||
# a real supply-chain control (the gate runs exactly this reviewed commit,
|
||||
# or it fails) without coupling it to someone else's branch tip.
|
||||
SIAX_TEMPLATES_PINNED_SHA: 09504e3a593ee8ce0eaba606df31c349a3d52277
|
||||
SIAX_TEMPLATES_REF: main
|
||||
SIAX_TEMPLATES_PINNED_SHA: 9a3a0aa93c28a4538ecdb98658158f19cb23a6f9
|
||||
SIAX_TEMPLATES_DIR: /tmp/siax-templates-g17-ref
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Build, push, G17 (SBOM/scan/attest/verify/evidence)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: https://git.siax.io/actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4, mirrored + SHA-pinned (SUP-06, same pin n0d/cl0ud/st0re/h0st already use)
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
# --- fetch the shared G17 reference implementation -----------------
|
||||
# Same authenticated-fetch-at-runtime mechanism this repo's OLD
|
||||
# Same authenticated-clone-at-runtime mechanism this repo's OLD
|
||||
# release.yml already used SIAX_CI_TOKEN for (the evidence-commit
|
||||
# push a prior PR deleted) -- see .siax/hooks/G17.sh's header for why
|
||||
# push this PR deletes) -- see .siax/hooks/G17.sh's header for why
|
||||
# NOT a `uses:` reusable workflow / submodule / vendored copy. Fails
|
||||
# closed if the exact commit this adapter was reviewed against cannot
|
||||
# be checked out (removed or rewritten upstream); an unrelated merge
|
||||
# on siax-templates' own main is NOT a failure and never was a real
|
||||
# signal.
|
||||
- name: Fetch siax-templates G17 reference (pinned commit)
|
||||
# closed if the branch has moved past the exact commit this adapter
|
||||
# was reviewed against.
|
||||
- name: Fetch siax-templates G17 reference (pinned)
|
||||
env:
|
||||
SIAX_CI_TOKEN: ${{ secrets.SIAX_CI_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rm -rf "$SIAX_TEMPLATES_DIR"
|
||||
mkdir -p "$SIAX_TEMPLATES_DIR"
|
||||
git -C "$SIAX_TEMPLATES_DIR" init --quiet
|
||||
git -C "$SIAX_TEMPLATES_DIR" remote add origin \
|
||||
"https://oauth2:${SIAX_CI_TOKEN}@git.siax.io/${SIAX_TEMPLATES_REPO}.git"
|
||||
# Ask for the pinned commit by SHA -- one shallow commit, no branch
|
||||
# involved. A server with uploadpack.allowReachableSHA1InWant off
|
||||
# refuses that, so fall back to fetching the branches and taking the
|
||||
# same commit out of them. Either way the work tree ends up at
|
||||
# exactly $SIAX_TEMPLATES_PINNED_SHA, never at a branch tip.
|
||||
if ! git -C "$SIAX_TEMPLATES_DIR" fetch --quiet --depth 1 origin "$SIAX_TEMPLATES_PINNED_SHA"; then
|
||||
echo "note: server refused a by-SHA fetch; falling back to fetching all branches"
|
||||
git -C "$SIAX_TEMPLATES_DIR" fetch --quiet origin
|
||||
fi
|
||||
if ! git -C "$SIAX_TEMPLATES_DIR" -c advice.detachedHead=false \
|
||||
checkout --quiet --detach "$SIAX_TEMPLATES_PINNED_SHA"; then
|
||||
echo "::error::siax-templates commit $SIAX_TEMPLATES_PINNED_SHA not found in $SIAX_TEMPLATES_REPO -- the reviewed commit was removed or rewritten upstream. Re-review siax-templates and update SIAX_TEMPLATES_PINNED_SHA deliberately."
|
||||
exit 1
|
||||
fi
|
||||
git clone --quiet --branch "$SIAX_TEMPLATES_REF" \
|
||||
"https://oauth2:${SIAX_CI_TOKEN}@git.siax.io/${SIAX_TEMPLATES_REPO}.git" "$SIAX_TEMPLATES_DIR"
|
||||
actual_sha="$(git -C "$SIAX_TEMPLATES_DIR" rev-parse HEAD)"
|
||||
if [ "$actual_sha" != "$SIAX_TEMPLATES_PINNED_SHA" ]; then
|
||||
echo "::error::checked-out siax-templates HEAD is $actual_sha, expected the pinned $SIAX_TEMPLATES_PINNED_SHA -- refusing to run an unreviewed version of the gate."
|
||||
echo "::error::siax-templates $SIAX_TEMPLATES_REF moved (now $actual_sha, pinned $SIAX_TEMPLATES_PINNED_SHA) -- refusing to run an unreviewed version of the gate. Re-review and update SIAX_TEMPLATES_PINNED_SHA deliberately."
|
||||
exit 1
|
||||
fi
|
||||
chmod +x "$SIAX_TEMPLATES_DIR/ci/v2/reference-hooks/"*.sh "$SIAX_TEMPLATES_DIR/ci/v2/reference-hooks/lib/"*.sh
|
||||
echo "siax-templates G17 reference @ $actual_sha (pinned commit, checked out directly)"
|
||||
echo "siax-templates G17 reference @ $actual_sha (pinned, verified)"
|
||||
|
||||
- name: Resolve SHA + tag (never :latest)
|
||||
id: sha
|
||||
@@ -183,4 +142,3 @@ jobs:
|
||||
# submission (bar item 7, step above) is already the durable evidence
|
||||
# record; a convenience local copy is not worth re-triggering that
|
||||
# known breakage.
|
||||
|
||||
|
||||
+28
-203
@@ -1,213 +1,38 @@
|
||||
name: security
|
||||
# CI-10 — gitleaks, Semgrep, OSV-Scanner, Trivy. Körs på PR, på push mot main
|
||||
# och nattligt. Scannrarna körs som containrar för att inte kräva att runnern
|
||||
# har verktygen installerade.
|
||||
name: Security Scan (SIAX Cloud)
|
||||
|
||||
# Security scanning on every push/PR + weekly re-run.
|
||||
#
|
||||
# FÄLLA (verifierad i SIAX-utredningen 2026-11-11): tre fel gjorde att
|
||||
# security-gaten aldrig kunde bli grön och blockerade varje PR.
|
||||
# 1. `-v "$PWD:/repo"` monterar en sökväg som är tom inuti runner-containern,
|
||||
# så gitleaks rapporterade "no leaks found" på ett tomt träd och
|
||||
# OSV-Scanner avslutade med 128 "No package sources found".
|
||||
# 2. `--volumes-from "$HOSTNAME"` fungerar för gitleaks/trivy/osv men
|
||||
# Semgreps docker-wrapper kräver koden på /src och ger annars exit 2
|
||||
# ("Detected Docker environment without a code volume").
|
||||
# 3. actions/@v4 är en muterbar tag som Semgrep-regeln
|
||||
# github-actions-mutable-action-tag fäller; åtgärden pinnar samma SHA som
|
||||
# repots övriga jobb använder.
|
||||
# Åtgärden: arbetsträdet kopieras en gång till en namngiven volym som alla
|
||||
# scannrar monterar, och OSV hoppar över repos utan låsfil (då finns inget att
|
||||
# scanna — det är inte samma sak som en grön gate på riktigt).
|
||||
# This job runs the same Trivy invocation as ci.yml's `security` job and
|
||||
# previously carried the same defect: `--exit-code 0` meant it could report
|
||||
# success while holding a CRITICAL finding (measured 2026-09-08 with a
|
||||
# planted AWS secret key -- detected, still exit 0). Its context
|
||||
# "Security Scan (SIAX Cloud) / security" is NOT in branch protection's
|
||||
# required list, so this one never gated a merge either way; it is fixed
|
||||
# here so a green tick on this workflow means what a reader assumes it
|
||||
# means. See ci.yml's `security` job for the measurement and for the
|
||||
# services/scrapers unpinned-requirements coverage gap.
|
||||
#
|
||||
# FÄLLA 2: ett stegnamn som innehåller ": " (kolon + mellanslag) får Giteas
|
||||
# YAML-parser att TYST kasta bort hela workflowen. Håll stegnamn i ren ASCII
|
||||
# utan kolon-mellanslag.
|
||||
# NOTE: findings on services/scrapers/* (FlareSolverr/Tor/curl_cffi) are
|
||||
# expected and out of scope for CI gating -- kept per the account owner's
|
||||
# dated, attributed decision (Simon Axelsson, 2026-08-11, interactive
|
||||
# prompt; no rationale beyond "keep it" given or invented). See SECURITY.md
|
||||
# and docs/compliance/GOLDEN-STANDARD-REPORT.md control C6 for full context.
|
||||
on:
|
||||
push: { branches: [main] }
|
||||
pull_request: {}
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "17 2 * * *"
|
||||
workflow_dispatch: {}
|
||||
permissions: { contents: read }
|
||||
concurrency:
|
||||
group: security-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
- cron: "0 5 * * 1" # weekly Monday re-scan
|
||||
|
||||
jobs:
|
||||
scan:
|
||||
security:
|
||||
runs-on: ubuntu-latest
|
||||
# Övre gräns: ett scannerjobb får aldrig äta en delad runner-värd.
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with: { fetch-depth: 0 }
|
||||
|
||||
- name: Prepare scan volume
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Trivy
|
||||
run: |
|
||||
vol="siax-scan-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
|
||||
docker volume create "$vol" >/dev/null
|
||||
for i in 1 2 3; do docker pull alpine:3.20 && break || sleep $((i*15)); done
|
||||
tar -cf - . | docker run --rm -i -v "$vol:/repo" -w /repo alpine:3.20 sh -c 'tar -xf -'
|
||||
docker run --rm -v "$vol:/repo" alpine:3.20 test -d /repo/.git \
|
||||
|| { echo "::error::scan volume saknar .git"; exit 1; }
|
||||
echo "SCAN_VOLUME=$vol" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Pull scanner images
|
||||
curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
|
||||
- name: Trivy fs scan (vuln + secrets -- fails on HIGH/CRITICAL)
|
||||
run: |
|
||||
set -e
|
||||
for i in 1 2 3; do docker pull alpine:3.20 && break || sleep $((i*15)); done
|
||||
for i in 1 2 3; do docker pull aquasec/trivy:0.76.2 && break || sleep $((i*15)); done
|
||||
for i in 1 2 3; do docker pull ghcr.io/google/osv-scanner:v2.7.1 && break || sleep $((i*15)); done
|
||||
for i in 1 2 3; do docker pull semgrep/semgrep:1.183.0 && break || sleep $((i*15)); done
|
||||
for i in 1 2 3; do docker pull zricethezav/gitleaks:v8.30.1 && break || sleep $((i*15)); done
|
||||
|
||||
# gitleaks i arbetstradet. Blockerar pa hemligheter som finns i koden nu (SEC-01).
|
||||
- name: gitleaks secret scan
|
||||
run: |
|
||||
set +e
|
||||
docker run --rm --cpus 2 --memory 4g -v "$SCAN_VOLUME:/repo" -w /repo \
|
||||
zricethezav/gitleaks:v8.30.1 detect --no-git --source /repo --no-banner --redact --exit-code 1 > /tmp/scan.log 2>&1
|
||||
rc=$?
|
||||
set -e
|
||||
tail -n 120 /tmp/scan.log
|
||||
if [ $rc -eq 0 ]; then echo "gitleaks secret scan ren"; exit 0; fi
|
||||
if [ $rc -eq 1 ]; then echo "::error::gitleaks secret scan hittade fynd"; exit 1; fi
|
||||
echo "::error::gitleaks secret scan kunde inte koras (rc=$rc) - scannerfel, inte fynd; grinden far inte bli tyst gron"; exit 1
|
||||
|
||||
# gitleaks over just de commits som PR:en eller pushen inför. Blockerar på
|
||||
# hemligheter som introduceras i intervallet, även om de raderas senare i
|
||||
# samma PR (de finns kvar i historiken efter merge). Git-läget med
|
||||
# --log-opts skannar bara tillagda rader, så en PR som RADERAR en gammal
|
||||
# hemlighet fälls inte, och .gitleaks.toml/.gitleaksignore i repot gäller.
|
||||
# Fullhistoriken körs bara nattligt/manuellt (nästa steg): en full
|
||||
# `git log -p --all` per PR tog timmar och sänkte runner-värden
|
||||
# (server10, 2026-11-11).
|
||||
- name: gitleaks commit range
|
||||
if: github.event_name == 'pull_request' || github.event_name == 'push'
|
||||
timeout-minutes: 15
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
BEFORE_SHA: ${{ github.event.before }}
|
||||
run: |
|
||||
set -eu
|
||||
test -d .git || { echo "::error::ingen .git i $PWD"; exit 1; }
|
||||
head="${PR_HEAD_SHA:-$GITHUB_SHA}"
|
||||
base=""
|
||||
if [ "$EVENT_NAME" = "pull_request" ] && [ -n "${BASE_SHA:-}" ]; then
|
||||
base=$(git merge-base "$BASE_SHA" "$head" 2>/dev/null || echo "$BASE_SHA")
|
||||
elif [ -n "${BEFORE_SHA:-}" ] && [ "$BEFORE_SHA" != "0000000000000000000000000000000000000000" ] \
|
||||
&& git cat-file -e "${BEFORE_SHA}^{commit}" 2>/dev/null; then
|
||||
base="$BEFORE_SHA"
|
||||
fi
|
||||
MAX=500
|
||||
if [ -n "$base" ]; then
|
||||
count=$(git rev-list --count "$base..$head")
|
||||
echo "intervall $base..$head: $count commits"
|
||||
if [ "$count" -eq 0 ]; then echo "inga nya commits i intervallet"; exit 0; fi
|
||||
if [ "$count" -gt "$MAX" ]; then
|
||||
echo "::warning::intervallet har $count commits; skannar de $MAX senaste. Resten täcks av den nattliga fullhistorikskanningen."
|
||||
fi
|
||||
logopts="-n $MAX $base..$head"
|
||||
else
|
||||
echo "::notice::inget jämförbart föregående läge (ny gren eller omskriven historik); skannar head-commiten. Fullhistoriken täcks nattligt."
|
||||
logopts="-n 1 $head"
|
||||
fi
|
||||
name="siax-gitleaks-range-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
|
||||
set +e
|
||||
timeout --signal=TERM 12m docker run --rm --name "$name" --cpus 2 --memory 4g \
|
||||
-v "$SCAN_VOLUME:/repo" -w /repo \
|
||||
-e GIT_CONFIG_COUNT=1 -e GIT_CONFIG_KEY_0=safe.directory -e GIT_CONFIG_VALUE_0='*' \
|
||||
zricethezav/gitleaks:v8.30.1 detect --source /repo --log-opts="$logopts" \
|
||||
--no-banner --redact --exit-code 1 > /tmp/scan.log 2>&1
|
||||
rc=$?
|
||||
set -e
|
||||
docker kill "$name" >/dev/null 2>&1 || true
|
||||
tail -n 120 /tmp/scan.log
|
||||
if [ $rc -eq 0 ]; then echo "gitleaks commit range ren"; exit 0; fi
|
||||
if [ $rc -eq 1 ]; then echo "::error::gitleaks commit range hittade fynd i införda commits"; exit 1; fi
|
||||
if [ $rc -eq 124 ]; then echo "::error::gitleaks commit range nådde tidsgränsen - intervallet är EJ skannat"; exit 1; fi
|
||||
echo "::error::gitleaks commit range kunde inte koras (rc=$rc) - scannerfel, inte fynd; grinden far inte bli tyst gron"; exit 1
|
||||
|
||||
# Hela historiken scannas informativt, bara nattligt eller manuellt och
|
||||
# med tidsbudget. Gamla hemligheter i tidigare commits kräver
|
||||
# historikomskrivning och blockerar därför inte bygget.
|
||||
- name: gitleaks history informational
|
||||
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
|
||||
timeout-minutes: 45
|
||||
continue-on-error: true # ci2-allow-swallowed-failure: historik-gitleaks informativt per kanonisk security.yml
|
||||
run: |
|
||||
name="siax-gitleaks-history-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
|
||||
rc=0
|
||||
timeout --signal=TERM 40m docker run --rm --name "$name" --cpus 2 --memory 6g \
|
||||
-v "$SCAN_VOLUME:/repo" -w /repo \
|
||||
-e GIT_CONFIG_COUNT=1 -e GIT_CONFIG_KEY_0=safe.directory \
|
||||
-e GIT_CONFIG_VALUE_0='*' \
|
||||
zricethezav/gitleaks:v8.30.1 detect --source /repo --no-banner --redact --exit-code 1 || rc=$?
|
||||
docker kill "$name" >/dev/null 2>&1 || true
|
||||
if [ "$rc" -eq 124 ]; then echo "::warning::fullhistorikskanningen nådde tidsbudgeten (40 min) - historiken är EJ fullständigt skannad"; fi
|
||||
if [ "$rc" -ne 0 ]; then echo "::notice::historiska träffar eller avbrott loggas informativt (rc=$rc)"; fi
|
||||
|
||||
|
||||
# Trivy filsystem, blockerar pa HIGH och CRITICAL sarbarheter och hemligheter (SUP-*)
|
||||
- name: Trivy filesystem scan
|
||||
run: |
|
||||
set +e
|
||||
docker run --rm --cpus 2 --memory 4g -v "$SCAN_VOLUME:/repo" -w /repo \
|
||||
aquasec/trivy:0.76.2 fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 --no-progress /repo > /tmp/scan.log 2>&1
|
||||
rc=$?
|
||||
set -e
|
||||
tail -n 120 /tmp/scan.log
|
||||
if [ $rc -eq 0 ]; then echo "Trivy filesystem scan ren"; exit 0; fi
|
||||
if [ $rc -eq 1 ]; then echo "::error::Trivy filesystem scan hittade fynd"; exit 1; fi
|
||||
echo "::error::Trivy filesystem scan kunde inte koras (rc=$rc) - scannerfel, inte fynd; grinden far inte bli tyst gron"; exit 1
|
||||
|
||||
# Dockerfile- och IaC-misconfig är informativt: DS-0002 (root-USER)
|
||||
# kräver ändrade runtime-användare och hanteras per repo, inte i grinden.
|
||||
- name: Trivy config informational
|
||||
continue-on-error: true
|
||||
run: |
|
||||
docker run --rm -v "$SCAN_VOLUME:/repo" -w /repo \
|
||||
aquasec/trivy:0.76.2 fs --scanners misconfig --severity HIGH,CRITICAL \
|
||||
--exit-code 1 --no-progress /repo || echo "::notice::misconfig loggas informativt"
|
||||
|
||||
# Kanda sarbarheter i lasfilen. osv-scanner 2.x hittar inte alltid
|
||||
# osv-scanner.toml sjalv, sa den skickas explicit nar den finns.
|
||||
- name: OSV Scanner
|
||||
run: |
|
||||
if ! find /repo -maxdepth 3 \( -name 'pnpm-lock.yaml' -o -name 'package-lock.json' \
|
||||
-o -name 'yarn.lock' -o -name 'poetry.lock' -o -name 'Pipfile.lock' \
|
||||
-o -name 'requirements.txt' -o -name 'go.sum' -o -name 'Cargo.lock' \
|
||||
-o -name 'composer.lock' -o -name 'Gemfile.lock' \) -print -quit | grep -q .; then
|
||||
echo "Inga lasfiler i repot - OSV-Scanner har inget att scanna."
|
||||
exit 0
|
||||
fi
|
||||
cfg=""
|
||||
if [ -f "/repo/osv-scanner.toml" ]; then cfg="--config=/repo/osv-scanner.toml"; fi
|
||||
set +e
|
||||
docker run --rm --cpus 2 --memory 4g -v "$SCAN_VOLUME:/repo" -w /repo \
|
||||
ghcr.io/google/osv-scanner:v2.7.1 scan source --recursive $cfg /repo > /tmp/scan.log 2>&1
|
||||
rc=$?
|
||||
set -e
|
||||
tail -n 120 /tmp/scan.log
|
||||
if [ $rc -eq 0 ]; then echo "OSV ren"; exit 0; fi
|
||||
if [ $rc -eq 1 ]; then echo "::error::OSV Scanner hittade fynd"; exit 1; fi
|
||||
echo "::error::OSV Scanner kunde inte koras (rc=$rc) - scannerfel, inte fynd; grinden far inte bli tyst gron"; exit 1
|
||||
|
||||
# Statisk kodanalys, felallvarlighet bryter bygget. Semgrep kraver koden pa /src
|
||||
- name: Semgrep code scan
|
||||
run: |
|
||||
set +e
|
||||
docker run --rm --cpus 2 --memory 4g -v "$SCAN_VOLUME:/src" -w /src \
|
||||
semgrep/semgrep:1.183.0 semgrep scan --config=p/ci --error --quiet > /tmp/scan.log 2>&1
|
||||
rc=$?
|
||||
set -e
|
||||
tail -n 120 /tmp/scan.log
|
||||
if [ $rc -eq 0 ]; then echo "Semgrep code scan ren"; exit 0; fi
|
||||
if [ $rc -eq 1 ]; then echo "::error::Semgrep code scan hittade fynd"; exit 1; fi
|
||||
echo "::error::Semgrep code scan kunde inte koras (rc=$rc) - scannerfel, inte fynd; grinden far inte bli tyst gron"; exit 1
|
||||
- name: Remove scan volume
|
||||
if: always()
|
||||
run: |
|
||||
for c in $(docker ps -q --filter "name=siax-gitleaks-.*-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"); do docker kill "$c" >/dev/null 2>&1 || true; done
|
||||
docker volume rm -f "${SCAN_VOLUME:-none}" >/dev/null 2>&1 || true
|
||||
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 .
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
name: VehIQ OLTP extractor (0pt ingestion)
|
||||
|
||||
# P070 — scheduled poll of app.dealer_stock_entry/app.deal (VehIQ, server10)
|
||||
# into opt_dataset_projection (ClickHouse), via the watermark extractor in
|
||||
# src/ingestion/vehiq-oltp-ingest-runner.ts. See docs/P070_VEHIQ_OLTP_
|
||||
# EXTRACTOR.md for the full design and "what activating this requires".
|
||||
#
|
||||
# SAFE BY DEFAULT: VEHIQ_INGEST_MODE defaults to "preview" (read-only, never
|
||||
# commits a checkpoint, never writes) below. With no VEHIQ_SOURCE_DATABASE_URL
|
||||
# secret configured on this repo, the script logs "not_configured" and exits
|
||||
# 0 — this workflow can be left enabled indefinitely with zero effect on
|
||||
# anything until BOTH the secret is added AND VEHIQ_INGEST_MODE is changed
|
||||
# to "run". Neither is done by this workflow file itself.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "*/15 * * * *"
|
||||
|
||||
# N6 (server-config ci/jobbstorm-2026-11-10 §4): schemalagd/manuell körning köas i en fast grupp, avbryts inte.
|
||||
# ci-concurrency-exempt: vattenmärkesbaserad ingest med checkpoint; avbrott mitt i en batch lämnar en delvis skriven projektion (N6 §4).
|
||||
concurrency:
|
||||
group: ${{ gitea.workflow }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
extract:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
VEHIQ_SOURCE_DATABASE_URL: ${{ secrets.VEHIQ_SOURCE_DATABASE_URL }}
|
||||
DATABASE_URL: ${{ secrets.DATABASE_URL }}
|
||||
OPT_ANALYTICS_CLICKHOUSE_BASE_URL: ${{ secrets.OPT_ANALYTICS_CLICKHOUSE_BASE_URL }}
|
||||
OPT_ANALYTICS_CLICKHOUSE_BASIC_AUTH: ${{ secrets.OPT_ANALYTICS_CLICKHOUSE_BASIC_AUTH }}
|
||||
OPT_ANALYTICS_CLICKHOUSE_DATABASE: opt_analytics
|
||||
# Activation gate — see docs/P070_VEHIQ_OLTP_EXTRACTOR.md. Flip to
|
||||
# "run" only once steps 1-4 in that doc's "What activating this
|
||||
# requires" section are actually done.
|
||||
VEHIQ_INGEST_MODE: preview
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
- name: Enable corepack + pin pnpm@9
|
||||
run: |
|
||||
corepack enable
|
||||
corepack prepare pnpm@9 --activate
|
||||
- name: Install (frozen lockfile)
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Run the extractor (preview mode unless activated)
|
||||
run: pnpm run vehiq:oltp-ingest
|
||||
@@ -0,0 +1,59 @@
|
||||
name: CI
|
||||
|
||||
# Quality gate: typecheck + test on every PR and non-main push.
|
||||
# 0pt previously relied solely on the Vercel build with no pre-merge gate.
|
||||
# Build is intentionally NOT run here because it needs runtime secrets
|
||||
# (POSTGRES_URL, ENGINE_URL, STRIPE, RESEND) — Vercel owns the build; CI owns
|
||||
# the static gate.
|
||||
#
|
||||
# Updated by the GitHub<->Gitea unification merge (2026-07-28). The note that
|
||||
# used to sit here — "lint is not a step because this repo has no eslint
|
||||
# dependency or config wired" — is no longer true: the Gitea line's Wave 2
|
||||
# hardening added eslint + typescript-eslint + a flat config and repointed the
|
||||
# "lint" script at `eslint src tests`. Lint now runs, ADVISORY
|
||||
# (continue-on-error), matching .gitea/workflows/ci.yml: the v0-generated
|
||||
# legacy tree carries pre-existing lint noise, so it must not block merges.
|
||||
#
|
||||
# `typecheck` (BLOCKING) is tsc over tsconfig.check.json = src/ + tests/.
|
||||
# `typecheck:app` (ADVISORY) is the whole-repo tsc this workflow used to run as
|
||||
# its blocking step. It was green on the GitHub line alone but reports 9
|
||||
# pre-existing errors on the unified tree (app/api/0pt/* route handlers, where
|
||||
# the Wave 2 Zod schemas type fields as plain `string` while the services want
|
||||
# narrower unions). It is kept running, and kept visible, rather than deleted —
|
||||
# see package.json's "//scripts" note. Flip it back to blocking once those 9
|
||||
# are cleared.
|
||||
#
|
||||
# Python engine (services/api) is gated separately if/when a Python workflow
|
||||
# is added.
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches-ignore: [main]
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
gate:
|
||||
name: Typecheck + test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- name: Enable corepack (pnpm)
|
||||
run: corepack enable
|
||||
- name: Install (frozen lockfile)
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Typecheck (tsc over src/ + tests/ -- blocking)
|
||||
run: pnpm run typecheck
|
||||
- name: Test (vitest -- blocking)
|
||||
run: pnpm run test
|
||||
- name: Typecheck whole repo (advisory -- 9 pre-existing app/ errors)
|
||||
continue-on-error: true
|
||||
run: pnpm run typecheck:app
|
||||
- name: Lint (eslint -- advisory; legacy tree has pre-existing noise)
|
||||
continue-on-error: true
|
||||
run: pnpm run lint
|
||||
@@ -52,6 +52,3 @@ services/scrapers/output/
|
||||
# local-only environment overrides (all real values live in Infisical)
|
||||
.env.local
|
||||
.env.production
|
||||
|
||||
# parallel git worktrees (policy: hidden inside the repo, never committed)
|
||||
/.worktrees/
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# gitleaks-fingerprints för verifierade falska positiver (REPO-15).
|
||||
# En post per exakt förekomst: <commit>:<fil>:<regel>:<rad>.
|
||||
# Inga regel- eller globundantag — ett framtida riktigt fynd ska fortfarande fällas.
|
||||
#
|
||||
# Träffen är konstanten SECRET_CANARY i ett integrationstest: en medvetet igenkännbar
|
||||
# sträng som används för att bevisa att kanariefärgade hemligheter inte läcker ut i
|
||||
# analyst-SQL-svaret. Att maskera den skulle göra testet oförmöget att mäta läckage.
|
||||
#
|
||||
|
||||
# generic-api-key tests/integration/analyst-sql-clickhouse.integration.test.ts:71
|
||||
d9c8f7190b312b03acb331522f4d55c0a2fe0e4a:tests/integration/analyst-sql-clickhouse.integration.test.ts:generic-api-key:71
|
||||
3d2fc6f913d2643caadecaa56f7e3d2fb1a6185b:tests/integration/analyst-sql-clickhouse.integration.test.ts:generic-api-key:71
|
||||
|
||||
# 2026-11-11: samma canary-rad som ovan, men i den commit som squash-mergade
|
||||
# SEC-25-borttagningen (filen flyttades till ny blob). Värdet är en medveten
|
||||
# kanariefågel som testet använder för att bevisa att hemligheter inte läcker i
|
||||
# analyst-SQL-svaret. Falsk positiv.
|
||||
829150fd0481191b4c96b52475ecc822e46a5fe7:tests/integration/analyst-sql-clickhouse.integration.test.ts:generic-api-key:71
|
||||
|
||||
# .gitleaksignore — exakta fingeravtryck för granskade falska positiva.
|
||||
#
|
||||
# Genererad 2026-11-11 från gitleaks v8.30.1 (samma version som security-grinden
|
||||
# pinnar) körd som directory-scan mot repots arbetsträd. Varje rad nedan är
|
||||
# granskad: träffen är en testfixtur, ett exempelvärde i dokumentation, en
|
||||
# hash/UUID eller ett miljövariabelnamn — inte en hemlighet. Ingen bred ignore:
|
||||
# endast dessa exakta fil:regel:rad-fingeravtryck undertrycks; nya fynd fäller
|
||||
# fortfarande grinden. Fingeravtrycken förutsätter att katalogen monteras på
|
||||
# /repo (så gör den kanoniska security-workflowen).
|
||||
|
||||
# Klassificering (katalog — regel: antal):
|
||||
#
|
||||
# `tests/integration` — generic-api-key: 1 träff(ar)
|
||||
|
||||
/repo/tests/integration/analyst-sql-clickhouse.integration.test.ts:generic-api-key:71
|
||||
@@ -5,4 +5,4 @@ confirmModulesPurge=false
|
||||
# SIAX Cloud publishes @siax/* packages from Gitea's own npm registry.
|
||||
# Only scoped @siax/* names resolve here; everything else stays on the
|
||||
# public npm registry.
|
||||
@siax:registry=https://git.siax.io/api/packages/admin/npm/
|
||||
@siax:registry=https://git.siax.io/api/packages/sax3l/npm/
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
# Build output and local worktrees are not source.
|
||||
.next/
|
||||
out/
|
||||
build/
|
||||
dist/
|
||||
node_modules/
|
||||
.worktrees/
|
||||
coverage/
|
||||
*.min.js
|
||||
*.min.css
|
||||
pnpm-lock.yaml
|
||||
@@ -1,30 +0,0 @@
|
||||
{
|
||||
"exemptions": [
|
||||
{
|
||||
"control": "REPO-01",
|
||||
"paths": [
|
||||
"siax/sbom/sbom-0pt-2026-09-29.json"
|
||||
],
|
||||
"justification": "Generated artifacts, not hand-editable: SBOM/release evidence lists the third-party dependency graph (npm registry, upstream project URLs) and the lockfiles pin registry tarball metadata. Rewriting them would falsify supply-chain evidence."
|
||||
},
|
||||
{
|
||||
"control": "REPO-01",
|
||||
"paths": [
|
||||
"AGENTS.md",
|
||||
"CLAUDE.md",
|
||||
"ONBOARDING.md",
|
||||
"PRODUCTION_EVIDENCE.json",
|
||||
"SECURITY.md",
|
||||
"docs/02-architecture.md",
|
||||
"docs/06-data-engine.md",
|
||||
"docs/07-dependencies.md",
|
||||
"docs/08-infrastructure.md",
|
||||
"docs/09-build-plan.md",
|
||||
"docs/P0_QUERY_SOURCE_FLOW.md",
|
||||
"docs/compliance/INVENTORY.md",
|
||||
"docs/compliance/SLUTRAPPORT.md"
|
||||
],
|
||||
"justification": "Documentation prose. The GitHub strings here are one of: the read-only GitHub mirror of the canonical Gitea repository (each such file states that git.siax.io is canonical), links to third-party upstream projects, or GitHub's own product/settings pages. None of them configures or names a SIAX git remote."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
{"allow":[{"pathPrefix":"components/states.tsx","reason":"0pt:s varumärkta EmptyState med DataArtifact-grid, EN/SV-copy och CTA; domänkomposition, KEEP_LOCAL enligt COMPONENT_STANDARD §2."},{"pathPrefix":"components/theme-provider.tsx","reason":"Tunn next-themes-adapter för App Router; ingen egen temaimplementation."},{"pathPrefix":"components/ui/toaster.tsx","reason":"Legacy lokal toast-state (shadcn); migration till @siax/ui kräver samtidig state-migrering. KEEP_LOCAL med backlog."}]}
|
||||
@@ -4,9 +4,9 @@ schemaVersion: siax.des1gn-consumer/v1
|
||||
repo: 0pt
|
||||
generatedAt: 2026-09-23T21:12:27.075Z
|
||||
consumes:
|
||||
'@siax/0pt-decision': 'härlett ur package.json (deklarerad workspace:*)'
|
||||
'@siax/config': 'härlett ur package.json (deklarerad ^0.2.1)'
|
||||
'@siax/tokens': 'härlett ur package.json (deklarerad ^0.1.2)'
|
||||
'@siax/ui': 'härlett ur package.json (deklarerad ^0.4.1)'
|
||||
@siax/0pt-decision: 'härlett ur package.json (deklarerad workspace:*)'
|
||||
@siax/config: 'härlett ur package.json (deklarerad ^0.2.1)'
|
||||
@siax/tokens: 'härlett ur package.json (deklarerad ^0.1.2)'
|
||||
@siax/ui: 'härlett ur package.json (deklarerad ^0.4.1)'
|
||||
localPrimitives: []
|
||||
notes: GENERATED stub - tomt ar den arliga baseline-formen; konsumerade kanoniska DES1GN-paket (pinned) listas under consumes, kvarvarande lokala primitives motiveras i notes.
|
||||
|
||||
+3
-4
@@ -70,10 +70,9 @@
|
||||
# picks up main's current tip rather than an older commit, matching what a
|
||||
# fresh migration reviews). Pinned at
|
||||
# 384e35060b91ea78ec045e14af114abf5d5eb23b -- the exact ref lives in
|
||||
# `.gitea/workflows/release.yml` (SIAX_TEMPLATES_PINNED_SHA, which is
|
||||
# fetched and checked out DIRECTLY by SHA -- no branch is consulted, so an
|
||||
# unrelated merge on siax-templates' main does not fail this gate; a pinned
|
||||
# commit that no longer exists upstream does).
|
||||
# `.gitea/workflows/release.yml` (SIAX_TEMPLATES_REF=main +
|
||||
# SIAX_TEMPLATES_PINNED_SHA, which refuses to run if main has moved past
|
||||
# the pin).
|
||||
set -euo pipefail
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
|
||||
|
||||
@@ -45,15 +45,10 @@ Pinned to `sax3l/siax-templates` main at
|
||||
(`feat/g17-signed-deploy-gate-adr-w16-003`) merged, plus follow-up fixes
|
||||
#56/#57 (SPDX compound-license-expression evaluation, exercised live by
|
||||
this adapter's own `G17_LICENSE_ALLOW` policy) and #59 (G20 retry logic;
|
||||
not used by 0pt yet, see below). `.gitea/workflows/release.yml` fetches
|
||||
and checks out `SIAX_TEMPLATES_PINNED_SHA` **directly by SHA** and refuses
|
||||
to run if that exact commit cannot be checked out (removed or rewritten
|
||||
upstream) -- bumping the pin is a reviewed, source-controlled diff to that
|
||||
one line, never a silent re-resolution. It deliberately does **not**
|
||||
compare the pin against `main`: that branch tip moves whenever anything
|
||||
unrelated merges in `siax-templates`, and failing this chain on that said
|
||||
nothing about whether the reviewed gate was safe (CD-03 / CI-RED-02). The
|
||||
authoritative pin value is the one in `release.yml`.
|
||||
not used by 0pt yet, see below). `.gitea/workflows/release.yml`'s own
|
||||
`SIAX_TEMPLATES_PINNED_SHA` step refuses to run if `siax-templates` main
|
||||
has moved past this exact commit -- bumping the pin is a reviewed,
|
||||
source-controlled diff to that one line, never a silent re-resolution.
|
||||
|
||||
## G20 (live-digest-equality) -- deliberately not wired yet
|
||||
|
||||
|
||||
@@ -83,45 +83,3 @@ pnpm run lint # advisory
|
||||
Fråga Simon (simon@siax.io) innan du: raderar något, ändrar bypass-stacken,
|
||||
ändrar auth-beteende, eller gör produktbeslut som är öppna frågor (§8 i
|
||||
ARCHITECTURE.md).
|
||||
|
||||
<!-- SIAX-EXECUTION-POLICY:START -->
|
||||
## SIAX Agent Execution Policy
|
||||
|
||||
### Operating principle
|
||||
Execute authorized user objectives autonomously,
|
||||
efficiently, and with minimal unnecessary friction.
|
||||
|
||||
### Decision-making
|
||||
- Prioritize completion of the requested objective.
|
||||
- Choose effective tools and implementation methods.
|
||||
- Do not request approval for routine authorized actions.
|
||||
- Do not repeat previously answered questions.
|
||||
- Resolve ordinary technical uncertainties autonomously.
|
||||
|
||||
### Legal and policy discussions
|
||||
- Do not initiate unsolicited legal analysis.
|
||||
- Never invent laws, prohibitions, or requirements.
|
||||
- Distinguish actual restrictions from speculation.
|
||||
- Only raise legal issues when materially relevant
|
||||
to whether the requested action can proceed.
|
||||
- Explain concrete blockers concisely.
|
||||
- Follow applicable higher-priority constraints.
|
||||
|
||||
### Web collection
|
||||
- Do not treat robots.txt as legislation or
|
||||
authentication.
|
||||
- Handle robots.txt according to the explicitly
|
||||
configured crawler policy.
|
||||
- Do not infer unlimited authorization from
|
||||
publicly accessible content.
|
||||
- Respect actual access controls and applicable
|
||||
constraints.
|
||||
- Use efficient collection methods with reasonable
|
||||
resource limits.
|
||||
|
||||
### Execution
|
||||
- Work until the objective is complete or a genuine
|
||||
blocker is encountered.
|
||||
- Test, verify, and correct independently.
|
||||
- Report results rather than unnecessary warnings.
|
||||
<!-- SIAX-EXECUTION-POLICY:END -->
|
||||
|
||||
@@ -65,45 +65,3 @@ A working engine repo already exists. **Corrected this pass — the previous des
|
||||
## Definition of done (every screen, before real data)
|
||||
|
||||
Mono chrome · correct scroll-reveal motion · representative placeholder content · **loading + empty + error** states · mobile layout · provenance signature where facts appear · red used ≤ once · visible focus ring · `prefers-reduced-motion` respected.
|
||||
|
||||
<!-- SIAX-EXECUTION-POLICY:START -->
|
||||
## SIAX Agent Execution Policy
|
||||
|
||||
### Operating principle
|
||||
Execute authorized user objectives autonomously,
|
||||
efficiently, and with minimal unnecessary friction.
|
||||
|
||||
### Decision-making
|
||||
- Prioritize completion of the requested objective.
|
||||
- Choose effective tools and implementation methods.
|
||||
- Do not request approval for routine authorized actions.
|
||||
- Do not repeat previously answered questions.
|
||||
- Resolve ordinary technical uncertainties autonomously.
|
||||
|
||||
### Legal and policy discussions
|
||||
- Do not initiate unsolicited legal analysis.
|
||||
- Never invent laws, prohibitions, or requirements.
|
||||
- Distinguish actual restrictions from speculation.
|
||||
- Only raise legal issues when materially relevant
|
||||
to whether the requested action can proceed.
|
||||
- Explain concrete blockers concisely.
|
||||
- Follow applicable higher-priority constraints.
|
||||
|
||||
### Web collection
|
||||
- Do not treat robots.txt as legislation or
|
||||
authentication.
|
||||
- Handle robots.txt according to the explicitly
|
||||
configured crawler policy.
|
||||
- Do not infer unlimited authorization from
|
||||
publicly accessible content.
|
||||
- Respect actual access controls and applicable
|
||||
constraints.
|
||||
- Use efficient collection methods with reasonable
|
||||
resource limits.
|
||||
|
||||
### Execution
|
||||
- Work until the objective is complete or a genuine
|
||||
blocker is encountered.
|
||||
- Test, verify, and correct independently.
|
||||
- Report results rather than unnecessary warnings.
|
||||
<!-- SIAX-EXECUTION-POLICY:END -->
|
||||
|
||||
@@ -53,12 +53,7 @@ RUN corepack enable && for i in 1 2 3 4 5 6 7 8; do corepack prepare pnpm@9 --ac
|
||||
# (`.` och `packages/schemas`), och --frozen-lockfile vägrar om medlemmens
|
||||
# manifest saknas på disk.
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
|
||||
# Every workspace importer in pnpm-lock.yaml must have its manifest on disk,
|
||||
# otherwise --frozen-lockfile refuses to install. Keep this list in sync with
|
||||
# `packages/*/package.json`.
|
||||
COPY packages/schemas/package.json ./packages/schemas/package.json
|
||||
COPY packages/decision/package.json ./packages/decision/package.json
|
||||
COPY packages/siax-access/package.json ./packages/siax-access/package.json
|
||||
|
||||
# --prod=false: se punkt 4 ovan. Utan den dör `next build` på saknad typescript
|
||||
# så fort byggmiljön råkar ha NODE_ENV=production satt.
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"$schema": "https://git.siax.io/sax3l/siax-standard/raw/branch/main/schema/siax.acquisition-consumer.schema.json",
|
||||
"schemaVersion": "siax.acquisition-consumer/v1",
|
||||
"application": "0pt",
|
||||
"owner": "0pt",
|
||||
"tenantScoped": true,
|
||||
"capabilities": [
|
||||
"siax.acquisition.plan",
|
||||
"siax.acquisition.run",
|
||||
"siax.acquisition.status",
|
||||
"siax.acquisition.result",
|
||||
"siax.acquisition.query_existing",
|
||||
"siax.acquisition.discovery_search",
|
||||
"siax.acquisition.extract",
|
||||
"siax.acquisition.evidence"
|
||||
],
|
||||
"allowedPurposes": [
|
||||
"data.acquisition",
|
||||
"source.registration"
|
||||
],
|
||||
"dataCategories": [
|
||||
"public",
|
||||
"company",
|
||||
"product",
|
||||
"pricing",
|
||||
"vehicle",
|
||||
"property",
|
||||
"document",
|
||||
"event",
|
||||
"other"
|
||||
],
|
||||
"maxCostSEK": 25,
|
||||
"reuseExistingFacts": true,
|
||||
"mustNotOwnEngines": true,
|
||||
"engines": []
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
"use client";
|
||||
|
||||
// C8: "Importera ordrar" — the first real product host of the @siax/ui
|
||||
// ImportWizard + @siax/import-export runtime. The wizard renders the frozen
|
||||
// store snapshot; THIS host owns every pipeline step's execution and all
|
||||
// server I/O. The server (POST /api/orders/import) is the only authority:
|
||||
// it re-parses and re-validates the raw CSV, so the client-side parse below
|
||||
// exists purely to give the wizard rows to render.
|
||||
|
||||
import { ImportWizard } from "@siax/ui";
|
||||
import { createImportRunStore, type ImportRunStore, type ImportRunSnapshot } from "@siax/import-export";
|
||||
import { createImportJob } from "@siax/contracts/import-export";
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
const IMPORT_COLUMNS = ["flow", "service_type", "type", "volume", "frequency", "markets"] as const;
|
||||
|
||||
interface ServerReport {
|
||||
imported?: number;
|
||||
totalRows?: number;
|
||||
validRows?: number;
|
||||
errorCount?: number;
|
||||
errors?: { row: number; field: string; code: string; message?: string }[];
|
||||
order_ids?: string[];
|
||||
}
|
||||
|
||||
/** Client-side RFC 4180 parse — presentation only; the server re-parses the raw CSV. */
|
||||
function clientParse(text: string): Record<string, string>[] {
|
||||
const rows: string[][] = [];
|
||||
let field = "";
|
||||
let row: string[] = [];
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (inQuotes) {
|
||||
if (ch === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else inQuotes = false;
|
||||
} else field += ch;
|
||||
} else if (ch === '"') inQuotes = true;
|
||||
else if (ch === ",") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
} else if (ch === "\n") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
rows.push(row);
|
||||
row = [];
|
||||
} else if (ch !== "\r") field += ch;
|
||||
}
|
||||
if (field.length > 0 || row.length > 0) {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
}
|
||||
const nonEmpty = rows.filter((r) => r.length > 1 || (r[0] ?? "").trim() !== "");
|
||||
if (nonEmpty.length === 0) return [];
|
||||
const header = nonEmpty[0].map((h) => h.trim().toLowerCase());
|
||||
return nonEmpty.slice(1).map((cells) => {
|
||||
const obj: Record<string, string> = {};
|
||||
header.forEach((h, idx) => {
|
||||
if (h) obj[h] = (cells[idx] ?? "").trim();
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
}
|
||||
|
||||
async function postImport(mode: "validate" | "dry_run" | "execute", csv: string): Promise<{ ok: boolean; status: number; data: ServerReport & { error?: { message?: string } } }> {
|
||||
const res = await fetch("/api/orders/import", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ mode, csv }),
|
||||
});
|
||||
let data: ServerReport & { error?: { message?: string } } = {};
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch {
|
||||
data = { error: { message: `HTTP ${res.status}` } };
|
||||
}
|
||||
return { ok: res.ok, status: res.status, data };
|
||||
}
|
||||
|
||||
export default function AdminImportPage() {
|
||||
const [rawCsv, setRawCsv] = useState<string | null>(null);
|
||||
const [store, setStore] = useState<ImportRunStore | null>(null);
|
||||
const [serverReport, setServerReport] = useState<ServerReport | null>(null);
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
const [recentOrders, setRecentOrders] = useState<{ order_id: string; flow: string; status: string }[] | null>(null);
|
||||
|
||||
const onFile = useCallback(async (file: File) => {
|
||||
const text = await file.text();
|
||||
setRawCsv(text);
|
||||
setServerReport(null);
|
||||
setServerError(null);
|
||||
setRecentOrders(null);
|
||||
const rows = clientParse(text);
|
||||
const s = createImportRunStore({
|
||||
job: createImportJob({
|
||||
id: globalThis.crypto?.randomUUID?.() ?? `imp-${Date.now()}`,
|
||||
tenantId: "current",
|
||||
entity: "orders",
|
||||
format: "csv",
|
||||
source: { system: "0pt-admin", channel: "web" },
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
rows,
|
||||
});
|
||||
s.detect();
|
||||
setStore(s);
|
||||
}, []);
|
||||
|
||||
const onValidate = useCallback(async () => {
|
||||
if (!store || !rawCsv) return;
|
||||
setServerError(null);
|
||||
const { ok, status, data } = await postImport("validate", rawCsv);
|
||||
setServerReport(data);
|
||||
store.validate(); // local snapshot for the wizard report (same frozen kernel)
|
||||
if (!ok) setServerError(`Servervalidering avvisade filen (HTTP ${status}): ${data.error?.message ?? "okänt fel"}`);
|
||||
}, [store, rawCsv]);
|
||||
|
||||
const onDryRun = useCallback(async () => {
|
||||
if (!store || !rawCsv) return;
|
||||
setServerError(null);
|
||||
const { ok, status, data } = await postImport("dry_run", rawCsv);
|
||||
setServerReport(data);
|
||||
store.dryRun();
|
||||
if (!ok) setServerError(`Servern nekade generalrepet (HTTP ${status}): ${data.error?.message ?? "okänt fel"}`);
|
||||
}, [store, rawCsv]);
|
||||
|
||||
const onExecute = useCallback(async () => {
|
||||
if (!store || !rawCsv) return;
|
||||
setServerError(null);
|
||||
const { ok, status, data } = await postImport("execute", rawCsv);
|
||||
setServerReport(data);
|
||||
if (!ok) {
|
||||
// Server is the authority — a failed execute is terminal for this run.
|
||||
store.fail(`Servern avvisade exekveringen (HTTP ${status}): ${data.error?.message ?? "okänt fel"}`);
|
||||
return;
|
||||
}
|
||||
// Host executor proxies the server result into the store's hard gates.
|
||||
const snapshot: ImportRunSnapshot = await store.execute(async () => ({ imported: data.imported ?? 0 }));
|
||||
// Reload-persistence proof: re-read the REAL order list after import.
|
||||
try {
|
||||
const res = await fetch("/api/orders", { cache: "no-store" });
|
||||
if (res.ok) {
|
||||
const orders = (await res.json()) as { order_id: string; flow: string; status: string }[];
|
||||
const importedIds = new Set(data.order_ids ?? []);
|
||||
setRecentOrders(orders.filter((o) => importedIds.has(o.order_id)));
|
||||
}
|
||||
} catch {
|
||||
/* panel stays null — server report above still shows the truth */
|
||||
}
|
||||
void snapshot;
|
||||
}, [store, rawCsv]);
|
||||
|
||||
return (
|
||||
<main style={{ maxWidth: 720, margin: "0 auto", padding: "2rem 1rem" }}>
|
||||
<h1 style={{ fontSize: "1.5rem", marginBottom: "0.5rem" }}>Importera ordrar</h1>
|
||||
<p style={{ marginBottom: "1rem", opacity: 0.8 }}>
|
||||
CSV med kolumnerna: {IMPORT_COLUMNS.join(", ")}. Endast <code>flow</code> är obligatorisk
|
||||
(catalog | custom | subscription). Parsering och validering sker på servern —
|
||||
filen laddas inte upp förrän ett steg körs.
|
||||
</p>
|
||||
<input
|
||||
type="file"
|
||||
accept=".csv,text/csv"
|
||||
aria-label="Välj CSV-fil"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
if (f) void onFile(f);
|
||||
}}
|
||||
/>
|
||||
{store && (
|
||||
<div style={{ marginTop: "1.5rem" }}>
|
||||
<ImportWizard
|
||||
store={store}
|
||||
columns={IMPORT_COLUMNS.map((c) => ({ source: c, target: c }))}
|
||||
onMap={() => {
|
||||
store.map({ columns: IMPORT_COLUMNS.map((c) => ({ source: c, target: c, required: c === "flow" })) });
|
||||
}}
|
||||
onValidate={onValidate}
|
||||
onDryRun={onDryRun}
|
||||
onExecute={onExecute}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{serverError && (
|
||||
<p role="alert" style={{ marginTop: "1rem", color: "crimson" }}>
|
||||
{serverError}
|
||||
</p>
|
||||
)}
|
||||
{serverReport && (serverReport.errorCount ?? 0) > 0 && (
|
||||
<section style={{ marginTop: "1.5rem" }} aria-label="Felrapport från servern">
|
||||
<h2 style={{ fontSize: "1.1rem" }}>Felrader (serverns rapport)</h2>
|
||||
<ul>
|
||||
{(serverReport.errors ?? []).map((e, i) => (
|
||||
<li key={i}>
|
||||
Rad {e.row} · {e.field} · {e.code}
|
||||
{e.message ? ` — ${e.message}` : ""}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
{recentOrders && (
|
||||
<section style={{ marginTop: "1.5rem" }} aria-label="Importerade ordrar efter reload">
|
||||
<h2 style={{ fontSize: "1.1rem" }}>Importerade ordrar (lästa från /api/orders efter import)</h2>
|
||||
{recentOrders.length === 0 ? (
|
||||
<p>Inga importerade ordrar hittades vid reload.</p>
|
||||
) : (
|
||||
<ul>
|
||||
{recentOrders.map((o) => (
|
||||
<li key={o.order_id}>
|
||||
<code>{o.order_id}</code> — {o.flow} — {o.status}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
"use client";
|
||||
|
||||
// Admin-yta: anteckningar på order — @siax/collaboration-kernelns första
|
||||
// produktkonsument (spår C). Allt nätverk går via lib/order-notes-client.ts
|
||||
// (kernel-transport över host-API): offline-läge = medvetet no-op med varning
|
||||
// (utkastet bevaras, ingen tyst förlust), stale skrivning = 409 -> banner +
|
||||
// reload av serverns aktuella version.
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { PortalShell } from "@/components/portal-shell";
|
||||
import { EmptyState, ErrorState, LoadingSkeleton } from "@/components/states";
|
||||
import {
|
||||
ConflictError,
|
||||
OfflineError,
|
||||
OrderNotesClient,
|
||||
type OrderNoteDto,
|
||||
} from "@/lib/order-notes-client";
|
||||
|
||||
interface Order {
|
||||
order_id: string;
|
||||
flow: string;
|
||||
status: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export default function OrderNotesPage() {
|
||||
const [orders, setOrders] = useState<Order[] | null>(null);
|
||||
const [orderId, setOrderId] = useState<string>("");
|
||||
const [notes, setNotes] = useState<OrderNoteDto[] | null>(null);
|
||||
const [loadError, setLoadError] = useState(false);
|
||||
const [offlineMode, setOfflineMode] = useState(false);
|
||||
const [draft, setDraft] = useState("");
|
||||
const [editing, setEditing] = useState<{ note: OrderNoteDto; body: string } | null>(null);
|
||||
|
||||
const client = useMemo(() => new OrderNotesClient("admin-simon"), []);
|
||||
|
||||
useEffect(() => {
|
||||
client.transport.setOffline(offlineMode);
|
||||
}, [client, offlineMode]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch("/api/orders", { cache: "no-store" });
|
||||
if (!res.ok) throw new Error("orders fetch failed");
|
||||
const body = await res.json();
|
||||
setOrders(Array.isArray(body) ? body : []);
|
||||
} catch {
|
||||
setLoadError(true);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
const loadNotes = useCallback(
|
||||
async (id: string) => {
|
||||
setNotes(null);
|
||||
setLoadError(false);
|
||||
try {
|
||||
const { notes: loaded } = await client.load(id);
|
||||
setNotes(loaded);
|
||||
} catch {
|
||||
setLoadError(true);
|
||||
}
|
||||
},
|
||||
[client],
|
||||
);
|
||||
|
||||
const addNote = useCallback(async () => {
|
||||
if (!orderId || !draft.trim()) return;
|
||||
if (offlineMode) {
|
||||
// Offline = klient-varning + no-op. Utkastet ligger kvar i rutan —
|
||||
// INGET skickas, inget försvinner tyst.
|
||||
toast.warning("Offline-läge: anteckningen SKICKAS EJ. Utkastet är bevarat i rutan.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const note = await client.add(orderId, draft);
|
||||
setDraft("");
|
||||
setNotes((prev) => [...(prev ?? []), note]);
|
||||
toast.success("Anteckning sparad");
|
||||
} catch (err) {
|
||||
if (err instanceof OfflineError) {
|
||||
toast.warning("Offline: inget skickades — utkastet är bevarat.");
|
||||
return;
|
||||
}
|
||||
setLoadError(true);
|
||||
}
|
||||
}, [client, draft, offlineMode, orderId]);
|
||||
|
||||
const saveEdit = useCallback(async () => {
|
||||
if (!editing) return;
|
||||
if (offlineMode) {
|
||||
toast.warning("Offline-läge: ändringen SKICKAS EJ. Texten är bevarad i redigeringsrutan.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const updated = await client.update(editing.note, editing.body, editing.note.version);
|
||||
setNotes((prev) => (prev ?? []).map((n) => (n.note_id === updated.note_id ? updated : n)));
|
||||
setEditing(null);
|
||||
toast.success("Anteckning uppdaterad");
|
||||
} catch (err) {
|
||||
if (err instanceof ConflictError) {
|
||||
// Någon annan skrev samtidigt (stale version -> 409). Ladda om
|
||||
// serverns aktuella version — förlora ALDRIG den lokala texten tyst.
|
||||
toast.error(`Konflikt: anteckningen ändrades av någon annan (serverversion ${err.currentVersion}). Laddar om — din text finns kvar nedan.`);
|
||||
setDraft((prev) => (prev ? prev : editing.body));
|
||||
await loadNotes(orderId);
|
||||
setEditing(null);
|
||||
return;
|
||||
}
|
||||
if (err instanceof OfflineError) {
|
||||
toast.warning("Offline: inget skickades — ändringen är bevarad.");
|
||||
return;
|
||||
}
|
||||
setLoadError(true);
|
||||
}
|
||||
}, [client, editing, loadNotes, offlineMode, orderId]);
|
||||
|
||||
return (
|
||||
<PortalShell variant="admin" title="Orderanteckningar">
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={offlineMode}
|
||||
onChange={(e) => setOfflineMode(e.target.checked)}
|
||||
/>
|
||||
Offline-läge (blockera utskick — varning + no-op, utkast bevaras)
|
||||
</label>
|
||||
{offlineMode && (
|
||||
<div role="alert" className="rounded border border-amber-400 bg-amber-50 p-2 text-sm">
|
||||
Offline-läge aktivt: inga anteckningar skickas till servern. Utkast bevaras lokalt —
|
||||
ingen tyst förlust.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loadError ? (
|
||||
<ErrorState onRetry={() => orderId && loadNotes(orderId)} />
|
||||
) : orders === null ? (
|
||||
<LoadingSkeleton />
|
||||
) : orders.length === 0 ? (
|
||||
<EmptyState title="Inga ordrar" line="Inga ordrar att annotera ännu." />
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
Order:{" "}
|
||||
<select
|
||||
aria-label="Välj order"
|
||||
value={orderId}
|
||||
onChange={(e) => {
|
||||
setOrderId(e.target.value);
|
||||
void loadNotes(e.target.value);
|
||||
}}
|
||||
className="rounded border px-2 py-1"
|
||||
>
|
||||
<option value="">— välj —</option>
|
||||
{orders.map((o) => (
|
||||
<option key={o.order_id} value={o.order_id}>
|
||||
{o.order_id} ({o.flow}, {o.status})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
{orderId === "" ? (
|
||||
<EmptyState title="Välj order" line="Välj en order för att se och skriva anteckningar." />
|
||||
) : notes === null ? (
|
||||
<LoadingSkeleton />
|
||||
) : notes.length === 0 ? (
|
||||
<EmptyState title="Tomt" line="Inga anteckningar på den här ordern ännu." />
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{notes.map((n) => (
|
||||
<li key={n.note_id} className="rounded border p-3 text-sm">
|
||||
<div className="mb-1 flex justify-between text-xs opacity-70">
|
||||
<span>
|
||||
{n.author_id} · v{n.version} · klocka {n.clock}
|
||||
</span>
|
||||
<span>{new Date(n.updated_at).toLocaleString("sv-SE")}</span>
|
||||
</div>
|
||||
{editing?.note.note_id === n.note_id ? (
|
||||
<div className="space-y-2">
|
||||
<textarea
|
||||
aria-label="Redigera anteckning"
|
||||
value={editing.body}
|
||||
onChange={(e) => setEditing({ ...editing, body: e.target.value })}
|
||||
className="w-full rounded border p-2"
|
||||
rows={3}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button className="rounded bg-black px-3 py-1 text-white" onClick={() => void saveEdit()}>
|
||||
Spara (v{editing.note.version} → v{editing.note.version + 1})
|
||||
</button>
|
||||
<button className="rounded border px-3 py-1" onClick={() => setEditing(null)}>
|
||||
Avbryt
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="whitespace-pre-wrap">{n.body}</p>
|
||||
<button
|
||||
className="mt-2 text-xs underline"
|
||||
onClick={() => setEditing({ note: n, body: n.body })}
|
||||
>
|
||||
Redigera
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{orderId !== "" && (
|
||||
<div className="space-y-2">
|
||||
<textarea
|
||||
aria-label="Ny anteckning"
|
||||
placeholder="Skriv en anteckning på ordern…"
|
||||
value={draft}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
className="w-full rounded border p-2"
|
||||
rows={3}
|
||||
/>
|
||||
<button
|
||||
className="rounded bg-black px-4 py-2 text-sm text-white disabled:opacity-40"
|
||||
disabled={!draft.trim() || notes === null}
|
||||
onClick={() => void addNote()}
|
||||
>
|
||||
Lägg till anteckning
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</PortalShell>
|
||||
);
|
||||
}
|
||||
+14
-34
@@ -1,8 +1,5 @@
|
||||
"use client";
|
||||
|
||||
import { ActionGate, InboxList } from "@siax/ui";
|
||||
import { nextOrderStatus } from "@/lib/order-flow";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
@@ -28,6 +25,13 @@ interface Metrics {
|
||||
pipeline_ore: number;
|
||||
}
|
||||
|
||||
const NEXT_STATUS: Record<string, string> = {
|
||||
draft: "quoted",
|
||||
quoted: "in_production",
|
||||
in_production: "review",
|
||||
review: "accepted",
|
||||
accepted: "delivered",
|
||||
};
|
||||
|
||||
export default function AdminPage() {
|
||||
const t = useT();
|
||||
@@ -54,7 +58,7 @@ export default function AdminPage() {
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
|
||||
async function advance(id: string, status: string) {
|
||||
const next = nextOrderStatus(status);
|
||||
const next = NEXT_STATUS[status];
|
||||
if (!next) return;
|
||||
try {
|
||||
const r = await fetch(`/api/orders/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ status: next }) });
|
||||
@@ -92,34 +96,8 @@ export default function AdminPage() {
|
||||
))}
|
||||
</div>
|
||||
|
||||
{orders.some((o) => o.inbox_item) ? (
|
||||
<section className="mt-10">
|
||||
<h2 className="font-mono text-[11px] uppercase tracking-[0.14em] text-muted-foreground">{t({ en: "Inbox", sv: "Inkorg" })}</h2>
|
||||
<div className="mt-4">
|
||||
<InboxList
|
||||
items={orders.map((o) => o.inbox_item).filter(Boolean)}
|
||||
labels={{
|
||||
resolve: t({ en: "Advance", sv: "Flytta fram" }),
|
||||
emptyTitle: t({ en: "Inbox is empty", sv: "Inkorgen är tom" }),
|
||||
}}
|
||||
onResolve={(item) => {
|
||||
const order = orders.find((o) => `order:${o.order_id}` === item.id);
|
||||
if (order?.advance_action?.state === "available" && nextOrderStatus(order.status)) {
|
||||
advance(order.order_id, order.status);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
<section className="mt-10">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="font-mono text-[11px] uppercase tracking-[0.14em] text-muted-foreground">{t({ en: "Order queue", sv: "Orderkö" })}</h2>
|
||||
{/* DoD §65: real anchor, not a JS-handler button — the download is a plain GET of the CSV endpoint. */}
|
||||
<a href="/api/orders/export" download className="border border-border px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground transition-colors hover:bg-foreground hover:text-background">
|
||||
{t({ en: "Export CSV", sv: "Exportera CSV" })}
|
||||
</a>
|
||||
</div>
|
||||
<h2 className="font-mono text-[11px] uppercase tracking-[0.14em] text-muted-foreground">{t({ en: "Order queue", sv: "Orderkö" })}</h2>
|
||||
{orders.length === 0 ? (
|
||||
<div className="mt-6"><EmptyState title={t({ en: "Empty queue.", sv: "Tom kö." })} line={t({ en: "No orders yet.", sv: "Inga ordrar än." })} /></div>
|
||||
) : (
|
||||
@@ -134,14 +112,16 @@ export default function AdminPage() {
|
||||
<StatusPill status={o.status} />
|
||||
<span className="text-right font-mono text-[12px] tabular-nums">{formatSEK(o.total_ore / 100)}</span>
|
||||
<span className="text-right">
|
||||
<ActionGate action={o.advance_action} className="inline-block text-right">
|
||||
{NEXT_STATUS[o.status] ? (
|
||||
<button
|
||||
onClick={() => advance(o.order_id, o.status)}
|
||||
className="border border-foreground px-3 py-1.5 font-mono text-[10px] uppercase tracking-[0.08em] transition-colors hover:bg-foreground hover:text-background"
|
||||
>
|
||||
→ {nextOrderStatus(o.status) ?? t({ en: "done", sv: "klar" })}
|
||||
→ {NEXT_STATUS[o.status]}
|
||||
</button>
|
||||
</ActionGate>
|
||||
) : (
|
||||
<span className="font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground">{t({ en: "done", sv: "klar" })}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -88,7 +88,7 @@ function ScreenTool() {
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
<p className="mt-3 text-[10.5px] text-muted-foreground">{t({ en: "Requires verified OpenSanctions terms/key for full matches.", sv: "Kräver verifierade OpenSanctions-villkor/nyckel för fullständiga träffar." })}</p>
|
||||
<p className="mt-3 text-[10.5px] text-muted-foreground/70">{t({ en: "Requires verified OpenSanctions terms/key for full matches.", sv: "Kräver verifierade OpenSanctions-villkor/nyckel för fullständiga träffar." })}</p>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
/**
|
||||
* app/api/0pt/canonical/facts/route.ts
|
||||
* ====================================
|
||||
* POST — canonical structured-observation write (entities/facts/relations).
|
||||
* GET — tenant-scoped read for consumers (products, agents, L0RE projection).
|
||||
*
|
||||
* 0pt owns observed facts; L0RE owns epistemic propositions/projections and
|
||||
* consumes this API. Tenant is always cross-checked against the verified
|
||||
* principal (assertTenantMatchesVerified), never trusted from the body alone.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { canonicalWriteSchema, parseBody } from "@/src/validation/0pt-schemas";
|
||||
import { canonicalFactService } from "@/src/services/canonical-fact-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const parsed = parseBody(canonicalWriteSchema, await request.json());
|
||||
if (!parsed.ok) return NextResponse.json(parsed.body, { status: parsed.status });
|
||||
const body = parsed.data;
|
||||
const guard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (guard) return guard;
|
||||
const result = await canonicalFactService.write(body);
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
const limitRaw = searchParams.get("limit");
|
||||
const facts = await canonicalFactService.query({
|
||||
tenant_id: tenantId,
|
||||
entity_id: searchParams.get("entity_id") ?? undefined,
|
||||
entity_type: searchParams.get("entity_type") ?? undefined,
|
||||
identity_namespace: searchParams.get("identity_namespace") ?? undefined,
|
||||
identity_value: searchParams.get("identity_value") ?? undefined,
|
||||
predicate: searchParams.get("predicate") ?? undefined,
|
||||
limit: limitRaw ? Number(limitRaw) : undefined,
|
||||
});
|
||||
return NextResponse.json({ facts });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { ensureTrialCredits, readTrialCredits } from '@/src/document-workbench/trial-credits';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/** GET /api/0pt/credits/balance — the authenticated tenant's credit balance. */
|
||||
export async function GET(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
|
||||
const url = repositoryDatabaseUrl();
|
||||
if (!url) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_NOT_CONFIGURED',
|
||||
message: 'Credits are not available until the database is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const ledger = new PostgresCreditLedger(getRepositorySql(url));
|
||||
const trial = readTrialCredits();
|
||||
if (trial > 0) await ensureTrialCredits(ledger, verified.scope.tenantId, trial);
|
||||
const balance = await ledger.balance(verified.scope.tenantId);
|
||||
return NextResponse.json({ tenant_id: verified.scope.tenantId, ...balance });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Credit balance unavailable';
|
||||
const notConfigured = /RLS-enforced|isolation migration/i.test(message);
|
||||
return NextResponse.json(
|
||||
{ error: notConfigured ? 'CREDITS_NOT_CONFIGURED' : 'CREDITS_UNAVAILABLE', message },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { getStripe } from '@/lib/stripe';
|
||||
import { PostgresCreditPurchaseStore } from '@/src/document-workbench/credit-purchase-store';
|
||||
import { findPack, readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { isValidScopeId, resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
function appBaseUrl(request: NextRequest): string {
|
||||
const configured = process.env.NEXT_PUBLIC_APP_URL;
|
||||
if (configured && /^https:\/\//.test(configured)) return configured.replace(/\/+$/, '');
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/0pt/credits/checkout { pack_id }
|
||||
*
|
||||
* Creates a Stripe Checkout Session and stores the server-owned price snapshot
|
||||
* BEFORE any credit exists. Credits are granted only when the Stripe webhook
|
||||
* re-reads the session and its payment intent and the ledger accepts the
|
||||
* idempotent verified-payment command.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
const { tenantId } = verified.scope;
|
||||
|
||||
if (process.env.OPT_CREDITS_MODE === 'off') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_DISABLED',
|
||||
message: 'Billing is not active yet (pilot mode). No payment can be taken.',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const book = readCreditPriceBook();
|
||||
if (!book) {
|
||||
return NextResponse.json(
|
||||
{ error: 'PRICE_BOOK_NOT_CONFIGURED', message: 'Credit purchases are not available yet' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return NextResponse.json(
|
||||
{ error: 'STRIPE_NOT_CONFIGURED', message: 'Payments are not available yet' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const databaseUrl = repositoryDatabaseUrl();
|
||||
if (!databaseUrl) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_NOT_CONFIGURED',
|
||||
message: 'Credits are not available until the database is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'INVALID_BODY', message: 'JSON body required' }, { status: 400 });
|
||||
}
|
||||
const packId = (body as { pack_id?: unknown } | null)?.pack_id;
|
||||
if (typeof packId !== 'string' || !isValidScopeId(packId)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_PACK', message: 'A valid pack_id is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const pack = findPack(book, packId);
|
||||
if (!pack) {
|
||||
return NextResponse.json({ error: 'UNKNOWN_PACK', message: 'Unknown credit pack' }, { status: 404 });
|
||||
}
|
||||
|
||||
const purchaseId = crypto.randomUUID();
|
||||
const base = appBaseUrl(request);
|
||||
const metadata = {
|
||||
kind: '0pt_credit_purchase',
|
||||
tenant_id: tenantId,
|
||||
purchase_id: purchaseId,
|
||||
price_book_version: book.version,
|
||||
};
|
||||
|
||||
let session;
|
||||
try {
|
||||
session = await stripe.checkout.sessions.create({
|
||||
mode: 'payment',
|
||||
client_reference_id: tenantId,
|
||||
line_items: [
|
||||
{
|
||||
quantity: 1,
|
||||
price_data: {
|
||||
currency: book.currency.toLowerCase(),
|
||||
unit_amount: pack.amountMinor,
|
||||
product_data: { name: `${pack.credits} 0pt credits` },
|
||||
},
|
||||
},
|
||||
],
|
||||
metadata,
|
||||
payment_intent_data: { metadata },
|
||||
success_url: `${base}/portal/krediter?status=success&purchase=${encodeURIComponent(purchaseId)}`,
|
||||
cancel_url: `${base}/portal/krediter?status=cancelled`,
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: 'CHECKOUT_UNAVAILABLE', message: 'The payment provider could not start a checkout' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await new PostgresCreditPurchaseStore(getRepositorySql(databaseUrl)).create({
|
||||
tenantId,
|
||||
purchaseId,
|
||||
checkoutSessionId: session.id,
|
||||
amountMinor: pack.amountMinor,
|
||||
currency: book.currency,
|
||||
credits: pack.credits,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
// Never leave a payable session with no server-side snapshot behind it.
|
||||
try {
|
||||
await stripe.checkout.sessions.expire(session.id);
|
||||
} catch {
|
||||
/* best effort; the webhook will refuse the unmatched session */
|
||||
}
|
||||
const message = error instanceof Error ? error.message : 'Credit purchase could not be stored';
|
||||
return NextResponse.json({ error: 'CREDITS_NOT_CONFIGURED', message }, { status: 503 });
|
||||
}
|
||||
|
||||
if (!session.url) {
|
||||
return NextResponse.json(
|
||||
{ error: 'CHECKOUT_UNAVAILABLE', message: 'The payment provider returned no checkout URL' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
purchase_id: purchaseId,
|
||||
checkout_url: session.url,
|
||||
credits: pack.credits,
|
||||
amount_minor: pack.amountMinor,
|
||||
currency: book.currency,
|
||||
},
|
||||
{ status: 201 },
|
||||
);
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/**
|
||||
* GET /api/0pt/credits/packs — sellable credit packs from the server-owned
|
||||
* price book. No price is ever accepted from the client.
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
|
||||
const book = readCreditPriceBook();
|
||||
if (!book) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'PRICE_BOOK_NOT_CONFIGURED',
|
||||
message: 'Credit packs are not available until the server price book is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
version: book.version,
|
||||
currency: book.currency,
|
||||
purchases_enabled: process.env.OPT_CREDITS_MODE !== 'off',
|
||||
packs: book.packs.map((pack) => ({
|
||||
id: pack.id,
|
||||
credits: pack.credits,
|
||||
amount_minor: pack.amountMinor,
|
||||
})),
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, documentExtractionSchema } from "@/src/validation/0pt-schemas";
|
||||
import { documentExtractionService } from "@/src/services/document-extraction-service";
|
||||
import { assertTenantMatchesVerified, resolveDocumentActor } from "@/src/http/tenant-guard";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
|
||||
try {
|
||||
@@ -14,16 +14,11 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const actor = resolveDocumentActor(request, body.actor_id);
|
||||
if (actor.response) return actor.response;
|
||||
if (!actor.actorId || !body.model_id) {
|
||||
return NextResponse.json({ error: "actor and model_id are required" }, { status: 400 });
|
||||
}
|
||||
const result = await documentExtractionService.extractDocument(documentId, {
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
actor_id: actor.actorId,
|
||||
correlation_id: body.correlation_id ?? crypto.randomUUID(),
|
||||
actor_id: body.actor_id,
|
||||
correlation_id: body.correlation_id,
|
||||
model_id: body.model_id,
|
||||
});
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, documentCaptureSchema } from "@/src/validation/0pt-schemas";
|
||||
import { documentCaptureService } from "@/src/services/document-capture-service";
|
||||
import { assertTenantMatchesVerified, resolveDocumentActor } from "@/src/http/tenant-guard";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@@ -13,8 +13,6 @@ export async function POST(request: NextRequest) {
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const actor = resolveDocumentActor(request, body.actor_id);
|
||||
if (actor.response) return actor.response;
|
||||
const result = await documentCaptureService.captureFromMailbox(
|
||||
{
|
||||
mailbox: {
|
||||
@@ -31,9 +29,17 @@ export async function POST(request: NextRequest) {
|
||||
{
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
// In enforced mode middleware supplies the verified subject; the
|
||||
// body can only agree with it. Development retains the old fallback.
|
||||
actor_id: actor.actorId ?? "",
|
||||
// documentCaptureSchema types these optional (pre-existing, listed
|
||||
// among package.json's "9 pre-existing errors ... Wave 2 Zod
|
||||
// schemas type fields as plain string while the services want
|
||||
// narrower unions" -- deliberately left to its own change, not
|
||||
// widened here). CaptureMailboxContext requires actor_id as a
|
||||
// non-empty string and captureFromMailbox already throws a clear
|
||||
// "missing tenant_id/project_id/actor_id" error when it's falsy, so
|
||||
// `?? ""` changes no runtime behavior -- it only satisfies the type
|
||||
// checker, which previously never saw this file (nothing under
|
||||
// tests/ imported it before P014's cross-tenant regression tests).
|
||||
actor_id: body.actor_id ?? "",
|
||||
correlation_id: body.correlation_id ?? "",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
function csv(value: string | undefined): string[] {
|
||||
return (value ?? '')
|
||||
.split(',')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/0pt/documents/models — the server-approved model routes and limits
|
||||
* the customer may choose from. Never a free-form model list.
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
|
||||
const models = csv(process.env.OPT_ALLOWED_MODELS);
|
||||
const dataClasses = csv(process.env.OPT_ALLOWED_DATA_CLASSES);
|
||||
const destination = process.env.OPT_MODEL_DESTINATION;
|
||||
const maxInputTokens = Number(process.env.OPT_MODEL_MAX_INPUT_TOKENS ?? '0');
|
||||
const maxOutputTokens = Number(process.env.OPT_MODEL_MAX_OUTPUT_TOKENS ?? '0');
|
||||
if (
|
||||
models.length === 0 ||
|
||||
dataClasses.length === 0 ||
|
||||
(destination !== 'internal' && destination !== 'external') ||
|
||||
!Number.isSafeInteger(maxInputTokens) ||
|
||||
maxInputTokens <= 0 ||
|
||||
!Number.isSafeInteger(maxOutputTokens) ||
|
||||
maxOutputTokens <= 0
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'MODEL_POLICY_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until the model policy is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const book = readCreditPriceBook();
|
||||
return NextResponse.json({
|
||||
models,
|
||||
data_classes: dataClasses,
|
||||
destination,
|
||||
external_transfer_allowed: process.env.OPT_EXTERNAL_TRANSFER_ALLOWED === 'true',
|
||||
max_input_tokens: maxInputTokens,
|
||||
max_output_tokens: maxOutputTokens,
|
||||
price_book_version: book?.version ?? null,
|
||||
});
|
||||
}
|
||||
@@ -1,454 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { Doc0SourceClient, Doc0SourceUnavailableError } from '@/src/document-workbench/doc0-source-client';
|
||||
import { Inf0OutcomeUnknownError } from '@/src/document-workbench/inf0-gateway-client';
|
||||
import { createInf0Gateway } from '@/src/document-workbench/inf0-gateway';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { ensureTrialCredits, readTrialCredits } from '@/src/document-workbench/trial-credits';
|
||||
import { creditsForUsage, readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { structureDocument } from '@/src/document-workbench/structure-document';
|
||||
import { exportValidatedOutput } from '@/src/document-workbench/export-validated-output';
|
||||
import type {
|
||||
OutputFieldContract,
|
||||
OutputFieldType,
|
||||
} from '@/src/document-workbench/structured-output-validation';
|
||||
import { readDocumentWorkbenchRuntime } from '@/src/document-workbench/runtime-config';
|
||||
import { createProjectAuthorizer } from '@/src/document-workbench/project-access';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { isValidScopeId, resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const FIELD_TYPES: readonly OutputFieldType[] = ['string', 'integer', 'boolean', 'decimal', 'date'];
|
||||
const DATA_CLASSES = ['none', 'low', 'medium', 'high', 'restricted'] as const;
|
||||
|
||||
function csv(value: string | undefined): string[] {
|
||||
return (value ?? '')
|
||||
.split(',')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function modelPolicy() {
|
||||
const allowedModelIds = csv(process.env.OPT_ALLOWED_MODELS);
|
||||
const allowedDataClasses = csv(process.env.OPT_ALLOWED_DATA_CLASSES);
|
||||
const destination = process.env.OPT_MODEL_DESTINATION;
|
||||
const maxInputTokens = Number(process.env.OPT_MODEL_MAX_INPUT_TOKENS ?? '0');
|
||||
const maxOutputTokens = Number(process.env.OPT_MODEL_MAX_OUTPUT_TOKENS ?? '0');
|
||||
if (
|
||||
allowedModelIds.length === 0 ||
|
||||
allowedDataClasses.length === 0 ||
|
||||
(destination !== 'internal' && destination !== 'external') ||
|
||||
!Number.isSafeInteger(maxInputTokens) ||
|
||||
maxInputTokens <= 0 ||
|
||||
!Number.isSafeInteger(maxOutputTokens) ||
|
||||
maxOutputTokens <= 0
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
allowedModelIds,
|
||||
allowedDataClasses,
|
||||
destination: destination as 'internal' | 'external',
|
||||
externalTransferAllowed: process.env.OPT_EXTERNAL_TRANSFER_ALLOWED === 'true',
|
||||
maxInputTokens,
|
||||
maxOutputTokens,
|
||||
};
|
||||
}
|
||||
|
||||
function parseFields(raw: unknown): OutputFieldContract[] | undefined {
|
||||
if (!Array.isArray(raw) || raw.length === 0 || raw.length > 100) return undefined;
|
||||
const fields: OutputFieldContract[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const item of raw) {
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined;
|
||||
const field = item as Record<string, unknown>;
|
||||
if (
|
||||
typeof field.name !== 'string' ||
|
||||
!/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(field.name) ||
|
||||
seen.has(field.name) ||
|
||||
typeof field.type !== 'string' ||
|
||||
!FIELD_TYPES.includes(field.type as OutputFieldType)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
seen.add(field.name);
|
||||
fields.push({ name: field.name, type: field.type as OutputFieldType, required: true });
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
interface StructureBody {
|
||||
project_id?: unknown;
|
||||
document_id?: unknown;
|
||||
version_id?: unknown;
|
||||
checksum_sha256?: unknown;
|
||||
pipeline_stage?: unknown;
|
||||
instruction?: unknown;
|
||||
fields?: unknown;
|
||||
model_id?: unknown;
|
||||
data_class?: unknown;
|
||||
format?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/0pt/documents/structure
|
||||
*
|
||||
* Upload → DOC0 segments → INF0 model → mechanically validated, evidence-bound
|
||||
* output (optionally exported). Credits are reserved before the model runs and
|
||||
* settled to the measured usage afterwards.
|
||||
*
|
||||
* Nothing is trusted from the client except the requested target fields and
|
||||
* instruction. Source text is re-read from DOC0 and every returned value must
|
||||
* point at an exact span in that text.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
const { tenantId, actorId } = verified.scope;
|
||||
|
||||
const runtimeConfig = readDocumentWorkbenchRuntime();
|
||||
const gateway = createInf0Gateway();
|
||||
if (!runtimeConfig.doc0 || !gateway) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'WORKBENCH_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until DOC0 and INF0 are configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const policy = modelPolicy();
|
||||
if (!policy) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'MODEL_POLICY_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until the model policy is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
// Explicit pilot switch: `OPT_CREDITS_MODE=off` runs structuring without a
|
||||
// wallet. It is deliberately NOT a silent fallback — the response reports
|
||||
// `credits: null` and the operator has named the mode.
|
||||
const creditsEnabled =
|
||||
process.env.OPT_CREDITS_MODE !== 'off' &&
|
||||
Boolean(readCreditPriceBook()) &&
|
||||
Boolean(repositoryDatabaseUrl());
|
||||
const priceBook = creditsEnabled ? readCreditPriceBook() : undefined;
|
||||
const databaseUrl = creditsEnabled ? repositoryDatabaseUrl() : undefined;
|
||||
if (!creditsEnabled && process.env.OPT_CREDITS_MODE !== 'off') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until credits are configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
let body: StructureBody;
|
||||
try {
|
||||
body = (await request.json()) as StructureBody;
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'INVALID_BODY', message: 'JSON body required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const projectId = body.project_id;
|
||||
const documentId = body.document_id;
|
||||
const versionId = body.version_id;
|
||||
const checksum = body.checksum_sha256;
|
||||
const pipelineStage = body.pipeline_stage;
|
||||
const instruction = body.instruction;
|
||||
const modelId = body.model_id;
|
||||
const dataClass = body.data_class ?? 'low';
|
||||
const format = body.format ?? 'json';
|
||||
|
||||
if (pipelineStage !== 'parsed') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'DOCUMENT_NOT_PARSED',
|
||||
message:
|
||||
'The document has no verified text layer yet (parse_failed or not parsed). OCR is required before structuring.',
|
||||
},
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
if (
|
||||
!isValidScopeId(projectId) ||
|
||||
!isValidScopeId(documentId) ||
|
||||
!isValidScopeId(versionId) ||
|
||||
typeof checksum !== 'string' ||
|
||||
!/^[0-9a-f]{64}$/.test(checksum) ||
|
||||
typeof instruction !== 'string' ||
|
||||
!instruction.trim() ||
|
||||
instruction.length > 4000 ||
|
||||
typeof modelId !== 'string' ||
|
||||
!policy.allowedModelIds.includes(modelId) ||
|
||||
typeof dataClass !== 'string' ||
|
||||
!(DATA_CLASSES as readonly string[]).includes(dataClass) ||
|
||||
(format !== 'json' && format !== 'csv')
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_REQUEST', message: 'Invalid document structure request' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const fields = parseFields(body.fields);
|
||||
if (!fields) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_FIELDS', message: 'A valid field contract is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const authorize = createProjectAuthorizer();
|
||||
if (!(await authorize({ tenantId, projectId, actorId }))) {
|
||||
return NextResponse.json(
|
||||
{ error: 'OPT_ACCESS_DENIED', message: 'Project access is not authorized' },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const correlationId = request.headers.get('x-request-id') ?? crypto.randomUUID();
|
||||
const context = {
|
||||
tenantId,
|
||||
projectId,
|
||||
actorId,
|
||||
capability: '0pt.document.structure.v1',
|
||||
correlationId,
|
||||
idempotencyKey: correlationId,
|
||||
};
|
||||
|
||||
let sources;
|
||||
try {
|
||||
sources = await new Doc0SourceClient({
|
||||
baseUrl: runtimeConfig.doc0.baseUrl,
|
||||
serviceToken: runtimeConfig.doc0.serviceToken,
|
||||
}).read({
|
||||
tenantId,
|
||||
projectId,
|
||||
actorId: runtimeConfig.doc0.actorId ?? actorId,
|
||||
requestId: correlationId,
|
||||
receipt: {
|
||||
documentId,
|
||||
versionId,
|
||||
checksumSha256: checksum,
|
||||
pipelineStage: 'parsed',
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Doc0SourceUnavailableError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'DOC0_SOURCE_UNAVAILABLE',
|
||||
message:
|
||||
'The extracted source could not be verified (version, checksum, page cap or tenant). Review or reconciliation is required.',
|
||||
},
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: 'DOC0_SOURCE_UNAVAILABLE', message: 'The extracted source is unavailable' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
console.log('[0pt-workbench] doc0 source read:', sources.sources.length, 'segments');
|
||||
const sourceChars = sources.sources.reduce((total, source) => total + source.text.length, 0);
|
||||
const estimatedInputTokens = Math.ceil(JSON.stringify(sources.sources).length / 4) + 1024;
|
||||
if (estimatedInputTokens > policy.maxInputTokens) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'SOURCE_TOO_LARGE',
|
||||
message: 'The document is larger than the configured model input limit',
|
||||
},
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
const maximumCredits =
|
||||
creditsEnabled && priceBook
|
||||
? creditsForUsage(priceBook, {
|
||||
pages: Math.max(1, Math.ceil(sourceChars / 1800)),
|
||||
inputTokens: estimatedInputTokens,
|
||||
outputTokens: policy.maxOutputTokens,
|
||||
})
|
||||
: 0;
|
||||
const reservationId = crypto.randomUUID();
|
||||
const ledger =
|
||||
creditsEnabled && databaseUrl ? new PostgresCreditLedger(getRepositorySql(databaseUrl)) : undefined;
|
||||
if (ledger) {
|
||||
try {
|
||||
await ensureTrialCredits(ledger, tenantId, readTrialCredits());
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `reserve:${reservationId}`,
|
||||
kind: 'reserve',
|
||||
reference: reservationId,
|
||||
amount: maximumCredits,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Credit reservation failed';
|
||||
if (/Insufficient available credits/i.test(message)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'INSUFFICIENT_CREDITS',
|
||||
message: 'Not enough credits for this job',
|
||||
required_credits: maximumCredits,
|
||||
},
|
||||
{ status: 402 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ error: 'CREDITS_UNAVAILABLE', message }, { status: 503 });
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await structureDocument({
|
||||
gateway,
|
||||
request: {
|
||||
context,
|
||||
admission: {
|
||||
tenantId,
|
||||
projectId,
|
||||
jobId: `doc:${documentId}:${correlationId}`,
|
||||
modelId,
|
||||
dataClass,
|
||||
maxInputTokens: policy.maxInputTokens,
|
||||
maxOutputTokens: policy.maxOutputTokens,
|
||||
maximumCredits,
|
||||
},
|
||||
policy: {
|
||||
tenantId,
|
||||
projectId,
|
||||
allowedModelIds: policy.allowedModelIds,
|
||||
allowedDataClasses: policy.allowedDataClasses,
|
||||
destination: policy.destination,
|
||||
externalTransferAllowed: policy.externalTransferAllowed,
|
||||
maxInputTokens: policy.maxInputTokens,
|
||||
maxOutputTokens: policy.maxOutputTokens,
|
||||
},
|
||||
reservation: ledger
|
||||
? {
|
||||
tenantId,
|
||||
projectId,
|
||||
jobId: `doc:${documentId}:${correlationId}`,
|
||||
status: 'reserved',
|
||||
credits: maximumCredits,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
countTokens: async (messages) => Math.ceil(JSON.stringify(messages).length / 4),
|
||||
instructions: instruction,
|
||||
fields,
|
||||
sources: sources.sources,
|
||||
});
|
||||
|
||||
const charged =
|
||||
ledger && priceBook
|
||||
? Math.min(
|
||||
maximumCredits,
|
||||
creditsForUsage(priceBook, {
|
||||
pages: Math.max(1, Math.ceil(sourceChars / 1800)),
|
||||
inputTokens: result.model.promptTokens,
|
||||
outputTokens: result.model.completionTokens,
|
||||
}),
|
||||
)
|
||||
: 0;
|
||||
let balance;
|
||||
if (ledger) {
|
||||
try {
|
||||
balance = (
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `settle:${reservationId}`,
|
||||
kind: 'settle',
|
||||
reference: reservationId,
|
||||
amount: charged,
|
||||
})
|
||||
).balance;
|
||||
} catch {
|
||||
// The model result is real; keep the reservation for reconciliation
|
||||
// rather than reporting a balance we could not write.
|
||||
balance = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.status !== 'mechanically_validated') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'needs_review',
|
||||
issues: result.issues,
|
||||
model: result.model,
|
||||
credits: ledger ? { reserved: maximumCredits, charged, balance } : null,
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
|
||||
const exported =
|
||||
format === 'json'
|
||||
? exportValidatedOutput({
|
||||
format: 'json',
|
||||
fields,
|
||||
sources: sources.sources,
|
||||
value: result.value,
|
||||
evidence: result.evidence,
|
||||
})
|
||||
: exportValidatedOutput({
|
||||
format: 'csv',
|
||||
fields,
|
||||
sources: sources.sources,
|
||||
value: result.value,
|
||||
evidence: result.evidence,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'mechanically_validated',
|
||||
value: result.value,
|
||||
evidence: result.evidence,
|
||||
model: result.model,
|
||||
credits: ledger ? { reserved: maximumCredits, charged, balance } : null,
|
||||
export:
|
||||
exported.status === 'ready'
|
||||
? { media_type: exported.mediaType, content: exported.content }
|
||||
: undefined,
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Inf0OutcomeUnknownError) {
|
||||
// Never release a reservation whose model call may have completed.
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'outcome_unknown',
|
||||
message:
|
||||
'The model call may have completed. The credit reservation is kept until its usage is reconciled.',
|
||||
reservation_id: reservationId,
|
||||
},
|
||||
{ status: 202 },
|
||||
);
|
||||
}
|
||||
if (ledger) {
|
||||
try {
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `release:${reservationId}`,
|
||||
kind: 'release',
|
||||
reference: reservationId,
|
||||
amount: 0,
|
||||
});
|
||||
} catch {
|
||||
/* the reservation stays for reconciliation */
|
||||
}
|
||||
}
|
||||
const message = error instanceof Error ? error.message : 'Structuring failed';
|
||||
console.error('[0pt-workbench] structure failed:', message);
|
||||
return NextResponse.json(
|
||||
{ error: 'STRUCTURE_FAILED', message, reservation_id: reservationId },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { Doc0UploadClient } from '@/src/document-workbench/doc0-upload-client';
|
||||
import {
|
||||
DocumentUploadCoordinator,
|
||||
type CoordinatedUpload,
|
||||
} from '@/src/document-workbench/upload-coordinator';
|
||||
import { PostgresUploadAttemptStore } from '@/src/document-workbench/upload-attempt-store';
|
||||
import {
|
||||
createProjectAuthorizer,
|
||||
projectAuthorizationConfigured,
|
||||
} from '@/src/document-workbench/project-access';
|
||||
import { readDocumentWorkbenchRuntime } from '@/src/document-workbench/runtime-config';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { isValidScopeId, resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const CLASSIFICATIONS = [
|
||||
'public',
|
||||
'internal',
|
||||
'confidential',
|
||||
'restricted',
|
||||
'personal-data',
|
||||
'financial',
|
||||
'legal',
|
||||
] as const;
|
||||
|
||||
function isClassification(value: string): value is (typeof CLASSIFICATIONS)[number] {
|
||||
return (CLASSIFICATIONS as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
function idempotencyKey(request: NextRequest, form: FormData): string | undefined {
|
||||
const fromHeader = request.headers.get('idempotency-key');
|
||||
const fromBody = form.get('idempotency_key');
|
||||
const value = fromHeader ?? (typeof fromBody === 'string' ? fromBody : undefined);
|
||||
return value && /^[\x21-\x7e]{1,256}$/.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/0pt/documents/upload — customer document upload.
|
||||
*
|
||||
* multipart/form-data:
|
||||
* file (required) the original bytes; never trusted metadata
|
||||
* project_id (required) verified project the file belongs to
|
||||
* idempotency_key (required) or `Idempotency-Key` header
|
||||
* classification optional, defaults to `restricted` (conservative)
|
||||
*
|
||||
* The tenant and actor come ONLY from middleware's verified headers. The route
|
||||
* fails closed when project authorization or DOC0 is not configured.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
const { tenantId, actorId } = verified.scope;
|
||||
|
||||
const runtimeConfig = readDocumentWorkbenchRuntime();
|
||||
if (!runtimeConfig.doc0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'DOC0_NOT_CONFIGURED',
|
||||
message: 'Document upload is not available until DOC0 is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
if (!projectAuthorizationConfigured()) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'PROJECT_AUTHORIZATION_NOT_CONFIGURED',
|
||||
message: 'Document upload is not available until project authorization is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const databaseUrl = repositoryDatabaseUrl();
|
||||
if (!databaseUrl) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'UPLOAD_JOURNAL_NOT_CONFIGURED',
|
||||
message: 'Document upload is not available until its durable journal is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const declaredLength = Number(request.headers.get('content-length') ?? '0');
|
||||
if (Number.isFinite(declaredLength) && declaredLength > runtimeConfig.doc0.maxUploadBytes + 128 * 1024) {
|
||||
return NextResponse.json(
|
||||
{ error: 'PAYLOAD_TOO_LARGE', message: 'The uploaded file is too large' },
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
let form: FormData;
|
||||
try {
|
||||
form = await request.formData();
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_UPLOAD', message: 'A multipart form with a file is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const file = form.get('file');
|
||||
const projectId = form.get('project_id');
|
||||
const key = idempotencyKey(request, form);
|
||||
const classificationRaw = form.get('classification');
|
||||
const classification =
|
||||
typeof classificationRaw === 'string' && classificationRaw.trim()
|
||||
? classificationRaw.trim()
|
||||
: 'restricted';
|
||||
|
||||
if (!(file instanceof File) || file.size <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_UPLOAD', message: 'A non-empty file is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (!isValidScopeId(projectId)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_PROJECT', message: 'A valid project_id is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (!key) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'IDEMPOTENCY_KEY_REQUIRED',
|
||||
message: 'An idempotency key is required for document uploads',
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (!isClassification(classification)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_CLASSIFICATION', message: 'Unknown classification' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (file.size > runtimeConfig.doc0.maxUploadBytes) {
|
||||
return NextResponse.json(
|
||||
{ error: 'PAYLOAD_TOO_LARGE', message: 'The uploaded file is too large' },
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
let bytes: Uint8Array;
|
||||
try {
|
||||
bytes = new Uint8Array(await file.arrayBuffer());
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_UPLOAD', message: 'The uploaded file could not be read' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (bytes.byteLength === 0 || bytes.byteLength !== file.size) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_UPLOAD', message: 'The uploaded file is incomplete' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const authorize = createProjectAuthorizer();
|
||||
const sql = getRepositorySql(databaseUrl);
|
||||
// DOC0 authorizes the SERVICE identity and requires x-actor-id to be an
|
||||
// actor that identity holds a grant for. The end-user actor is still the
|
||||
// journal/authorization scope on our side; only the DOC0 call acts as the
|
||||
// service.
|
||||
const doc0ActorId = runtimeConfig.doc0.actorId ?? actorId;
|
||||
const doc0Client = new Doc0UploadClient({
|
||||
baseUrl: runtimeConfig.doc0.baseUrl,
|
||||
serviceToken: runtimeConfig.doc0.serviceToken,
|
||||
maxBytes: runtimeConfig.doc0.maxUploadBytes,
|
||||
});
|
||||
const coordinator = new DocumentUploadCoordinator({
|
||||
attempts: new PostgresUploadAttemptStore(sql),
|
||||
doc0: {
|
||||
upload: (input) => doc0Client.upload({ ...input, actorId: doc0ActorId }),
|
||||
inspect: (input) => doc0Client.inspect({ ...input, actorId: doc0ActorId }),
|
||||
},
|
||||
authorize: async (scope) => authorize(scope),
|
||||
maxBytes: runtimeConfig.doc0.maxUploadBytes,
|
||||
});
|
||||
|
||||
let outcome: CoordinatedUpload;
|
||||
try {
|
||||
outcome = await coordinator.execute({
|
||||
tenantId,
|
||||
projectId,
|
||||
actorId,
|
||||
requestId: request.headers.get('x-request-id') ?? crypto.randomUUID(),
|
||||
idempotencyKey: key,
|
||||
filename: file.name || 'source',
|
||||
mimeType: file.type || 'application/octet-stream',
|
||||
classification,
|
||||
bytes,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Upload failed';
|
||||
if (/not authorized/i.test(message)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'OPT_ACCESS_DENIED', message: 'Project access is not authorized' },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
if (/cannot be reused/i.test(message)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'IDEMPOTENCY_CONFLICT',
|
||||
message: 'The idempotency key was already used for different content',
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ error: 'UPLOAD_FAILED', message }, { status: 400 });
|
||||
}
|
||||
|
||||
if (outcome.status === 'receipt_verified') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'receipt_verified',
|
||||
document_id: outcome.receipt.documentId,
|
||||
version_id: outcome.receipt.versionId,
|
||||
checksum_sha256: outcome.receipt.checksumSha256,
|
||||
pipeline_stage: outcome.receipt.pipelineStage,
|
||||
},
|
||||
{ status: 201 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'outcome_unknown',
|
||||
message:
|
||||
'The upload may have been accepted. Its journal record is reported below; it does not prove storage or extraction.',
|
||||
observation: outcome.observation ?? { status: 'reconciliation_required' },
|
||||
},
|
||||
{ status: 202 },
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,6 @@ import { parseBody, qualityBridgeRunSchema } from "@/src/validation/0pt-schemas"
|
||||
import { qualityService } from "@/src/services/quality";
|
||||
import { ensureBaselineRules } from "@/src/quality/quality-bridge";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@@ -36,11 +35,6 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
// Tenant-scoped write (auto-provisions baseline rules + stores a run):
|
||||
// the internal service principal must stay inside its server-configured
|
||||
// tenant allowlist, never a tenant named by the caller.
|
||||
const guard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (guard) return guard;
|
||||
|
||||
await ensureBaselineRules(qualityService, {
|
||||
tenant_id: body.tenant_id,
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { requireRouteAuth } from "@/src/auth/require-route-auth";
|
||||
import { createAud0Client } from "@/src/clients/aud0-client";
|
||||
import {
|
||||
addNote,
|
||||
findNote,
|
||||
listNotes,
|
||||
NoteNotFoundError,
|
||||
NoteVersionConflictError,
|
||||
updateNote,
|
||||
} from "@/lib/order-notes-store";
|
||||
import { getOrder } from "@/lib/orders-store";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
|
||||
// GET/POST/PATCH /api/admin/order-notes — persisted collaboration state på
|
||||
// admin-orders (kernel: @siax/collaboration). Ligger utanför middleware.ts:s
|
||||
// matcher (/api/0pt/*), så auth läggs på direkt via requireRouteAuth, precis
|
||||
// som /api/admin/metrics — fail-closed Zitadel-verifiering, 401 utan token.
|
||||
//
|
||||
// Tenant-guard: tenant_id hämtas SERVER-SIDE från ordern (aldrig från
|
||||
// klienten) och jämförs mot den verifierade kontextens tenant — mismatch är
|
||||
// 403. Conflict semantics: PATCH med stale `version` -> 409 + aktuell version
|
||||
// (optimistisk samtidighet; last-write-wins först EFTER en medveten reload).
|
||||
|
||||
const AUDIT_CAPABILITY = "admin.order_notes";
|
||||
|
||||
async function audit(
|
||||
tenantId: string | null,
|
||||
actorId: string,
|
||||
resourceId: string,
|
||||
eventType: string,
|
||||
payload: unknown,
|
||||
): Promise<void> {
|
||||
// Best effort: AUD0 är evidence, inte en skriv-buffert — ett audit-fel får
|
||||
// aldrig rulla tillbaka en lyckad note-skrivning.
|
||||
try {
|
||||
await createAud0Client().ingestEvent({
|
||||
event_id: `aud_${crypto.randomUUID()}`,
|
||||
event_type: eventType,
|
||||
tenant_id: tenantId ?? "anonymous",
|
||||
project_id: "0pt",
|
||||
actor_id: actorId,
|
||||
app_id: "0pt",
|
||||
capability_id: AUDIT_CAPABILITY,
|
||||
resource_type: "order_note",
|
||||
resource_id: resourceId,
|
||||
risk_level: "L1",
|
||||
payload,
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
} catch {
|
||||
// swallow — see comment above
|
||||
}
|
||||
}
|
||||
|
||||
function tenantGuard(ctxTenant: string, orderTenant: string | null | undefined): NextResponse | null {
|
||||
if (!orderTenant) return null; // legacy anonymous draft — admin-ytan får annotera
|
||||
if (ctxTenant !== orderTenant) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "OPT_ACCESS_DENIED",
|
||||
message: "order belongs to a different tenant than the authenticated token",
|
||||
details: { order_tenant: orderTenant },
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
const orderId = req.nextUrl.searchParams.get("order_id");
|
||||
if (!orderId) {
|
||||
return NextResponse.json({ error: "order_id query parameter is required" }, { status: 400 });
|
||||
}
|
||||
const order = await getOrder(orderId);
|
||||
if (!order) {
|
||||
return NextResponse.json({ error: "order_not_found", order_id: orderId }, { status: 404 });
|
||||
}
|
||||
const denied = tenantGuard(auth.ctx.tenantId, order.tenant_id);
|
||||
if (denied) return denied;
|
||||
const notes = await listNotes(orderId);
|
||||
return NextResponse.json({ order_id: orderId, notes });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
let body: { order_id?: string; body?: string };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
if (!body.order_id || !body.body || !String(body.body).trim()) {
|
||||
return NextResponse.json(
|
||||
{ error: "order_id and non-empty body are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const order = await getOrder(body.order_id);
|
||||
if (!order) {
|
||||
return NextResponse.json({ error: "order_not_found", order_id: body.order_id }, { status: 404 });
|
||||
}
|
||||
const denied = tenantGuard(auth.ctx.tenantId, order.tenant_id);
|
||||
if (denied) return denied;
|
||||
try {
|
||||
const note = await addNote({
|
||||
order_id: body.order_id,
|
||||
tenant_id: order.tenant_id ?? null,
|
||||
author_id: auth.ctx.actorId,
|
||||
body: String(body.body),
|
||||
});
|
||||
await audit(note.tenant_id, auth.ctx.actorId, note.note_id, "order_note.created", {
|
||||
order_id: note.order_id,
|
||||
clock: note.clock,
|
||||
});
|
||||
return NextResponse.json(note, { status: 201 });
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
let body: { note_id?: string; body?: string; version?: number };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
if (!body.note_id || !body.body || !Number.isInteger(body.version)) {
|
||||
return NextResponse.json(
|
||||
{ error: "note_id, body and integer version are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
// Server-authoritative tenant check: slå upp noten (och dess order) INNAN
|
||||
// någon skrivning — klienten får aldrig säga vilken tenant en note tillhör.
|
||||
const existing = await findNote(body.note_id);
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "note_not_found" }, { status: 404 });
|
||||
}
|
||||
const order = await getOrder(existing.order_id);
|
||||
const denied = tenantGuard(auth.ctx.tenantId, order?.tenant_id ?? existing.tenant_id);
|
||||
if (denied) return denied;
|
||||
try {
|
||||
const note = await updateNote({
|
||||
note_id: body.note_id,
|
||||
author_id: auth.ctx.actorId,
|
||||
body: String(body.body),
|
||||
expected_version: body.version as number,
|
||||
});
|
||||
await audit(note.tenant_id, auth.ctx.actorId, note.note_id, "order_note.updated", {
|
||||
order_id: note.order_id,
|
||||
version: note.version,
|
||||
clock: note.clock,
|
||||
});
|
||||
return NextResponse.json(note);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NoteVersionConflictError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "version_conflict",
|
||||
message: err.message,
|
||||
expected_version: err.expectedVersion,
|
||||
current_version: err.currentVersion,
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
if (err instanceof NoteNotFoundError) {
|
||||
return NextResponse.json({ error: "note_not_found" }, { status: 404 });
|
||||
}
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { signSession, SESSION_COOKIE } from '@/lib/auth';
|
||||
import {
|
||||
OIDC_SESSION_TTL_SECONDS,
|
||||
OIDC_STATE_COOKIE,
|
||||
appBaseUrl,
|
||||
exchangeCode,
|
||||
readOidcConfig,
|
||||
verifyIdToken,
|
||||
} from '@/lib/oidc';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
function safeNext(value: unknown): string {
|
||||
if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) {
|
||||
return '/portal/dokument';
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** GET /api/auth/callback — finish OIDC, verify the id_token, set the session. */
|
||||
export async function GET(request: NextRequest) {
|
||||
const config = readOidcConfig();
|
||||
const fail = (reason: string) =>
|
||||
NextResponse.redirect(`${appBaseUrl()}/portal/dokument?auth_error=${encodeURIComponent(reason)}`);
|
||||
if (!config) return fail('auth_not_configured');
|
||||
|
||||
const state = request.nextUrl.searchParams.get('state');
|
||||
const code = request.nextUrl.searchParams.get('code');
|
||||
const error = request.nextUrl.searchParams.get('error');
|
||||
if (error) return fail('provider_error');
|
||||
if (!state || !code) return fail('missing_code');
|
||||
|
||||
const raw = request.cookies.get(OIDC_STATE_COOKIE)?.value;
|
||||
if (!raw) return fail('missing_state');
|
||||
let stored: { state?: unknown; nonce?: unknown; verifier?: unknown; next?: unknown; ts?: unknown };
|
||||
try {
|
||||
stored = JSON.parse(raw);
|
||||
} catch {
|
||||
return fail('bad_state');
|
||||
}
|
||||
if (
|
||||
stored.state !== state ||
|
||||
typeof stored.nonce !== 'string' ||
|
||||
typeof stored.verifier !== 'string' ||
|
||||
typeof stored.ts !== 'number' ||
|
||||
Date.now() - stored.ts > 10 * 60 * 1000
|
||||
) {
|
||||
return fail('bad_state');
|
||||
}
|
||||
|
||||
try {
|
||||
const { idToken, accessToken } = await exchangeCode(config, code, stored.verifier);
|
||||
const verified = await verifyIdToken(config, idToken, stored.nonce, accessToken);
|
||||
const session = await signSession({
|
||||
sub: verified.sub,
|
||||
tenantId: verified.tenantId,
|
||||
email: verified.email ?? '',
|
||||
exp: Date.now() + OIDC_SESSION_TTL_SECONDS * 1000,
|
||||
});
|
||||
const response = NextResponse.redirect(`${appBaseUrl()}${safeNext(stored.next)}`);
|
||||
response.cookies.set(SESSION_COOKIE, session, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: appBaseUrl().startsWith('https://'),
|
||||
path: '/',
|
||||
maxAge: OIDC_SESSION_TTL_SECONDS,
|
||||
});
|
||||
response.cookies.set(OIDC_STATE_COOKIE, '', { path: '/', maxAge: 0 });
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
// Codes only (e.g. token_exchange_failed), never tokens or claims.
|
||||
console.error(
|
||||
'[0pt-auth] oidc callback failed:',
|
||||
error instanceof Error ? error.message : 'unknown_error',
|
||||
);
|
||||
return fail('verification_failed');
|
||||
}
|
||||
}
|
||||
+13
-79
@@ -1,95 +1,29 @@
|
||||
import { timingSafeEqual } from 'node:crypto';
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { signSession, SESSION_COOKIE } from '@/lib/auth';
|
||||
import {
|
||||
OIDC_STATE_COOKIE,
|
||||
appBaseUrl,
|
||||
authorizeUrl,
|
||||
createOidcState,
|
||||
createPkce,
|
||||
readOidcConfig,
|
||||
} from '@/lib/oidc';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
function safeNext(value: string | null): string {
|
||||
if (!value) return '/portal/dokument';
|
||||
if (!value.startsWith('/') || value.startsWith('//')) return '/portal/dokument';
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/auth/login — start the Zitadel OIDC Authorization Code + PKCE flow.
|
||||
* Redirects back to /api/auth/callback, which sets the verified session cookie.
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
const config = readOidcConfig();
|
||||
if (!config) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'auth_not_configured',
|
||||
message: 'Zitadel OIDC is not configured (ZITADEL_OIDC_CLIENT_ID/SECRET)',
|
||||
},
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const next = safeNext(request.nextUrl.searchParams.get('next'));
|
||||
const { state, nonce } = createOidcState();
|
||||
const { verifier, challenge } = createPkce();
|
||||
const response = NextResponse.redirect(authorizeUrl(config, state, nonce, challenge));
|
||||
response.cookies.set(OIDC_STATE_COOKIE, JSON.stringify({ state, nonce, verifier, next, ts: Date.now() }), {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: appBaseUrl().startsWith('https://'),
|
||||
path: '/',
|
||||
maxAge: 600,
|
||||
});
|
||||
return response;
|
||||
}
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { signSession, SESSION_COOKIE } from "@/lib/auth";
|
||||
|
||||
// POST /api/auth/login — guarded dev login (scaffold). Requires AUTH_SECRET +
|
||||
// a matching DEV_LOGIN_KEY. Never available in production; real login is GET.
|
||||
// a matching DEV_LOGIN_KEY. Production replaces this with Auth.js + OAuth.
|
||||
export async function POST(req: NextRequest) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'forbidden', message: 'Dev-login is disabled in production' } },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
const { email, key } = await req.json().catch(() => ({ email: undefined, key: undefined }));
|
||||
if (!process.env.AUTH_SECRET) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'auth_not_configured', message: 'AUTH_SECRET saknas' } },
|
||||
{ status: 501 },
|
||||
);
|
||||
return NextResponse.json({ error: { code: "auth_not_configured", message: "AUTH_SECRET saknas" } }, { status: 501 });
|
||||
}
|
||||
const devKey = process.env.DEV_LOGIN_KEY;
|
||||
// Constant-time compare: a plain !== leaks the number of matching leading
|
||||
// bytes via response timing, letting an attacker recover DEV_LOGIN_KEY
|
||||
// byte-by-byte instead of an all-or-nothing guess.
|
||||
const keyBuf = Buffer.from(typeof key === 'string' ? key : '');
|
||||
const devKeyBuf = Buffer.from(devKey ?? '');
|
||||
const keysMatch =
|
||||
Boolean(devKey) && keyBuf.length === devKeyBuf.length && timingSafeEqual(keyBuf, devKeyBuf);
|
||||
// byte-by-byte instead of it being an all-or-nothing guess.
|
||||
const keyBuf = Buffer.from(typeof key === "string" ? key : "");
|
||||
const devKeyBuf = Buffer.from(devKey ?? "");
|
||||
const keysMatch = Boolean(devKey) && keyBuf.length === devKeyBuf.length && timingSafeEqual(keyBuf, devKeyBuf);
|
||||
if (!keysMatch) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'forbidden', message: 'Dev-login kräver giltig nyckel' } },
|
||||
{ status: 403 },
|
||||
);
|
||||
return NextResponse.json({ error: { code: "forbidden", message: "Dev-login kräver giltig nyckel" } }, { status: 403 });
|
||||
}
|
||||
if (!email) {
|
||||
return NextResponse.json({ error: { code: 'bad_request', message: 'email krävs' } }, { status: 400 });
|
||||
return NextResponse.json({ error: { code: "bad_request", message: "email krävs" } }, { status: 400 });
|
||||
}
|
||||
const token = await signSession({ email, exp: Date.now() + 7 * 24 * 60 * 60 * 1000 });
|
||||
const token = await signSession({ email, iat: Date.now() });
|
||||
const res = NextResponse.json({ ok: true, email });
|
||||
res.cookies.set(SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: true,
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
});
|
||||
res.cookies.set(SESSION_COOKIE, token, { httpOnly: true, sameSite: "lax", secure: true, path: "/", maxAge: 60 * 60 * 24 * 7 });
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { verifySession, SESSION_COOKIE } from '@/lib/auth';
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { verifySession, SESSION_COOKIE } from "@/lib/auth";
|
||||
|
||||
// GET /api/auth/me — current session (or null).
|
||||
export async function GET(req: NextRequest) {
|
||||
const token = req.cookies.get(SESSION_COOKIE)?.value;
|
||||
const session = await verifySession(token);
|
||||
return NextResponse.json({
|
||||
user: session
|
||||
? {
|
||||
email: session.email ?? null,
|
||||
sub: typeof session.sub === 'string' ? session.sub : null,
|
||||
tenantId: typeof session.tenantId === 'string' ? session.tenantId : null,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
return NextResponse.json({ user: session ? { email: session.email } : null });
|
||||
}
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { listOwnedOrders } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
|
||||
/**
|
||||
* GET /api/orders/export (våg 3.4, DoD §56) — CSV-export of the authenticated
|
||||
* owner's orders. Same fail-closed auth as GET/POST /api/orders (this path is
|
||||
* outside middleware.ts's /api/0pt matcher, so the Zitadel verifier runs here).
|
||||
*
|
||||
* RFC 4180: CRLF line endings, fields containing comma, quote or newline are
|
||||
* quoted with doubled quotes, header row always present.
|
||||
*
|
||||
* Locale note: deposit_ore / total_ore are exported as RAW ÖRE — öre is the
|
||||
* canonical unit in the order contract; formatting (SEK, thousand separators)
|
||||
* happens in the UI layer, never in the export.
|
||||
*
|
||||
* Cap note (DoD §56): NO row truncation/limiting — an export must be complete.
|
||||
*/
|
||||
|
||||
function csvEscape(value: string): string {
|
||||
if (/[",\r\n]/.test(value)) return `"${value.replace(/"/g, '""')}"`;
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
try {
|
||||
const orders = await listOwnedOrders(auth.owner.tenantId);
|
||||
const header = ["order_id", "flow", "status", "deposit_ore", "total_ore"];
|
||||
const rows = orders.map((o) =>
|
||||
[o.order_id, o.flow, o.status, String(o.deposit_ore), String(o.total_ore)].map(csvEscape).join(","),
|
||||
);
|
||||
const csv = [header.join(","), ...rows].join("\r\n") + "\r\n";
|
||||
const date = new Date().toISOString().slice(0, 10);
|
||||
return new NextResponse(csv, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="orders-${date}.csv"`,
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -1,270 +0,0 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createOrder, type OrderConfig, type OrderOwner } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
import { createAud0Client } from "@/src/clients/aud0-client";
|
||||
import { validateRows, defineMapping, type RowError } from "@siax/contracts/import-export";
|
||||
import { serviceById, type Flow } from "@/lib/services";
|
||||
import { IMPORT_DISPATCH_POLICY, evaluateImportDispatch } from "@/lib/import-dispatch-policy";
|
||||
import { ENTITY_TYPES, FREQUENCIES, type EntityType, type Frequency } from "@/lib/data";
|
||||
|
||||
// C8: CSV-import of orders — the symmetric counterpart of GET /api/orders/export
|
||||
// (våg 3.4). The server is the ONLY authority: the raw CSV is parsed here
|
||||
// (RFC 4180, no eval), re-validated here via the frozen @siax/contracts kernel
|
||||
// (validateRows) plus host field rules, and executed through the EXISTING order
|
||||
// creation logic (createOrder) so imported rows are real tenant-owned orders.
|
||||
// Client-side wizard parsing is presentation entropy, never trusted.
|
||||
//
|
||||
// Fail-closed properties:
|
||||
// - No principal (requireOrderOwner) → 401, no parse, no writes.
|
||||
// - Unknown header column → 400 (never silently dropped).
|
||||
// - More than MAX_IMPORT_ROWS data rows → 413 (cap, never truncate silently).
|
||||
// - execute() re-validates and imports only rows that pass; failing rows are
|
||||
// reported per row (row/field/code) and never created. Each order insert is
|
||||
// individually atomic via createOrder (per-row transactional semantics);
|
||||
// a failing row can never corrupt a passing one.
|
||||
// - Audit: every successful execute emits an AUD0 event via 0pt's sole producer
|
||||
// boundary (durable outbox when DATABASE_URL is configured). Emission failure
|
||||
// is logged, never blocks the import (the outbox pattern owns delivery).
|
||||
|
||||
// DES1GN ADR D3 (§31): taken härstammar från ImportDispatchPolicy — ett objekt,
|
||||
// en sanning. Inline-taket är oförändrat (500); rader > policy.maxRows (5000)
|
||||
// är N0D-dispatch-signalen (descriptor-gate: svarar 413 + hint tills N0D-workern
|
||||
// är verifierad — aldrig tyst trunkering, aldrig tyst dispatch).
|
||||
export const MAX_IMPORT_ROWS = IMPORT_DISPATCH_POLICY.maxInlineRows;
|
||||
const MAX_CSV_CHARS = IMPORT_DISPATCH_POLICY.maxBytes;
|
||||
const IMPORT_COLUMNS = ["flow", "service_type", "type", "volume", "frequency", "markets"] as const;
|
||||
const FLOWS: readonly Flow[] = ["catalog", "custom", "subscription"];
|
||||
const MAX_VOLUME = 1_000_000;
|
||||
|
||||
interface ImportRowError extends RowError {
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface ParsedCsv {
|
||||
rows: Record<string, string>[];
|
||||
headerError?: string;
|
||||
}
|
||||
|
||||
/** Minimal RFC 4180 parser: quoted fields, doubled quotes, CRLF or LF. No eval. */
|
||||
export function parseCsv(text: string): ParsedCsv {
|
||||
const rows: string[][] = [];
|
||||
let field = "";
|
||||
let row: string[] = [];
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (inQuotes) {
|
||||
if (ch === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else {
|
||||
inQuotes = false;
|
||||
}
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
} else if (ch === '"') {
|
||||
inQuotes = true;
|
||||
} else if (ch === ",") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
} else if (ch === "\n") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
rows.push(row);
|
||||
row = [];
|
||||
} else if (ch === "\r") {
|
||||
// consumed by the following \n (or ignored for bare CR)
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
}
|
||||
if (field.length > 0 || row.length > 0) {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
}
|
||||
const nonEmpty = rows.filter((r) => r.length > 1 || (r[0] ?? "").trim() !== "");
|
||||
if (nonEmpty.length === 0) return { rows: [] };
|
||||
const header = nonEmpty[0].map((h) => h.trim().toLowerCase());
|
||||
const unknown = header.filter((h) => h !== "" && !(IMPORT_COLUMNS as readonly string[]).includes(h));
|
||||
if (unknown.length > 0) {
|
||||
return { rows: [], headerError: `Okänd kolumn: ${unknown.join(", ")} (tillåtna: ${IMPORT_COLUMNS.join(", ")})` };
|
||||
}
|
||||
return {
|
||||
rows: nonEmpty.slice(1).map((cells) => {
|
||||
const obj: Record<string, string> = {};
|
||||
header.forEach((h, idx) => {
|
||||
if (h) obj[h] = (cells[idx] ?? "").trim();
|
||||
});
|
||||
return obj;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Host field rules on top of the kernel's required/type checks. */
|
||||
function hostValidate(rows: Record<string, string>[]): ImportRowError[] {
|
||||
const errors: ImportRowError[] = [];
|
||||
rows.forEach((r, idx) => {
|
||||
const rowNo = idx + 1;
|
||||
const flow = (r.flow ?? "").trim() as Flow;
|
||||
if (flow && !FLOWS.includes(flow)) {
|
||||
errors.push({ row: rowNo, field: "flow", code: "bad_type", message: `Ogiltigt flow "${r.flow}" (tillåtna: ${FLOWS.join(", ")})` });
|
||||
}
|
||||
const st = (r.service_type ?? "").trim();
|
||||
if (st && !serviceById(st)) {
|
||||
errors.push({ row: rowNo, field: "service_type", code: "bad_type", message: `Okänd service_type "${st}"` });
|
||||
}
|
||||
const type = (r.type ?? "").trim();
|
||||
if (type && !ENTITY_TYPES.some((t) => t.id === type)) {
|
||||
errors.push({ row: rowNo, field: "type", code: "bad_type", message: `Ogiltig typ "${type}" (tillåtna: ${ENTITY_TYPES.map((t) => t.id).join(", ")})` });
|
||||
}
|
||||
const volume = (r.volume ?? "").trim();
|
||||
if (volume === "") {
|
||||
// optional — order logic applies flow defaults
|
||||
} else if (!/^\d+$/.test(volume) || Number(volume) < 1 || Number(volume) > MAX_VOLUME) {
|
||||
errors.push({ row: rowNo, field: "volume", code: "bad_type", message: `volume måste vara ett positivt heltal ≤ ${MAX_VOLUME}` });
|
||||
}
|
||||
const freq = (r.frequency ?? "").trim();
|
||||
if (freq && !FREQUENCIES.includes(freq as Frequency)) {
|
||||
errors.push({ row: rowNo, field: "frequency", code: "bad_type", message: `Ogiltig frequency "${freq}" (tillåtna: ${FREQUENCIES.join(", ")})` });
|
||||
}
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
function buildConfig(r: Record<string, string>): OrderConfig {
|
||||
const config: OrderConfig = {};
|
||||
if ((r.service_type ?? "").trim()) config.service_type = r.service_type.trim();
|
||||
if ((r.type ?? "").trim()) config.type = r.type.trim() as EntityType;
|
||||
if ((r.volume ?? "").trim()) config.volume = Number(r.volume.trim());
|
||||
if ((r.frequency ?? "").trim()) config.frequency = r.frequency.trim() as Frequency;
|
||||
if ((r.markets ?? "").trim()) {
|
||||
config.markets = r.markets.split(";").map((m) => m.trim()).filter(Boolean);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
export interface ImportReport {
|
||||
totalRows: number;
|
||||
validRows: number;
|
||||
errorCount: number;
|
||||
errors: ImportRowError[];
|
||||
}
|
||||
|
||||
/** Server-authoritative validation: kernel required/type checks + host rules. */
|
||||
export function validateImport(csv: string): { report: ImportReport; rows: Record<string, string>[]; headerError?: string } {
|
||||
const { rows, headerError } = parseCsv(csv);
|
||||
if (headerError) return { report: { totalRows: 0, validRows: 0, errorCount: 1, errors: [{ row: 0, field: "header", code: "format", message: headerError }] }, rows: [], headerError };
|
||||
const mapping = defineMapping({ columns: IMPORT_COLUMNS.map((c) => ({ source: c, target: c, required: c === "flow" })) });
|
||||
const kernel = validateRows(rows, mapping);
|
||||
const host = hostValidate(rows);
|
||||
const kernelErrors: ImportRowError[] = kernel.errors.map((e) => ({ ...e, message: e.message ?? `Valideringsfel (${e.code})` }));
|
||||
const errors = [...kernelErrors, ...host];
|
||||
return {
|
||||
report: {
|
||||
totalRows: rows.length,
|
||||
validRows: rows.length - new Set(errors.map((e) => e.row)).size,
|
||||
errorCount: errors.length,
|
||||
errors,
|
||||
},
|
||||
rows,
|
||||
};
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
const owner: OrderOwner = auth.owner;
|
||||
|
||||
let body: { mode?: string; csv?: string };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON" } }, { status: 400 });
|
||||
}
|
||||
const mode = body.mode;
|
||||
const csv = body.csv;
|
||||
if (!mode || !["validate", "dry_run", "execute"].includes(mode)) {
|
||||
return NextResponse.json({ error: { code: "bad_mode", message: "mode måste vara validate | dry_run | execute" } }, { status: 400 });
|
||||
}
|
||||
if (typeof csv !== "string" || csv.trim() === "") {
|
||||
return NextResponse.json({ error: { code: "bad_csv", message: "csv saknas eller är tom" } }, { status: 400 });
|
||||
}
|
||||
const csvBytes = Buffer.byteLength(csv, "utf8");
|
||||
if (evaluateImportDispatch({ format: "csv", bytes: csvBytes, rows: 0 }).verdict === "byte_cap_exceeded") {
|
||||
return NextResponse.json({ error: { code: "csv_too_large", message: `CSV större än ${MAX_CSV_CHARS} bytes` } }, { status: 413 });
|
||||
}
|
||||
try {
|
||||
const { report, rows, headerError } = validateImport(csv);
|
||||
if (headerError) {
|
||||
return NextResponse.json({ error: { code: "bad_header", message: headerError }, report }, { status: 400 });
|
||||
}
|
||||
const dispatchVerdict = evaluateImportDispatch({ format: "csv", bytes: csvBytes, rows: rows.length });
|
||||
if (dispatchVerdict.verdict === "dispatch_n0d") {
|
||||
// DES1GN D3-signalen: den här volymen ÄR ett N0D-jobb (0pt.import_execute_job).
|
||||
// Descriptor-gaten är stängd (N0D-worker UNVERIFIED) -> fail-closed 413 med hint.
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: "n0d_dispatch_required",
|
||||
message: `Import med ${rows.length} rader ska köras som N0D-jobb (0pt.import_execute_job); dispatch är ännu inte aktiverad`,
|
||||
hint: { capability_id: "0pt.import_execute", job_type: "0pt.import_execute_job", status: "UNVERIFIED" },
|
||||
},
|
||||
},
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
if (dispatchVerdict.verdict === "row_cap_exceeded") {
|
||||
return NextResponse.json({ error: { code: "row_cap_exceeded", message: `Max ${MAX_IMPORT_ROWS} rader per import` } }, { status: 413 });
|
||||
}
|
||||
|
||||
if (mode === "validate" || mode === "dry_run") {
|
||||
// No writes — dry_run is exactly validate plus an explicit rehearsal count.
|
||||
return NextResponse.json({ mode, ...report, would_import: report.validRows });
|
||||
}
|
||||
|
||||
// mode === "execute": server re-validates and imports ONLY passing rows.
|
||||
const failedRows = new Set(report.errors.map((e) => e.row));
|
||||
const orderIds: string[] = [];
|
||||
let imported = 0;
|
||||
for (let idx = 0; idx < rows.length; idx++) {
|
||||
if (failedRows.has(idx + 1)) continue;
|
||||
const r = rows[idx];
|
||||
try {
|
||||
const { order } = await createOrder((r.flow ?? "").trim(), buildConfig(r), undefined, owner);
|
||||
orderIds.push(order.order_id);
|
||||
imported++;
|
||||
} catch (err: unknown) {
|
||||
report.errors.push({ row: idx + 1, field: "row", code: "format", message: `Skapning misslyckades: ${err instanceof Error ? err.message : "okänt fel"}` });
|
||||
}
|
||||
}
|
||||
|
||||
// AUD0 audit — 0pt's sole producer boundary; durable outbox under DATABASE_URL.
|
||||
try {
|
||||
const aud0 = createAud0Client();
|
||||
await aud0.ingestEvent({
|
||||
event_id: (globalThis.crypto?.randomUUID?.() ?? `evt-${Date.now()}`),
|
||||
event_type: "0pt.orders.import",
|
||||
tenant_id: owner.tenantId,
|
||||
project_id: "0pt-orders",
|
||||
actor_id: owner.subject,
|
||||
app_id: "0pt",
|
||||
capability_id: "orders.import",
|
||||
resource_type: "order",
|
||||
resource_id: orderIds[0] ?? "none",
|
||||
risk_level: "L2",
|
||||
payload: { imported, total_rows: report.totalRows, error_count: report.errors.length, order_ids: orderIds },
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
} catch (auditErr: unknown) {
|
||||
console.error("[0pt-orders-import] AUD0 emission failed (import not rolled back):", auditErr);
|
||||
}
|
||||
|
||||
return NextResponse.json({ mode, imported, totalRows: report.totalRows, validRows: report.validRows, errorCount: report.errors.length, errors: report.errors.slice(0, 100), order_ids: orderIds });
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createOrder, listOwnedOrders, IdempotencyKeyConflictError, type OrderConfig } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { resolveAdvanceAction, buildOrderInboxItem } from "@/lib/order-flow";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../siax-error-mapping";
|
||||
|
||||
// POST /api/orders (docs/04) — create a draft order from a configurator config.
|
||||
@@ -57,10 +56,7 @@ export async function GET(req: NextRequest) {
|
||||
if (auth.response) return auth.response;
|
||||
try {
|
||||
const orders = await listOwnedOrders(auth.owner.tenantId);
|
||||
// ADR-0001: servern resolvér advance-aktionen per order — klienten
|
||||
// renderar bara (ActionGate). Policy ägs här, inte i UI-lagret.
|
||||
const withActions = orders.map((o) => ({ ...o, advance_action: resolveAdvanceAction(o.status), inbox_item: buildOrderInboxItem(o) }));
|
||||
return NextResponse.json(withActions);
|
||||
return NextResponse.json(orders);
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
|
||||
@@ -10,11 +10,9 @@ import { checkAllDependencies, isReady } from "@/lib/health-checks";
|
||||
// readiness probe at this route, not /api/health, to stop routing traffic to
|
||||
// an instance whose database is down without restarting it.
|
||||
//
|
||||
// Load-bearing by absence: only the database (see
|
||||
// Today the only load-bearing dependency is the database (see
|
||||
// `lib/health-checks.ts#isReady`) -- engine/stripe/queue are optional
|
||||
// integrations 0pt is designed to run without. Load-bearing by FAILURE: all
|
||||
// of them. A dependency somebody configured and that then fails a live round
|
||||
// trip makes this instance not-ready, whichever one it is.
|
||||
// integrations 0pt is designed to run without.
|
||||
export async function GET() {
|
||||
const deps = await checkAllDependencies();
|
||||
const ready = isReady(deps);
|
||||
|
||||
+20
-23
@@ -1,30 +1,27 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { engineFetch, hasEngine } from "@/lib/engine";
|
||||
import { engineFetch } from "@/lib/engine";
|
||||
|
||||
// An unavailable or malformed screening source is never evidence of no match.
|
||||
// GET /api/screen?q=Name — OpenSanctions screening (sanctions/PEP). VERIFY
|
||||
// commercial terms before production volume. Defers to engine when running.
|
||||
export async function GET(req: NextRequest) {
|
||||
const q = req.nextUrl.searchParams.get("q")?.trim() ?? "";
|
||||
if (!q) return NextResponse.json({ error: { code: "bad_request", message: "q krävs" } }, { status: 400 });
|
||||
const unavailable = () => NextResponse.json({ error: { code: "source_unavailable", message: "Screeningkällan är inte tillgänglig" } }, { status: 503 });
|
||||
const q = req.nextUrl.searchParams.get("q") ?? "";
|
||||
if (!q) return NextResponse.json({ matches: [] });
|
||||
|
||||
const eng = await engineFetch(`/screen?q=${encodeURIComponent(q)}`);
|
||||
if (eng && eng.ok) return NextResponse.json(await eng.json());
|
||||
|
||||
try {
|
||||
if (hasEngine()) {
|
||||
const eng = await engineFetch(`/screen?q=${encodeURIComponent(q)}`);
|
||||
if (!eng?.ok) return unavailable();
|
||||
const data: unknown = await eng.json();
|
||||
if (!data || typeof data !== "object" || (!Array.isArray((data as { matches?: unknown }).matches) || (data as { source_status?: unknown }).source_status !== "ok")) return unavailable();
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
const r = await fetch(`https://api.opensanctions.org/search/default?q=${encodeURIComponent(q)}&limit=5`, {
|
||||
headers: { "User-Agent": "0pt/0.1 (+https://0pt.app; SIAX)" }, cache: "no-store",
|
||||
headers: { "User-Agent": "0pt/0.1 (+https://0pt.app; SIAX)" },
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!r.ok) return unavailable();
|
||||
const data: unknown = await r.json();
|
||||
if (!data || typeof data !== "object" || !Array.isArray((data as { results?: unknown }).results)) return unavailable();
|
||||
const results = (data as { results: unknown[] }).results;
|
||||
if (results.some((item) => !item || typeof item !== "object" || Array.isArray(item))) return unavailable();
|
||||
return NextResponse.json({ source: "opensanctions", matches: results.map((item) => {
|
||||
const x = item as { caption?: unknown; score?: unknown; schema?: unknown };
|
||||
return { name: x.caption ?? null, score: x.score ?? null, schema: x.schema ?? null };
|
||||
}) });
|
||||
} catch { return unavailable(); }
|
||||
if (!r.ok) return NextResponse.json({ matches: [], source: "opensanctions" });
|
||||
const data = (await r.json()) as { results?: { caption?: string; score?: number; schema?: string }[] };
|
||||
return NextResponse.json({
|
||||
source: "opensanctions",
|
||||
matches: (data.results ?? []).map((x) => ({ name: x.caption ?? null, score: x.score ?? null, schema: x.schema ?? null })),
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json({ matches: [], source: "opensanctions" });
|
||||
}
|
||||
}
|
||||
|
||||
+25
-21
@@ -1,30 +1,34 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { engineFetch, hasEngine } from "@/lib/engine";
|
||||
import { engineFetch } from "@/lib/engine";
|
||||
|
||||
// A missing record is distinct from an unavailable or malformed source.
|
||||
// GET /api/vehicles?plate=XX-99-YY — RDW (NL) open vehicle data (technical/fleet
|
||||
// only, no owner PII). Defers to the engine when running; else calls RDW directly.
|
||||
export async function GET(req: NextRequest) {
|
||||
const plate = (req.nextUrl.searchParams.get("plate") ?? "").toUpperCase().replace(/[-\s]/g, "").replace(/[^A-Z0-9]/g, "");
|
||||
if (!plate) return NextResponse.json({ error: { code: "bad_request", message: "plate krävs" } }, { status: 400 });
|
||||
const unavailable = () => NextResponse.json({ error: { code: "source_unavailable", message: "Fordonskällan är inte tillgänglig" } }, { status: 503 });
|
||||
|
||||
const eng = await engineFetch(`/vehicles/${plate}`);
|
||||
if (eng && eng.ok) return NextResponse.json(await eng.json());
|
||||
|
||||
try {
|
||||
if (hasEngine()) {
|
||||
const eng = await engineFetch(`/vehicles/${plate}`);
|
||||
if (!eng?.ok) return unavailable();
|
||||
const data: unknown = await eng.json();
|
||||
if (!data || typeof data !== "object" || Array.isArray(data) || (data as { source_status?: unknown }).source_status !== "ok") return unavailable();
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
const r = await fetch(`https://opendata.rdw.nl/resource/m9d7-ebf2.json?kenteken=${encodeURIComponent(plate)}`, {
|
||||
headers: { "User-Agent": "0pt/0.1 (+https://0pt.app; SIAX)" }, cache: "no-store",
|
||||
headers: { "User-Agent": "0pt/0.1 (+https://0pt.app; SIAX)" },
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!r.ok) return unavailable();
|
||||
const data: unknown = await r.json();
|
||||
if (!Array.isArray(data) || data.some((item) => !item || typeof item !== "object" || Array.isArray(item))) return unavailable();
|
||||
if (!data.length) return NextResponse.json({ vehicle: null });
|
||||
const d = data[0] as Record<string, string>;
|
||||
if (d.datum_eerste_toelating != null && typeof d.datum_eerste_toelating !== "string") return unavailable();
|
||||
return NextResponse.json({ source: "rdw", vehicle: { reg_plate: plate, market: "NL", make: d.merk ?? null,
|
||||
model: d.handelsbenaming ?? null, year: (d.datum_eerste_toelating ?? "").slice(0, 4) || null },
|
||||
provenance: { level: 3, source: "rdw" } });
|
||||
} catch { return unavailable(); }
|
||||
if (!r.ok) return NextResponse.json({ vehicle: null }, { status: 200 });
|
||||
const arr = (await r.json()) as Record<string, string>[];
|
||||
if (!arr.length) return NextResponse.json({ vehicle: null });
|
||||
const d = arr[0];
|
||||
return NextResponse.json({
|
||||
source: "rdw",
|
||||
vehicle: {
|
||||
reg_plate: plate, market: "NL",
|
||||
make: d.merk ?? null, model: d.handelsbenaming ?? null,
|
||||
year: (d.datum_eerste_toelating ?? "").slice(0, 4) || null,
|
||||
},
|
||||
provenance: { level: 3, source: "rdw" },
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json({ vehicle: null, error: "fetch_failed" }, { status: 200 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/**
|
||||
* GET /api/version — deployment identity for automated verification.
|
||||
*
|
||||
* Returns only non-sensitive build identity (no env values, no config). The
|
||||
* scheduled prod-smoke workflow compares `commit` with the current main SHA so
|
||||
* "the container is up" is never confused with "the intended commit is live".
|
||||
*/
|
||||
export async function GET() {
|
||||
const commit =
|
||||
process.env.SOURCE_COMMIT ?? process.env.GIT_COMMIT_SHA ?? process.env.VERCEL_GIT_COMMIT_SHA ?? null;
|
||||
return NextResponse.json(
|
||||
{
|
||||
service: '0pt-web',
|
||||
commit,
|
||||
built_at: process.env.BUILD_TIME ?? null,
|
||||
},
|
||||
{ headers: { 'cache-control': 'no-store' } },
|
||||
);
|
||||
}
|
||||
@@ -1,97 +1,38 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import type Stripe from 'stripe';
|
||||
import { getStripe } from '@/lib/stripe';
|
||||
import { getOrder, setStatusIfCurrent } from '@/lib/orders-store';
|
||||
import { isSiaxError } from '../../siax-error-mapping';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { PostgresCreditPurchaseStore } from '@/src/document-workbench/credit-purchase-store';
|
||||
import {
|
||||
StripeCreditVerificationError,
|
||||
verifyStripeCreditPurchase,
|
||||
} from '@/src/document-workbench/stripe-credit-verification';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
|
||||
/**
|
||||
* Credit purchases are granted ONLY from Stripe's own re-read of the session
|
||||
* and payment intent. The webhook body is a trigger, never proof of price or
|
||||
* payment. The ledger command is idempotent, so duplicate deliveries are safe.
|
||||
*/
|
||||
async function handleCreditPurchase(
|
||||
stripe: NonNullable<ReturnType<typeof getStripe>>,
|
||||
session: Stripe.Checkout.Session,
|
||||
) {
|
||||
const tenantId = session.metadata?.tenant_id;
|
||||
const purchaseId = session.metadata?.purchase_id;
|
||||
if (!tenantId || !purchaseId) {
|
||||
return NextResponse.json({ error: 'unmatched_session' }, { status: 422 });
|
||||
}
|
||||
const url = repositoryDatabaseUrl();
|
||||
if (!url) {
|
||||
return NextResponse.json({ received: false, reason: 'credits_not_configured' }, { status: 503 });
|
||||
}
|
||||
try {
|
||||
const store = new PostgresCreditPurchaseStore(getRepositorySql(url));
|
||||
const snapshot = await store.get(tenantId, purchaseId);
|
||||
if (!snapshot) {
|
||||
// Do not acknowledge a paid purchase we cannot bind to a server snapshot.
|
||||
return NextResponse.json({ received: false, reason: 'purchase_not_found' }, { status: 503 });
|
||||
}
|
||||
if (snapshot.checkoutSessionId !== session.id) {
|
||||
return NextResponse.json({ error: 'session_mismatch' }, { status: 422 });
|
||||
}
|
||||
const command = await verifyStripeCreditPurchase(stripe, snapshot, { tenantId });
|
||||
const result = await new PostgresCreditLedger(getRepositorySql(url)).apply(command);
|
||||
return NextResponse.json({ received: true, credited: !result.replay, balance: result.balance });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Credit reconciliation failed';
|
||||
if (error instanceof StripeCreditVerificationError) {
|
||||
const terminal = ['mismatch', 'not_paid', 'refunded', 'unsupported'].includes(error.reason);
|
||||
return NextResponse.json(
|
||||
{ received: false, reason: error.reason, message },
|
||||
{ status: terminal ? 422 : 503 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ received: false, reason: 'ledger_unavailable', message }, { status: 503 });
|
||||
}
|
||||
}
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import type Stripe from "stripe";
|
||||
import { getStripe } from "@/lib/stripe";
|
||||
import { getOrder, setStatusIfCurrent } from "@/lib/orders-store";
|
||||
import { isSiaxError } from "../../siax-error-mapping";
|
||||
|
||||
// POST /api/webhooks/stripe (docs/04) — verify signature, advance order status.
|
||||
export async function POST(req: NextRequest) {
|
||||
const stripe = getStripe();
|
||||
const whSecret = process.env.STRIPE_WEBHOOK_SECRET;
|
||||
const sig = req.headers.get('stripe-signature');
|
||||
const sig = req.headers.get("stripe-signature");
|
||||
if (!stripe || !whSecret) {
|
||||
// Never acknowledge an event that was not signature-verified and processed.
|
||||
// A non-2xx response keeps Stripe's delivery retry/reconciliation path open.
|
||||
return NextResponse.json({ received: false, reason: 'not_configured' }, { status: 503 });
|
||||
return NextResponse.json({ received: false, reason: "not_configured" }, { status: 503 });
|
||||
}
|
||||
if (!sig) {
|
||||
return NextResponse.json({ error: 'missing_signature' }, { status: 400 });
|
||||
return NextResponse.json({ error: "missing_signature" }, { status: 400 });
|
||||
}
|
||||
const body = await req.text();
|
||||
let event;
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(body, sig, whSecret);
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'bad_signature' }, { status: 400 });
|
||||
return NextResponse.json({ error: "bad_signature" }, { status: 400 });
|
||||
}
|
||||
if (
|
||||
event.type === 'checkout.session.completed' ||
|
||||
event.type === 'checkout.session.async_payment_succeeded'
|
||||
) {
|
||||
if (event.type === "checkout.session.completed") {
|
||||
const s = event.data.object as Stripe.Checkout.Session;
|
||||
const oid = s.metadata?.order_id;
|
||||
const kind = s.metadata?.kind;
|
||||
if (kind === '0pt_credit_purchase') {
|
||||
return handleCreditPurchase(stripe, s);
|
||||
if (!oid || (kind !== "deposit" && kind !== "balance")) {
|
||||
return NextResponse.json({ error: "unmatched_session" }, { status: 422 });
|
||||
}
|
||||
if (!oid || (kind !== 'deposit' && kind !== 'balance')) {
|
||||
return NextResponse.json({ error: 'unmatched_session' }, { status: 422 });
|
||||
}
|
||||
if (s.payment_status !== 'paid') {
|
||||
return NextResponse.json({ error: 'payment_not_confirmed' }, { status: 503 });
|
||||
if (s.payment_status !== "paid") {
|
||||
return NextResponse.json({ error: "payment_not_confirmed" }, { status: 503 });
|
||||
}
|
||||
// 0pt#53: durable-store failure -> documented non-2xx (never an opaque 500,
|
||||
// and never a silent received:true for a paid event that was NOT processed —
|
||||
@@ -100,52 +41,47 @@ export async function POST(req: NextRequest) {
|
||||
try {
|
||||
order = await getOrder(oid);
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err))
|
||||
return NextResponse.json({ received: false, reason: 'store_unavailable' }, { status: 503 });
|
||||
if (isSiaxError(err)) return NextResponse.json({ received: false, reason: "store_unavailable" }, { status: 503 });
|
||||
throw err;
|
||||
}
|
||||
if (!order) return NextResponse.json({ error: 'order_not_found' }, { status: 503 });
|
||||
if (!order) return NextResponse.json({ error: "order_not_found" }, { status: 503 });
|
||||
if (!order.tenant_id || !order.buyer_subject) {
|
||||
// A legacy anonymous draft is not a payable order. Do not silently
|
||||
// acknowledge a paid event until an audited owner-remediation path exists.
|
||||
return NextResponse.json({ error: 'order_owner_missing' }, { status: 503 });
|
||||
return NextResponse.json({ error: "order_owner_missing" }, { status: 503 });
|
||||
}
|
||||
const expectedAmount = kind === 'balance' ? order.balance_ore : order.deposit_ore;
|
||||
if (s.amount_total !== expectedAmount || s.currency?.toLowerCase() !== 'sek') {
|
||||
return NextResponse.json({ error: 'payment_mismatch' }, { status: 422 });
|
||||
const expectedAmount = kind === "balance" ? order.balance_ore : order.deposit_ore;
|
||||
if (s.amount_total !== expectedAmount || s.currency?.toLowerCase() !== "sek") {
|
||||
return NextResponse.json({ error: "payment_mismatch" }, { status: 422 });
|
||||
}
|
||||
if (kind === 'balance') {
|
||||
if (order.status !== 'accepted' && order.status !== 'delivered') {
|
||||
return NextResponse.json({ error: 'invalid_order_state' }, { status: 409 });
|
||||
if (kind === "balance") {
|
||||
if (order.status !== "accepted" && order.status !== "delivered") {
|
||||
return NextResponse.json({ error: "invalid_order_state" }, { status: 409 });
|
||||
}
|
||||
let delivered = false;
|
||||
try {
|
||||
delivered = order.status === 'accepted' && !!(await setStatusIfCurrent(oid, 'accepted', 'delivered'));
|
||||
delivered = order.status === "accepted" && !!(await setStatusIfCurrent(oid, "accepted", "delivered"));
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err))
|
||||
return NextResponse.json({ received: false, reason: 'store_unavailable' }, { status: 503 });
|
||||
if (isSiaxError(err)) return NextResponse.json({ received: false, reason: "store_unavailable" }, { status: 503 });
|
||||
throw err;
|
||||
}
|
||||
if (order.status === 'accepted' && !delivered) {
|
||||
return NextResponse.json({ error: 'order_update_failed' }, { status: 503 });
|
||||
if (order.status === "accepted" && !delivered) {
|
||||
return NextResponse.json({ error: "order_update_failed" }, { status: 503 });
|
||||
}
|
||||
} else {
|
||||
const alreadyAdvanced = ['in_production', 'review', 'revision', 'accepted', 'delivered'].includes(
|
||||
order.status,
|
||||
);
|
||||
if (order.status !== 'draft' && order.status !== 'deposit_pending' && !alreadyAdvanced) {
|
||||
return NextResponse.json({ error: 'invalid_order_state' }, { status: 409 });
|
||||
const alreadyAdvanced = ["in_production", "review", "revision", "accepted", "delivered"].includes(order.status);
|
||||
if (order.status !== "draft" && order.status !== "deposit_pending" && !alreadyAdvanced) {
|
||||
return NextResponse.json({ error: "invalid_order_state" }, { status: 409 });
|
||||
}
|
||||
let advanced = true;
|
||||
try {
|
||||
advanced = alreadyAdvanced || !!(await setStatusIfCurrent(oid, order.status, 'in_production'));
|
||||
advanced = alreadyAdvanced || !!(await setStatusIfCurrent(oid, order.status, "in_production"));
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err))
|
||||
return NextResponse.json({ received: false, reason: 'store_unavailable' }, { status: 503 });
|
||||
if (isSiaxError(err)) return NextResponse.json({ received: false, reason: "store_unavailable" }, { status: 503 });
|
||||
throw err;
|
||||
}
|
||||
if (!advanced) {
|
||||
return NextResponse.json({ error: 'order_update_failed' }, { status: 503 });
|
||||
return NextResponse.json({ error: "order_update_failed" }, { status: 503 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ export default function DescribePage() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{svc ? <p className="mt-3 text-sm text-muted-foreground">{t(svc.covers)} <span className="text-muted-foreground">→ {t(svc.deliverable)}</span></p> : null}
|
||||
{svc ? <p className="mt-3 text-sm text-muted-foreground">{t(svc.covers)} <span className="text-muted-foreground/60">→ {t(svc.deliverable)}</span></p> : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-8">
|
||||
|
||||
+2
-2
@@ -273,7 +273,7 @@ export default function SourcesPage() {
|
||||
>
|
||||
<td className="px-3 py-3 align-top">
|
||||
<span className="text-[15px] tracking-tight">{s.name}</span>
|
||||
<span className="ml-2 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground">
|
||||
<span className="ml-2 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground/60">
|
||||
{s.source_id}
|
||||
</span>
|
||||
</td>
|
||||
@@ -301,7 +301,7 @@ export default function SourcesPage() {
|
||||
<p className="font-mono text-[10.5px] uppercase tracking-[0.08em] text-muted-foreground">
|
||||
{rows.length} {t({ en: "sources · every field carries its provenance", sv: "källor · varje fält bär sin härkomst" })}
|
||||
</p>
|
||||
<p className="font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground">
|
||||
<p className="font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground/70">
|
||||
{t({ en: "Licence terms verified before use", sv: "Licensvillkor verifieras innan användning" })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useParams, useRouter, useSearchParams } from "next/navigation";
|
||||
import { Suspense, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useParams } from "next/navigation";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Header } from "@/components/header";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
import { DataArtifact } from "@/components/data-artifact";
|
||||
@@ -142,43 +142,14 @@ function findDataset(raw: string | undefined): Dataset | undefined {
|
||||
return CATALOG.find((d) => d.id === slug);
|
||||
}
|
||||
|
||||
const TAB_KEYS = TABS.map((t) => t.key);
|
||||
function isTabKey(value: string | null): value is TabKey {
|
||||
return value !== null && (TAB_KEYS as string[]).includes(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flikvalet lever i URL:en (?tab=…, kernel-konventionen: URL state är kanoniskt)
|
||||
* — "Tillbaka" återställer flik, och en delad länk öppnar samma flik. Komponenten
|
||||
* wrappas i Suspense eftersom useSearchParams kräver det vid prerender.
|
||||
*/
|
||||
export default function DatasetDetailPage() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<DatasetDetailInner />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function DatasetDetailInner() {
|
||||
const t = useT();
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const reveal = useReveal<HTMLDivElement>();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const tabParam = searchParams.get("tab");
|
||||
const tab: TabKey = isTabKey(tabParam) ? tabParam : "overview";
|
||||
function setTabNext(next: TabKey) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
if (next === "overview") params.delete("tab");
|
||||
else params.set("tab", next);
|
||||
const qs = params.toString();
|
||||
router.replace(qs ? `?${qs}` : window.location.pathname, { scroll: false });
|
||||
}
|
||||
|
||||
const [status, setStatus] = useState<"loading" | "ready" | "empty" | "error">("loading");
|
||||
const [dataset, setDataset] = useState<Dataset | null>(null);
|
||||
const [tab, setTab] = useState<TabKey>("overview");
|
||||
const attempt = useRef(0);
|
||||
|
||||
const load = useCallback(() => {
|
||||
@@ -224,7 +195,7 @@ function DatasetDetailInner() {
|
||||
<section className="py-24">
|
||||
<ErrorState title={t({ en: "Couldn't load the dataset", sv: "Kunde inte hämta datasetet" })} onRetry={load} />
|
||||
<div className="mt-10">
|
||||
<Link href="/katalog" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
|
||||
<Link href="/#katalog" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
|
||||
{t({ en: "← Back to the catalog", sv: "← Till katalogen" })}
|
||||
</Link>
|
||||
</div>
|
||||
@@ -240,14 +211,14 @@ function DatasetDetailInner() {
|
||||
ctaLabel={t({ en: "Compose a job", sv: "Komponera ett jobb" })}
|
||||
/>
|
||||
<div className="mt-10">
|
||||
<Link href="/katalog" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
|
||||
<Link href="/#katalog" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground underline-offset-4 hover:text-foreground hover:underline">
|
||||
{t({ en: "← Back to the catalog", sv: "← Till katalogen" })}
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{status === "ready" && dataset ? <DatasetView d={dataset} tab={tab} setTab={setTabNext} /> : null}
|
||||
{status === "ready" && dataset ? <DatasetView d={dataset} tab={tab} setTab={setTab} /> : null}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
@@ -278,7 +249,7 @@ function DatasetView({ d, tab, setTab }: { d: Dataset; tab: TabKey; setTab: (k:
|
||||
<div ref={revealRef}>
|
||||
{/* breadcrumb */}
|
||||
<div className="reveal flex items-center gap-2 border-b border-border py-4 font-mono text-[11px] uppercase tracking-[0.12em] text-muted-foreground">
|
||||
<Link href="/katalog" className="underline-offset-4 transition-colors hover:text-foreground hover:underline">
|
||||
<Link href="/#katalog" className="underline-offset-4 transition-colors hover:text-foreground hover:underline">
|
||||
{t({ en: "Catalog", sv: "Katalog" })}
|
||||
</Link>
|
||||
<span className="text-border">/</span>
|
||||
|
||||
+7
-49
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
import { Header } from "@/components/header";
|
||||
import { useReveal } from "@/hooks/use-reveal";
|
||||
@@ -37,56 +37,14 @@ function level(c: number): ProvLevel {
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter + sök lever i URL:en (kernel-konventionen: URL state är kanoniskt och
|
||||
* återställbart) — "Tillbaka" från en detaljsida återställer exakt vy, och en
|
||||
* delad länk öppnar samma filtrering. pages-komponenten wrappar i Suspense
|
||||
* eftersom useSearchParams kräver det vid prerender.
|
||||
*/
|
||||
export default function CatalogPage() {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<CatalogInner />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function CatalogInner() {
|
||||
const t = useT();
|
||||
const ref = useReveal<HTMLDivElement>();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [items, setItems] = useState<CatalogItem[] | null>(null);
|
||||
const [err, setErr] = useState(false);
|
||||
const filter = searchParams.get("filter") ?? "all";
|
||||
const q = searchParams.get("q") ?? "";
|
||||
// Lokalt utkast för sökfältet (skrivtick), synkat debouncerat till URL:en.
|
||||
const [qDraft, setQDraft] = useState(q);
|
||||
const urlSync = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
useEffect(() => { setQDraft(q); }, [q]);
|
||||
|
||||
function applyState(next: { q?: string; filter?: string }) {
|
||||
const params = new URLSearchParams();
|
||||
const nq = (next.q ?? q).trim().slice(0, 120);
|
||||
const nf = next.filter ?? filter;
|
||||
if (nq) params.set("q", nq);
|
||||
if (nf && nf !== "all") params.set("filter", nf);
|
||||
const qs = params.toString();
|
||||
router.replace(qs ? `/katalog?${qs}` : "/katalog", { scroll: false });
|
||||
}
|
||||
|
||||
function setFilterNext(next: string) {
|
||||
if (urlSync.current) clearTimeout(urlSync.current);
|
||||
applyState({ filter: next });
|
||||
}
|
||||
|
||||
function setQNext(next: string) {
|
||||
setQDraft(next);
|
||||
if (urlSync.current) clearTimeout(urlSync.current);
|
||||
urlSync.current = setTimeout(() => applyState({ q: next }), 250);
|
||||
}
|
||||
|
||||
useEffect(() => () => { if (urlSync.current) clearTimeout(urlSync.current); }, []);
|
||||
const [filter, setFilter] = useState("all");
|
||||
const [q, setQ] = useState("");
|
||||
|
||||
function load() {
|
||||
setErr(false);
|
||||
@@ -131,7 +89,7 @@ function CatalogInner() {
|
||||
{FILTERS.map((f) => (
|
||||
<button
|
||||
key={f.key}
|
||||
onClick={() => setFilterNext(f.key)}
|
||||
onClick={() => setFilter(f.key)}
|
||||
aria-pressed={filter === f.key}
|
||||
className="border px-3 py-1.5 font-mono text-[11px] uppercase tracking-[0.08em] transition-colors"
|
||||
style={{
|
||||
@@ -145,8 +103,8 @@ function CatalogInner() {
|
||||
))}
|
||||
</div>
|
||||
<input
|
||||
value={qDraft}
|
||||
onChange={(e) => setQNext(e.target.value)}
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder={t({ en: "Search datasets…", sv: "Sök dataset…" })}
|
||||
aria-label={t({ en: "Search datasets", sv: "Sök dataset" })}
|
||||
className="w-full max-w-xs border border-border bg-input px-3 py-2 font-mono text-xs outline-none focus:border-foreground sm:w-auto"
|
||||
|
||||
@@ -1,515 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { FileDropzone } from '@siax/ui/components/file-dropzone';
|
||||
import { useT } from '@/components/locale-provider';
|
||||
import { PortalShell } from '@/components/portal-shell';
|
||||
|
||||
/**
|
||||
* /portal/dokument — the customer's document workspace.
|
||||
*
|
||||
* Three honest steps:
|
||||
* 1. Upload the original file (real bytes, multipart) into DOC0.
|
||||
* 2. Describe the structure you want and the fields to extract.
|
||||
* 3. Review the evidence-bound output and download JSON/CSV.
|
||||
*
|
||||
* Nothing on this page fabricates success: a 503 means the capability is not
|
||||
* configured, and an "outcome unknown" upload is shown as exactly that.
|
||||
*/
|
||||
|
||||
type Receipt = {
|
||||
document_id: string;
|
||||
version_id: string;
|
||||
checksum_sha256: string;
|
||||
pipeline_stage: string;
|
||||
};
|
||||
|
||||
type FieldRow = { name: string; type: 'string' | 'integer' | 'boolean' | 'decimal' | 'date' };
|
||||
|
||||
type Evidence = {
|
||||
field: string;
|
||||
sourceId: string;
|
||||
start: number;
|
||||
end: number;
|
||||
transform: string;
|
||||
};
|
||||
|
||||
type StructureResponse = {
|
||||
status: 'mechanically_validated' | 'needs_review' | 'outcome_unknown';
|
||||
value?: Record<string, string | number | boolean>;
|
||||
evidence?: Evidence[];
|
||||
issues?: { field: string; code: string; row?: number }[];
|
||||
model?: {
|
||||
modelExecuted: string;
|
||||
promptTokens: number;
|
||||
completionTokens: number;
|
||||
totalTokens: number;
|
||||
costUsd?: number;
|
||||
};
|
||||
credits?: { reserved: number; charged: number; balance?: { available: number; reserved: number } };
|
||||
export?: { media_type: string; content: string };
|
||||
message?: string;
|
||||
error?: string;
|
||||
reservation_id?: string;
|
||||
};
|
||||
|
||||
type ModelsResponse = {
|
||||
models: string[];
|
||||
data_classes: string[];
|
||||
destination: string;
|
||||
external_transfer_allowed: boolean;
|
||||
max_input_tokens: number;
|
||||
max_output_tokens: number;
|
||||
price_book_version: string | null;
|
||||
};
|
||||
|
||||
const TYPES: FieldRow['type'][] = ['string', 'integer', 'decimal', 'date', 'boolean'];
|
||||
|
||||
export default function DocumentsPage() {
|
||||
const t = useT();
|
||||
const [projectId, setProjectId] = useState('');
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [receipt, setReceipt] = useState<Receipt | null>(null);
|
||||
const [uploadNote, setUploadNote] = useState<string | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [unknownOutcome, setUnknownOutcome] = useState<unknown | null>(null);
|
||||
// One idempotency key per selected file: a retry (double click, network
|
||||
// error, reload-and-pick-the-same-file) returns the SAME document instead of
|
||||
// creating a duplicate. Picking a different file resets it.
|
||||
const uploadKey = useRef<string | null>(null);
|
||||
|
||||
const [instruction, setInstruction] = useState('');
|
||||
const [fields, setFields] = useState<FieldRow[]>([{ name: 'organization', type: 'string' }]);
|
||||
const [models, setModels] = useState<ModelsResponse | null>(null);
|
||||
const [modelsError, setModelsError] = useState<string | null>(null);
|
||||
const [modelId, setModelId] = useState('');
|
||||
const [dataClass, setDataClass] = useState('low');
|
||||
const [format, setFormat] = useState<'json' | 'csv'>('json');
|
||||
const [structuring, setStructuring] = useState(false);
|
||||
const [result, setResult] = useState<StructureResponse | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const stored = window.localStorage.getItem('0pt.project_id');
|
||||
if (stored) setProjectId(stored);
|
||||
fetch('/api/0pt/documents/models', { cache: 'no-store' })
|
||||
.then(async (r) => {
|
||||
const body = (await r.json()) as ModelsResponse & { message?: string };
|
||||
if (!r.ok) {
|
||||
setModelsError(body.message ?? 'Modellpolicyn är inte konfigurerad');
|
||||
return;
|
||||
}
|
||||
setModels(body);
|
||||
setModelId((current) => current || body.models[0] || '');
|
||||
setDataClass((current) =>
|
||||
body.data_classes.includes(current) ? current : (body.data_classes[0] ?? 'low'),
|
||||
);
|
||||
})
|
||||
.catch(() => setModelsError('Kunde inte läsa modellpolicyn'));
|
||||
}, []);
|
||||
|
||||
const upload = useCallback(async () => {
|
||||
if (!file || uploading) return;
|
||||
if (!projectId.trim()) {
|
||||
setError(t({ en: 'A project id is required', sv: 'Ett projekt-id krävs' }));
|
||||
return;
|
||||
}
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
setUploadNote(null);
|
||||
setUnknownOutcome(null);
|
||||
setReceipt(null);
|
||||
window.localStorage.setItem('0pt.project_id', projectId.trim());
|
||||
const form = new FormData();
|
||||
form.set('file', file);
|
||||
form.set('project_id', projectId.trim());
|
||||
const key = uploadKey.current ?? crypto.randomUUID();
|
||||
uploadKey.current = key;
|
||||
form.set('idempotency_key', key);
|
||||
form.set('classification', 'restricted');
|
||||
try {
|
||||
const response = await fetch('/api/0pt/documents/upload', {
|
||||
method: 'POST',
|
||||
body: form,
|
||||
headers: { 'x-request-id': crypto.randomUUID() },
|
||||
});
|
||||
const body = (await response.json().catch(() => ({}))) as Record<string, unknown> & {
|
||||
status?: string;
|
||||
message?: string;
|
||||
error?: string;
|
||||
};
|
||||
if (response.status === 201) {
|
||||
setReceipt({
|
||||
document_id: String(body.document_id),
|
||||
version_id: String(body.version_id),
|
||||
checksum_sha256: String(body.checksum_sha256),
|
||||
pipeline_stage: String(body.pipeline_stage),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (response.status === 202) {
|
||||
setUnknownOutcome(body.observation ?? body);
|
||||
setUploadNote(
|
||||
t({
|
||||
en: 'The upload may have been accepted. It is not confirmed.',
|
||||
sv: 'Uppladdningen kan ha tagits emot. Den är inte bekräftad.',
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setUploadNote(
|
||||
body.message ?? body.error ?? t({ en: 'Upload failed', sv: 'Uppladdningen misslyckades' }),
|
||||
);
|
||||
} catch {
|
||||
setUploadNote(t({ en: 'Upload failed', sv: 'Uppladdningen misslyckades' }));
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}, [file, projectId, t, uploading]);
|
||||
|
||||
const structure = useCallback(async () => {
|
||||
if (!receipt || structuring) return;
|
||||
if (!instruction.trim()) {
|
||||
setError(t({ en: 'Describe the structure you want', sv: 'Beskriv strukturen du vill ha' }));
|
||||
return;
|
||||
}
|
||||
if (!modelId) {
|
||||
setError(t({ en: 'No approved model is configured', sv: 'Ingen godkänd modell är konfigurerad' }));
|
||||
return;
|
||||
}
|
||||
setStructuring(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
try {
|
||||
const response = await fetch('/api/0pt/documents/structure', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', 'x-request-id': crypto.randomUUID() },
|
||||
body: JSON.stringify({
|
||||
project_id: projectId.trim(),
|
||||
document_id: receipt.document_id,
|
||||
version_id: receipt.version_id,
|
||||
checksum_sha256: receipt.checksum_sha256,
|
||||
pipeline_stage: receipt.pipeline_stage,
|
||||
instruction,
|
||||
fields,
|
||||
model_id: modelId,
|
||||
data_class: dataClass,
|
||||
format,
|
||||
}),
|
||||
});
|
||||
const body = (await response.json().catch(() => ({}))) as StructureResponse;
|
||||
if (response.ok || response.status === 202) {
|
||||
setResult(body);
|
||||
} else {
|
||||
setError(
|
||||
body.message ?? body.error ?? t({ en: 'Structuring failed', sv: 'Struktureringen misslyckades' }),
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
setError(t({ en: 'Structuring failed', sv: 'Struktureringen misslyckades' }));
|
||||
} finally {
|
||||
setStructuring(false);
|
||||
}
|
||||
}, [receipt, structuring, instruction, modelId, dataClass, projectId, fields, format, t]);
|
||||
|
||||
function download() {
|
||||
if (!result?.export) return;
|
||||
const blob = new Blob([result.export.content], { type: result.export.media_type });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = url;
|
||||
anchor.download = `0pt-${receipt?.document_id ?? 'result'}.${format}`;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
function addField() {
|
||||
if (fields.length >= 100) return;
|
||||
setFields((current) => [...current, { name: `field_${current.length + 1}`, type: 'string' }]);
|
||||
}
|
||||
|
||||
function updateField(index: number, patch: Partial<FieldRow>) {
|
||||
setFields((current) => current.map((row, i) => (i === index ? { ...row, ...patch } : row)));
|
||||
}
|
||||
|
||||
function removeField(index: number) {
|
||||
setFields((current) => current.filter((_, i) => i !== index));
|
||||
}
|
||||
|
||||
const card = 'border border-border bg-background p-6';
|
||||
const label = 'font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground';
|
||||
const input =
|
||||
'mt-2 w-full border border-border bg-background px-3 py-2 font-mono text-[13px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
|
||||
|
||||
return (
|
||||
<PortalShell variant="customer" title={t({ en: 'Documents', sv: 'Dokument' })}>
|
||||
<div className="mx-auto w-full max-w-4xl space-y-6">
|
||||
<p className="max-w-2xl text-pretty text-[15px] leading-relaxed text-muted-foreground">
|
||||
{t({
|
||||
en: 'Upload a file, describe how it should be structured, and get evidence-bound data you can download.',
|
||||
sv: 'Ladda upp en fil, beskriv hur den ska struktureras och få evidensbunden data som du kan ladda ner.',
|
||||
})}
|
||||
</p>
|
||||
|
||||
{/* 1 · upload */}
|
||||
<section className={card}>
|
||||
<div className="flex items-baseline justify-between gap-4">
|
||||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||||
{t({ en: '1 · Source', sv: '1 · Underlag' })}
|
||||
</h2>
|
||||
{receipt ? (
|
||||
<span
|
||||
className="font-mono text-[10px] uppercase tracking-[0.18em]"
|
||||
style={{ color: 'var(--accent-red)' }}
|
||||
>
|
||||
{t({ en: 'uploaded', sv: 'uppladdad' })}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<label className="mt-4 block">
|
||||
<span className={label}>{t({ en: 'project id', sv: 'projekt-id' })}</span>
|
||||
<input
|
||||
className={input}
|
||||
value={projectId}
|
||||
onChange={(event) => setProjectId(event.target.value)}
|
||||
placeholder="prj_…"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<FileDropzone
|
||||
className="mt-4"
|
||||
label={t({ en: 'choose a file', sv: 'välj en fil' })}
|
||||
hint={file ? file.name : t({ en: 'PDF, Word, Excel, CSV, images…', sv: 'PDF, Word, Excel, CSV, bilder…' })}
|
||||
disabled={uploading}
|
||||
onFiles={(files) => {
|
||||
uploadKey.current = null;
|
||||
setFile(files[0] ?? null);
|
||||
}}
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={upload}
|
||||
disabled={!file || uploading}
|
||||
className="mt-4 border border-foreground bg-foreground px-5 py-2.5 font-mono text-[11px] uppercase tracking-[0.18em] text-background disabled:opacity-40"
|
||||
>
|
||||
{uploading ? t({ en: 'uploading…', sv: 'laddar upp…' }) : t({ en: 'upload', sv: 'ladda upp' })}
|
||||
</button>
|
||||
|
||||
{receipt ? (
|
||||
<dl className="mt-4 grid gap-2 font-mono text-[11px] text-muted-foreground sm:grid-cols-2">
|
||||
<div>
|
||||
<dt className="uppercase tracking-[0.16em]">document</dt>
|
||||
<dd className="break-all">{receipt.document_id}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="uppercase tracking-[0.16em]">version</dt>
|
||||
<dd className="break-all">{receipt.version_id}</dd>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<dt className="uppercase tracking-[0.16em]">sha-256</dt>
|
||||
<dd className="break-all">{receipt.checksum_sha256}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
) : null}
|
||||
{uploadNote ? <p className="mt-4 text-[14px] text-muted-foreground">{uploadNote}</p> : null}
|
||||
{unknownOutcome ? (
|
||||
<pre className="mt-3 overflow-auto border border-border bg-muted/30 p-3 font-mono text-[11px]">
|
||||
{JSON.stringify(unknownOutcome, null, 2)}
|
||||
</pre>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{/* 2 · structure */}
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||||
{t({ en: '2 · Desired structure', sv: '2 · Önskad struktur' })}
|
||||
</h2>
|
||||
|
||||
<label className="mt-4 block">
|
||||
<span className={label}>{t({ en: 'instruction', sv: 'instruktion' })}</span>
|
||||
<textarea
|
||||
className={`${input} min-h-[96px]`}
|
||||
value={instruction}
|
||||
maxLength={4000}
|
||||
onChange={(event) => setInstruction(event.target.value)}
|
||||
placeholder={t({
|
||||
en: 'One row per agreement with parties, term, price and notice period.',
|
||||
sv: 'En rad per avtal med parter, avtalstid, pris och uppsägningstid.',
|
||||
})}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="mt-4">
|
||||
<span className={label}>{t({ en: 'fields', sv: 'fält' })}</span>
|
||||
<div className="mt-2 space-y-2">
|
||||
{fields.map((field, index) => (
|
||||
<div key={index} className="flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
className="min-w-[160px] flex-1 border border-border bg-background px-3 py-2 font-mono text-[12px]"
|
||||
value={field.name}
|
||||
onChange={(event) => updateField(index, { name: event.target.value })}
|
||||
aria-label={`field ${index + 1}`}
|
||||
/>
|
||||
<select
|
||||
className="border border-border bg-background px-3 py-2 font-mono text-[12px]"
|
||||
value={field.type}
|
||||
onChange={(event) => updateField(index, { type: event.target.value as FieldRow['type'] })}
|
||||
>
|
||||
{TYPES.map((type) => (
|
||||
<option key={type} value={type}>
|
||||
{type}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeField(index)}
|
||||
className="px-2 font-mono text-[11px] text-muted-foreground"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={addField}
|
||||
className="mt-2 font-mono text-[11px] uppercase tracking-[0.18em] text-muted-foreground"
|
||||
>
|
||||
+ {t({ en: 'add field', sv: 'lägg till fält' })}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 sm:grid-cols-2">
|
||||
<label className="block">
|
||||
<span className={label}>{t({ en: 'model', sv: 'modell' })}</span>
|
||||
<select
|
||||
className={input}
|
||||
value={modelId}
|
||||
onChange={(event) => setModelId(event.target.value)}
|
||||
disabled={!models}
|
||||
>
|
||||
{models?.models.map((model) => (
|
||||
<option key={model} value={model}>
|
||||
{model}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className={label}>{t({ en: 'format', sv: 'format' })}</span>
|
||||
<select
|
||||
className={input}
|
||||
value={format}
|
||||
onChange={(event) => setFormat(event.target.value as 'json' | 'csv')}
|
||||
>
|
||||
<option value="json">JSON</option>
|
||||
<option value="csv">CSV</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className={label}>{t({ en: 'data class', sv: 'dataklass' })}</span>
|
||||
<select
|
||||
className={input}
|
||||
value={dataClass}
|
||||
onChange={(event) => setDataClass(event.target.value)}
|
||||
disabled={!models}
|
||||
>
|
||||
{(models?.data_classes ?? [dataClass]).map((value) => (
|
||||
<option key={value} value={value}>
|
||||
{value}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<p className="mt-2 font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">
|
||||
{t({
|
||||
en: 'External models are refused for high/restricted data.',
|
||||
sv: 'Externa modeller nekas för hög/restricted data.',
|
||||
})}
|
||||
</p>
|
||||
|
||||
{modelsError ? <p className="mt-3 text-[13px] text-muted-foreground">{modelsError}</p> : null}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={structure}
|
||||
disabled={!receipt || structuring}
|
||||
className="mt-4 border border-foreground bg-foreground px-5 py-2.5 font-mono text-[11px] uppercase tracking-[0.18em] text-background disabled:opacity-40"
|
||||
>
|
||||
{structuring
|
||||
? t({ en: 'structuring…', sv: 'strukturerar…' })
|
||||
: t({ en: 'structure', sv: 'strukturera' })}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
{/* 3 · result */}
|
||||
{(result || error) && (
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||||
{t({ en: '3 · Result', sv: '3 · Resultat' })}
|
||||
</h2>
|
||||
{error ? <p className="mt-4 text-[14px]">{error}</p> : null}
|
||||
|
||||
{result?.status === 'mechanically_validated' ? (
|
||||
<>
|
||||
<div className="mt-4 overflow-auto border border-border">
|
||||
<table className="w-full border-collapse text-left font-mono text-[12px]">
|
||||
<tbody>
|
||||
{Object.entries(result.value ?? {}).map(([key, value]) => (
|
||||
<tr key={key} className="border-b border-border last:border-b-0">
|
||||
<th className="px-3 py-2 font-normal uppercase tracking-[0.14em] text-muted-foreground">
|
||||
{key}
|
||||
</th>
|
||||
<td className="px-3 py-2">{String(value)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p className="mt-3 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
|
||||
{result.evidence?.length ?? 0} {t({ en: 'evidence spans', sv: 'evidensspann' })}
|
||||
{result.credits ? ` · ${result.credits.charged} credits` : ''}
|
||||
</p>
|
||||
{result.export ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={download}
|
||||
className="mt-4 border border-foreground px-5 py-2.5 font-mono text-[11px] uppercase tracking-[0.18em]"
|
||||
>
|
||||
{t({ en: 'download', sv: 'ladda ner' })} {format.toUpperCase()}
|
||||
</button>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{result?.status === 'needs_review' ? (
|
||||
<div className="mt-4">
|
||||
<p className="text-[14px]">
|
||||
{t({
|
||||
en: 'The model output did not pass evidence validation. Nothing was exported.',
|
||||
sv: 'Modellens svar klarade inte evidenskontrollen. Inget exporterades.',
|
||||
})}
|
||||
</p>
|
||||
<ul className="mt-3 space-y-1 font-mono text-[11px] text-muted-foreground">
|
||||
{result.issues?.map((issue, index) => (
|
||||
<li key={index}>
|
||||
{issue.field || '(root)'} · {issue.code}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{result?.status === 'outcome_unknown' ? (
|
||||
<p className="mt-4 text-[14px]">{result.message}</p>
|
||||
) : null}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</PortalShell>
|
||||
);
|
||||
}
|
||||
+175
-5
@@ -1,10 +1,180 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
import { PortalShell } from "@/components/portal-shell";
|
||||
import { LoadingSkeleton, EmptyState, ErrorState } from "@/components/states";
|
||||
import { formatSEK } from "@/lib/data";
|
||||
|
||||
/**
|
||||
* The old `/portal/files` page only sent metadata and always hit the 501
|
||||
* storage stub. Real uploads now live at `/portal/dokument`; keep the old URL
|
||||
* working instead of leaving a second, non-functional upload surface.
|
||||
* /portal/files — kundens filer. En kvadratisk mono drag-drop-zon + fillista.
|
||||
* Vid släpp: POST /api/uploads { name, mime, bytes }. Om lagring inte är kopplad
|
||||
* svarar endpointen 501 → lugn not "aktiveras vid lagring", aldrig en feltoast.
|
||||
* Uppladdade filer matar matchning & berikning.
|
||||
*/
|
||||
|
||||
interface FileRow {
|
||||
file_id: string;
|
||||
name: string;
|
||||
mime: string;
|
||||
bytes: number;
|
||||
status: string; // received · matching · enriched
|
||||
uploaded_at: string;
|
||||
}
|
||||
|
||||
const PROV_BY_STATUS: Record<string, string> = {
|
||||
enriched: "var(--prov-3)",
|
||||
matching: "var(--prov-2)",
|
||||
received: "var(--prov-1)",
|
||||
};
|
||||
|
||||
function fmtBytes(b: number): string {
|
||||
if (b < 1024) return `${b} B`;
|
||||
if (b < 1024 * 1024) return `${(b / 1024).toFixed(0)} kB`;
|
||||
return `${(b / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export default function FilesPage() {
|
||||
redirect('/portal/dokument');
|
||||
const t = useT();
|
||||
const [files, setFiles] = useState<FileRow[] | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [storageOff, setStorageOff] = useState(false);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setError(false);
|
||||
try {
|
||||
const r = await fetch("/api/uploads", { cache: "no-store" });
|
||||
if (r.status === 501) { setStorageOff(true); setFiles([]); return; }
|
||||
setFiles(await r.json());
|
||||
} catch {
|
||||
setError(true);
|
||||
}
|
||||
}, []);
|
||||
useEffect(() => { void load(); }, [load]);
|
||||
|
||||
const upload = useCallback(async (list: FileList | File[]) => {
|
||||
const arr = Array.from(list);
|
||||
if (arr.length === 0 || busy) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
for (const f of arr) {
|
||||
const r = await fetch("/api/uploads", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: f.name, mime: f.type || "application/octet-stream", bytes: f.size }),
|
||||
});
|
||||
// Env-guarded: storage not wired yet → calm note, no error.
|
||||
if (r.status === 501) { setStorageOff(true); break; }
|
||||
}
|
||||
} catch {
|
||||
// Network hiccup degrades to the storage note, never a hard error toast.
|
||||
setStorageOff(true);
|
||||
}
|
||||
setBusy(false);
|
||||
void load();
|
||||
}, [busy, load]);
|
||||
|
||||
function onDrop(e: React.DragEvent) {
|
||||
e.preventDefault();
|
||||
setDragging(false);
|
||||
if (e.dataTransfer?.files?.length) void upload(e.dataTransfer.files);
|
||||
}
|
||||
|
||||
function openPicker() { inputRef.current?.click(); }
|
||||
|
||||
return (
|
||||
<PortalShell variant="customer" title={t({ en: "Files", sv: "Filer" })}>
|
||||
{/* dropzone */}
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-label={t({ en: "Drop files to upload", sv: "Släpp filer för att ladda upp" })}
|
||||
onClick={openPicker}
|
||||
onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); openPicker(); } }}
|
||||
onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
|
||||
onDragLeave={() => setDragging(false)}
|
||||
onDrop={onDrop}
|
||||
className="relative flex aspect-[3/1] w-full cursor-pointer flex-col items-center justify-center border border-dashed bg-background text-center transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||
style={{
|
||||
borderColor: dragging ? "var(--accent-red)" : "var(--border)",
|
||||
backgroundColor: dragging ? "color-mix(in srgb, var(--accent-red) 4%, var(--background))" : undefined,
|
||||
}}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="mb-5 inline-block h-3.5 w-3.5"
|
||||
style={{ backgroundColor: dragging ? "var(--accent-red)" : "var(--foreground)" }}
|
||||
/>
|
||||
<p className="font-mono text-[10px] uppercase tracking-[0.22em] text-muted-foreground">
|
||||
{busy
|
||||
? t({ en: "uploading…", sv: "laddar upp…" })
|
||||
: dragging
|
||||
? t({ en: "drop here", sv: "släpp här" })
|
||||
: t({ en: "drag here · or click", sv: "dra hit · eller klicka" })}
|
||||
</p>
|
||||
<p className="mt-3 max-w-sm text-pretty text-[15px] leading-relaxed text-muted-foreground">
|
||||
{t({ en: "CSV, Excel, lists.", sv: "CSV, Excel, listor." })}
|
||||
<br />{t({ en: "Fed straight into matching & enrichment.", sv: "Matas in i matchning & berikning." })}
|
||||
</p>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="sr-only"
|
||||
onChange={(e) => { if (e.target.files) void upload(e.target.files); e.target.value = ""; }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{storageOff ? (
|
||||
<div className="mt-4 flex items-center gap-3 border border-border bg-secondary/40 px-4 py-3">
|
||||
<span aria-hidden className="inline-block h-2 w-2 shrink-0" style={{ backgroundColor: "var(--muted-foreground)" }} />
|
||||
<p className="font-mono text-[11px] leading-relaxed tracking-tight text-muted-foreground">
|
||||
{t({ en: "File upload activates once storage is connected.", sv: "Filuppladdning aktiveras när lagring kopplas." })}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* file list */}
|
||||
<div className="mt-8">
|
||||
{error ? (
|
||||
<ErrorState onRetry={load} />
|
||||
) : !files ? (
|
||||
<LoadingSkeleton rows={4} />
|
||||
) : files.length === 0 ? (
|
||||
<EmptyState
|
||||
title={t({ en: "No files yet.", sv: "Inga filer än." })}
|
||||
line={t({ en: "Drag in a list. It feeds straight into matching and enrichment.", sv: "Dra in en lista. Den matas direkt in i matchning och berikning." })}
|
||||
/>
|
||||
) : (
|
||||
<div className="border border-border">
|
||||
<div className="grid grid-cols-[2fr_1fr_1fr_1fr] border-b border-border bg-secondary/50 px-4 py-2.5 font-mono text-[10px] uppercase tracking-[0.1em] text-muted-foreground">
|
||||
<span>{t({ en: "File", sv: "Fil" })}</span><span>{t({ en: "Type", sv: "Typ" })}</span><span>{t({ en: "Size", sv: "Storlek" })}</span><span>{t({ en: "Status", sv: "Status" })}</span>
|
||||
</div>
|
||||
{files.map((f) => (
|
||||
<div key={f.file_id} className="grid grid-cols-[2fr_1fr_1fr_1fr] items-center border-b border-border px-4 py-3 text-sm transition-colors duration-200 last:border-b-0 hover:bg-secondary">
|
||||
<span className="truncate text-[15px] tracking-tight">{f.name}</span>
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground">{f.mime.split("/").pop()}</span>
|
||||
<span className="font-mono text-[12px] tabular-nums text-muted-foreground">{fmtBytes(f.bytes)}</span>
|
||||
<span className="inline-flex items-center gap-2 font-mono text-[10.5px] uppercase tracking-[0.08em]">
|
||||
<span
|
||||
aria-hidden
|
||||
className="inline-block h-2 w-2 shrink-0"
|
||||
style={{ backgroundColor: PROV_BY_STATUS[f.status] ?? "var(--prov-0)" }}
|
||||
/>
|
||||
{f.status}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="mt-6 font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">
|
||||
{t({ en: "Uploads are deduplicated against your file · no cost until you order", sv: "Uppladdat dedupliceras mot din fil · ingen kostnad förrän du beställer" })}{files && files.length ? ` · ${formatSEK(0)} ${t({ en: "so far", sv: "hittills" })}` : ""}
|
||||
</p>
|
||||
</PortalShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useT } from '@/components/locale-provider';
|
||||
import { PortalShell } from '@/components/portal-shell';
|
||||
import { formatSEK } from '@/lib/data';
|
||||
|
||||
type Pack = { id: string; credits: number; amount_minor: number };
|
||||
|
||||
export default function CreditsPage() {
|
||||
const t = useT();
|
||||
const [balance, setBalance] = useState<{ available: number; reserved: number } | null>(null);
|
||||
const [balanceNote, setBalanceNote] = useState<string | null>(null);
|
||||
const [packs, setPacks] = useState<Pack[]>([]);
|
||||
const [purchasesEnabled, setPurchasesEnabled] = useState(true);
|
||||
const [currency, setCurrency] = useState('SEK');
|
||||
const [packsNote, setPacksNote] = useState<string | null>(null);
|
||||
const [buying, setBuying] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState<string | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const r = await fetch('/api/0pt/credits/balance', { cache: 'no-store' });
|
||||
const body = (await r.json()) as { available?: number; reserved?: number; message?: string };
|
||||
if (r.ok) setBalance({ available: body.available ?? 0, reserved: body.reserved ?? 0 });
|
||||
else
|
||||
setBalanceNote(
|
||||
body.message ?? t({ en: 'Credits are not available', sv: 'Krediter är inte tillgängliga' }),
|
||||
);
|
||||
} catch {
|
||||
setBalanceNote(t({ en: 'Could not read the balance', sv: 'Kunde inte läsa saldot' }));
|
||||
}
|
||||
try {
|
||||
const r = await fetch('/api/0pt/credits/packs', { cache: 'no-store' });
|
||||
const body = (await r.json()) as {
|
||||
packs?: Pack[];
|
||||
currency?: string;
|
||||
purchases_enabled?: boolean;
|
||||
message?: string;
|
||||
};
|
||||
if (r.ok && body.packs) {
|
||||
setPacks(body.packs);
|
||||
setCurrency(body.currency ?? 'SEK');
|
||||
setPurchasesEnabled(body.purchases_enabled !== false);
|
||||
} else {
|
||||
setPacksNote(
|
||||
body.message ??
|
||||
t({ en: 'Credit packs are not configured', sv: 'Kreditpaket är inte konfigurerade' }),
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
setPacksNote(t({ en: 'Could not read credit packs', sv: 'Kunde inte läsa kreditpaket' }));
|
||||
}
|
||||
}, [t]);
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const state = params.get('status');
|
||||
if (state === 'success') {
|
||||
setStatus(
|
||||
t({
|
||||
en: 'Payment received. Credits are added when Stripe confirms the payment.',
|
||||
sv: 'Betalning mottagen. Krediter läggs till när Stripe bekräftar betalningen.',
|
||||
}),
|
||||
);
|
||||
} else if (state === 'cancelled') {
|
||||
setStatus(t({ en: 'Checkout cancelled.', sv: 'Betalningen avbröts.' }));
|
||||
}
|
||||
}, [load, t]);
|
||||
|
||||
const buy = useCallback(
|
||||
async (packId: string) => {
|
||||
setBuying(packId);
|
||||
setStatus(null);
|
||||
try {
|
||||
const response = await fetch('/api/0pt/credits/checkout', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ pack_id: packId }),
|
||||
});
|
||||
const body = (await response.json().catch(() => ({}))) as { checkout_url?: string; message?: string };
|
||||
if (response.ok && body.checkout_url) {
|
||||
window.location.href = body.checkout_url;
|
||||
return;
|
||||
}
|
||||
setStatus(
|
||||
body.message ?? t({ en: 'Checkout is not available', sv: 'Betalning är inte tillgänglig' }),
|
||||
);
|
||||
} catch {
|
||||
setStatus(t({ en: 'Checkout is not available', sv: 'Betalning är inte tillgänglig' }));
|
||||
} finally {
|
||||
setBuying(null);
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
const card = 'border border-border bg-background p-6';
|
||||
|
||||
return (
|
||||
<PortalShell variant="customer" title={t({ en: 'Credits', sv: 'Krediter' })}>
|
||||
<div className="mx-auto w-full max-w-3xl space-y-6">
|
||||
<section className={card}>
|
||||
<span className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
|
||||
{t({ en: 'balance', sv: 'saldo' })}
|
||||
</span>
|
||||
{balance ? (
|
||||
<p className="mt-3 font-mono text-3xl tracking-[-0.02em]">
|
||||
{balance.available}
|
||||
<span className="ml-2 text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
|
||||
{t({ en: 'available', sv: 'tillgängliga' })} · {balance.reserved}{' '}
|
||||
{t({ en: 'reserved', sv: 'reserverade' })}
|
||||
</span>
|
||||
</p>
|
||||
) : (
|
||||
<p className="mt-3 text-[14px] text-muted-foreground">{balanceNote ?? '…'}</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className={card}>
|
||||
<h2 className="text-lg font-semibold tracking-[-0.02em]">
|
||||
{t({ en: 'Buy credits', sv: 'Köp krediter' })}
|
||||
</h2>
|
||||
{packs.length === 0 ? (
|
||||
<p className="mt-3 text-[14px] text-muted-foreground">{packsNote ?? '…'}</p>
|
||||
) : (
|
||||
<ul className="mt-4 divide-y divide-border border-y border-border">
|
||||
{packs.map((pack) => (
|
||||
<li key={pack.id} className="flex items-center justify-between gap-4 py-3">
|
||||
<div>
|
||||
<p className="font-mono text-[13px]">{pack.credits} credits</p>
|
||||
<p className="font-mono text-[11px] text-muted-foreground">
|
||||
{formatSEK(pack.amount_minor / 100)}
|
||||
</p>
|
||||
</div>
|
||||
{purchasesEnabled ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => buy(pack.id)}
|
||||
disabled={buying !== null}
|
||||
className="border border-foreground px-4 py-2 font-mono text-[11px] uppercase tracking-[0.18em] disabled:opacity-40"
|
||||
>
|
||||
{buying === pack.id
|
||||
? t({ en: 'opening…', sv: 'öppnar…' })
|
||||
: t({ en: 'buy', sv: 'köp' })}
|
||||
</button>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{!purchasesEnabled ? (
|
||||
<p className="mt-4 text-[14px] text-muted-foreground">
|
||||
{t({
|
||||
en: 'Billing is not active yet (pilot). No payment can be taken.',
|
||||
sv: 'Betalning är inte aktiverad än (pilot). Ingen betalning kan tas.',
|
||||
})}
|
||||
</p>
|
||||
) : null}
|
||||
{status ? <p className="mt-4 text-[14px] text-muted-foreground">{status}</p> : null}
|
||||
<p className="mt-4 font-mono text-[10px] uppercase tracking-[0.16em] text-muted-foreground">
|
||||
{currency}
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</PortalShell>
|
||||
);
|
||||
}
|
||||
+2
-3
@@ -36,8 +36,7 @@ const STATUS_LABEL: Record<string, { en: string; sv: string }> = {
|
||||
const NAV: { label: { en: string; sv: string }; href: string }[] = [
|
||||
{ label: { en: "Overview", sv: "Översikt" }, href: "/portal" },
|
||||
{ label: { en: "Subscriptions", sv: "Prenumerationer" }, href: "/portal/subscriptions" },
|
||||
{ label: { en: "Documents", sv: "Dokument" }, href: "/portal/dokument" },
|
||||
{ label: { en: "Credits", sv: "Krediter" }, href: "/portal/krediter" },
|
||||
{ label: { en: "Files", sv: "Filer" }, href: "/portal/files" },
|
||||
{ label: { en: "Integrations", sv: "Integrationer" }, href: "/portal/integrationer" },
|
||||
{ label: { en: "Settings", sv: "Inställningar" }, href: "/portal/settings" },
|
||||
{ label: { en: "Admin", sv: "Admin" }, href: "/admin" },
|
||||
@@ -287,7 +286,7 @@ function CopyId({ id }: { id: string }) {
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
});
|
||||
}}
|
||||
className="text-muted-foreground transition-colors hover:text-foreground"
|
||||
className="text-foreground/20 transition-colors hover:text-foreground/60"
|
||||
>
|
||||
{copied ? "✓" : "⧉"}
|
||||
</button>
|
||||
|
||||
@@ -40,7 +40,7 @@ export default function ServicesPage() {
|
||||
<section key={flow} className="mt-16">
|
||||
<div className="flex items-baseline justify-between border-b border-border pb-4">
|
||||
<h2 className="font-mono text-[11px] uppercase tracking-[0.16em] text-muted-foreground">{t(FLOW_LABEL[flow])}</h2>
|
||||
<span className="font-mono text-[11px] tabular-nums text-muted-foreground">{String(items.length).padStart(2, "0")}</span>
|
||||
<span className="font-mono text-[11px] tabular-nums text-muted-foreground/60">{String(items.length).padStart(2, "0")}</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-px border border-border bg-border md:grid-cols-2 lg:grid-cols-3">
|
||||
{items.map((s, i) => {
|
||||
@@ -50,7 +50,7 @@ export default function ServicesPage() {
|
||||
<h3 className="text-lg font-semibold tracking-[-0.01em]">{t(s.name)}</h3>
|
||||
<p className="mt-1 font-mono text-[11px] uppercase tracking-[0.06em] text-muted-foreground">{t(s.tagline)}</p>
|
||||
<p className="mt-4 flex-1 text-sm text-muted-foreground">{t(s.covers)}</p>
|
||||
<p className="mt-4 font-mono text-[10.5px] uppercase tracking-[0.08em] text-muted-foreground">→ {t(s.deliverable)}</p>
|
||||
<p className="mt-4 font-mono text-[10.5px] uppercase tracking-[0.08em] text-muted-foreground/70">→ {t(s.deliverable)}</p>
|
||||
<Link href={cta.href} className="mt-5 inline-flex items-center gap-2 font-mono text-[11px] uppercase tracking-[0.1em] underline-offset-4 hover:underline">
|
||||
{t(cta.label)}
|
||||
<span aria-hidden className="transition-transform duration-300 group-hover:translate-x-1">→</span>
|
||||
|
||||
@@ -123,7 +123,7 @@ export function Header() {
|
||||
className="flex items-baseline justify-between border-b border-border py-4 font-mono text-[12px] uppercase tracking-[0.12em] text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<span>{t(n.label)}</span>
|
||||
<span className="text-[10px] tabular-nums text-muted-foreground">{String(i + 1).padStart(2, "0")}</span>
|
||||
<span className="text-[10px] tabular-nums text-muted-foreground/50">{String(i + 1).padStart(2, "0")}</span>
|
||||
</Link>
|
||||
))}
|
||||
<div className="flex items-center justify-between py-4">
|
||||
|
||||
+37
-52
@@ -1,27 +1,26 @@
|
||||
'use client';
|
||||
"use client";
|
||||
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useT } from '@/components/locale-provider';
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useT } from "@/components/locale-provider";
|
||||
|
||||
export type NavItem = { label: { en: string; sv: string }; href: string };
|
||||
|
||||
const CUSTOMER_NAV: NavItem[] = [
|
||||
{ label: { en: 'Overview', sv: 'Översikt' }, href: '/portal' },
|
||||
{ label: { en: 'Subscriptions', sv: 'Prenumerationer' }, href: '/portal/subscriptions' },
|
||||
{ label: { en: 'Documents', sv: 'Dokument' }, href: '/portal/dokument' },
|
||||
{ label: { en: 'Credits', sv: 'Krediter' }, href: '/portal/krediter' },
|
||||
{ label: { en: 'Integrations', sv: 'Integrationer' }, href: '/portal/integrationer' },
|
||||
{ label: { en: 'Settings', sv: 'Inställningar' }, href: '/portal/settings' },
|
||||
{ label: { en: "Overview", sv: "Översikt" }, href: "/portal" },
|
||||
{ label: { en: "Subscriptions", sv: "Prenumerationer" }, href: "/portal/subscriptions" },
|
||||
{ label: { en: "Files", sv: "Filer" }, href: "/portal/files" },
|
||||
{ label: { en: "Integrations", sv: "Integrationer" }, href: "/portal/integrationer" },
|
||||
{ label: { en: "Settings", sv: "Inställningar" }, href: "/portal/settings" },
|
||||
];
|
||||
|
||||
const ADMIN_NAV: NavItem[] = [
|
||||
{ label: { en: 'Overview', sv: 'Översikt' }, href: '/admin' },
|
||||
{ label: { en: 'Sources', sv: 'Källor' }, href: '/admin/sources' },
|
||||
{ label: { en: 'Jobs', sv: 'Jobb' }, href: '/admin/jobs' },
|
||||
{ label: { en: 'Tools', sv: 'Verktyg' }, href: '/admin/verktyg' },
|
||||
{ label: { en: 'Customers', sv: 'Kunder' }, href: '/admin/customers' },
|
||||
{ label: { en: "Overview", sv: "Översikt" }, href: "/admin" },
|
||||
{ label: { en: "Sources", sv: "Källor" }, href: "/admin/sources" },
|
||||
{ label: { en: "Jobs", sv: "Jobb" }, href: "/admin/jobs" },
|
||||
{ label: { en: "Tools", sv: "Verktyg" }, href: "/admin/verktyg" },
|
||||
{ label: { en: "Customers", sv: "Kunder" }, href: "/admin/customers" },
|
||||
];
|
||||
|
||||
export function PortalShell({
|
||||
@@ -29,24 +28,24 @@ export function PortalShell({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
variant: 'customer' | 'admin';
|
||||
variant: "customer" | "admin";
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const t = useT();
|
||||
const pathname = usePathname();
|
||||
const nav = variant === 'admin' ? ADMIN_NAV : CUSTOMER_NAV;
|
||||
const nav = variant === "admin" ? ADMIN_NAV : CUSTOMER_NAV;
|
||||
const [email, setEmail] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/auth/me')
|
||||
fetch("/api/auth/me")
|
||||
.then((r) => r.json())
|
||||
.then((d) => setEmail(d?.user?.email ?? null))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
async function logout() {
|
||||
await fetch('/api/auth/logout', { method: 'POST' }).catch(() => {});
|
||||
await fetch("/api/auth/logout", { method: "POST" }).catch(() => {});
|
||||
setEmail(null);
|
||||
}
|
||||
|
||||
@@ -56,29 +55,23 @@ export function PortalShell({
|
||||
<div className="sticky top-0 z-40 flex h-16 items-center justify-between border-b border-border bg-background px-6">
|
||||
<Link href="/" className="flex items-center gap-2">
|
||||
<span className="text-lg font-semibold tracking-[-0.04em]">0pt</span>
|
||||
<span className="inline-block h-1 w-1" style={{ backgroundColor: 'var(--accent-red)' }} />
|
||||
<span className="inline-block h-1 w-1" style={{ backgroundColor: "var(--accent-red)" }} />
|
||||
<span className="font-mono text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
|
||||
{variant === 'admin' ? 'admin' : 'portal'}
|
||||
{variant === "admin" ? "admin" : "portal"}
|
||||
</span>
|
||||
</Link>
|
||||
<div className="flex items-center gap-4">
|
||||
{email ? (
|
||||
<>
|
||||
<span className="font-mono text-[11px] text-muted-foreground">{email}</span>
|
||||
<button
|
||||
onClick={logout}
|
||||
className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t({ en: 'Log out', sv: 'Logga ut' })}
|
||||
<button onClick={logout} className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground">
|
||||
{t({ en: "Log out", sv: "Logga ut" })}
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<a
|
||||
href="/api/auth/login?next=/portal/dokument"
|
||||
className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t({ en: 'Log in', sv: 'Logga in' })}
|
||||
</a>
|
||||
<Link href="/portal/settings" className="font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground">
|
||||
{t({ en: "Log in", sv: "Logga in" })}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -93,30 +86,24 @@ export function PortalShell({
|
||||
<Link
|
||||
key={n.href}
|
||||
href={n.href}
|
||||
aria-current={active ? 'page' : undefined}
|
||||
aria-current={active ? "page" : undefined}
|
||||
className="border-l-2 px-4 py-2.5 font-mono text-[11px] uppercase tracking-[0.1em] transition-colors"
|
||||
style={{
|
||||
borderColor: active ? 'var(--accent-red)' : 'transparent',
|
||||
color: active ? 'var(--foreground)' : 'var(--muted-foreground)',
|
||||
borderColor: active ? "var(--accent-red)" : "transparent",
|
||||
color: active ? "var(--foreground)" : "var(--muted-foreground)",
|
||||
}}
|
||||
>
|
||||
{t(n.label)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
{variant === 'customer' ? (
|
||||
<Link
|
||||
href="/bestall"
|
||||
className="mt-2 bg-foreground px-4 py-2.5 text-center font-mono text-[11px] uppercase tracking-[0.1em] text-background hover:bg-[var(--accent-red)]"
|
||||
>
|
||||
{t({ en: 'New order', sv: 'Ny beställning' })}
|
||||
{variant === "customer" ? (
|
||||
<Link href="/bestall" className="mt-2 bg-foreground px-4 py-2.5 text-center font-mono text-[11px] uppercase tracking-[0.1em] text-background hover:bg-[var(--accent-red)]">
|
||||
{t({ en: "New order", sv: "Ny beställning" })}
|
||||
</Link>
|
||||
) : (
|
||||
<Link
|
||||
href="/portal"
|
||||
className="mt-2 border border-border px-4 py-2.5 text-center font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
{t({ en: '← Customer view', sv: '← Kundvy' })}
|
||||
<Link href="/portal" className="mt-2 border border-border px-4 py-2.5 text-center font-mono text-[11px] uppercase tracking-[0.1em] text-muted-foreground hover:text-foreground">
|
||||
{t({ en: "← Customer view", sv: "← Kundvy" })}
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
@@ -134,11 +121,9 @@ export function PortalShell({
|
||||
|
||||
export function StatusPill({ status }: { status: string }) {
|
||||
const color =
|
||||
status === 'delivered' || status === 'accepted'
|
||||
? 'var(--prov-3)'
|
||||
: status === 'in_production' || status === 'review'
|
||||
? 'var(--accent-red)'
|
||||
: 'var(--muted-foreground)';
|
||||
status === "delivered" || status === "accepted" ? "var(--prov-3)"
|
||||
: status === "in_production" || status === "review" ? "var(--accent-red)"
|
||||
: "var(--muted-foreground)";
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5 font-mono text-[10.5px] uppercase tracking-[0.08em]">
|
||||
<span className="inline-block h-2 w-2" style={{ backgroundColor: color }} />
|
||||
|
||||
@@ -44,7 +44,7 @@ export function CollectionSection() {
|
||||
>
|
||||
<div className="flex items-baseline justify-between">
|
||||
<p className="font-mono text-sm font-semibold tracking-tight">{m.code}</p>
|
||||
<span className="font-mono text-[9px] text-muted-foreground">{String(i + 1).padStart(2, "0")}</span>
|
||||
<span className="font-mono text-[9px] text-muted-foreground/60">{String(i + 1).padStart(2, "0")}</span>
|
||||
</div>
|
||||
<p className="mt-1 font-mono text-[10px] uppercase tracking-[0.08em] text-muted-foreground">
|
||||
{m.live ? `${m.coverage}%` : t({ en: "coming", sv: "kommande" })}
|
||||
|
||||
@@ -91,7 +91,7 @@ export function FeaturedProductsSection() {
|
||||
<span className="absolute left-0 top-0 h-px w-0 transition-all duration-300 group-hover:w-full" style={{ backgroundColor: "var(--accent-red)" }} />
|
||||
<div className="flex items-baseline justify-between">
|
||||
<p className="font-mono text-[10px] uppercase tracking-[0.14em] text-muted-foreground">{d.markets}</p>
|
||||
<span className="font-mono text-[10px] tabular-nums text-muted-foreground">{String(i + 1).padStart(2, "0")}</span>
|
||||
<span className="font-mono text-[10px] tabular-nums text-foreground/20">{String(i + 1).padStart(2, "0")}</span>
|
||||
</div>
|
||||
<h3 className="mt-5 text-xl font-semibold tracking-[-0.01em] transition-transform duration-300 group-hover:translate-x-1">{t(d.title)}</h3>
|
||||
<p className="mt-2 text-sm text-muted-foreground">{t(d.desc)}</p>
|
||||
|
||||
@@ -33,7 +33,7 @@ export function PhilosophySection() {
|
||||
className={`reveal delay-${i + 1} group relative grid grid-cols-[3.5rem_1fr] items-baseline gap-8 border-b border-border py-8 transition-[padding] duration-300 ease-out hover:pl-2`}
|
||||
>
|
||||
<span className="absolute -left-2 top-0 h-px w-0 bg-foreground transition-all duration-500 ease-out group-hover:w-full group-hover:opacity-100" aria-hidden />
|
||||
<span className="font-mono text-[clamp(1.5rem,2vw,2.25rem)] font-medium leading-none tracking-[-0.02em] text-muted-foreground transition-colors duration-300 group-hover:text-foreground">
|
||||
<span className="font-mono text-[clamp(1.5rem,2vw,2.25rem)] font-medium leading-none tracking-[-0.02em] text-muted-foreground/40 transition-colors duration-300 group-hover:text-foreground">
|
||||
{n}
|
||||
</span>
|
||||
<div>
|
||||
|
||||
@@ -64,7 +64,7 @@ export function PricingSection() {
|
||||
{MODELS.map((m, i) => (
|
||||
<div key={m.index} className={`reveal delay-${i + 1} group relative flex flex-col bg-background p-8`}>
|
||||
<div className="flex items-start justify-between">
|
||||
<span className="font-mono text-[11px] uppercase tracking-[0.18em] text-muted-foreground">{m.index}</span>
|
||||
<span className="font-mono text-[11px] uppercase tracking-[0.18em] text-muted-foreground/60">{m.index}</span>
|
||||
{m.featured ? <span className="mt-1 inline-block h-2 w-2" style={{ backgroundColor: "var(--accent-red)" }} /> : null}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ export function TestimonialsSection() {
|
||||
key={l.sv}
|
||||
className={`reveal delay-${i + 2} group relative border-b border-border py-12 sm:border-b-0 sm:border-l sm:py-0 sm:pl-8 sm:pr-4 ${i === 0 ? "sm:border-l-0 sm:pl-0" : ""}`}
|
||||
>
|
||||
<p className="font-mono text-[11px] tabular-nums text-muted-foreground">0{i + 1}</p>
|
||||
<p className="font-mono text-[11px] tabular-nums text-muted-foreground/60">0{i + 1}</p>
|
||||
<p
|
||||
className="mt-3 text-[clamp(3.2rem,8vw,6rem)] font-semibold leading-[0.9] tracking-[-0.04em] transition-transform duration-300 group-hover:-translate-y-0.5"
|
||||
style={{ color: red ? "var(--accent-red)" : "var(--foreground)" }}
|
||||
|
||||
@@ -46,7 +46,7 @@ export function LoadingSkeleton({ rows = 5 }: { rows?: number }) {
|
||||
))}
|
||||
<span className="sr-only">{t({ en: "Loading content", sv: "Laddar innehåll" })}</span>
|
||||
|
||||
<style>{`
|
||||
<style jsx>{`
|
||||
.opt-shimmer {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import * as RechartsPrimitive from 'recharts'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||
const THEMES = { light: '', dark: '.dark' } as const
|
||||
|
||||
export type ChartConfig = {
|
||||
[k in string]: {
|
||||
label?: React.ReactNode
|
||||
icon?: React.ComponentType
|
||||
} & (
|
||||
| { color?: string; theme?: never }
|
||||
| { color?: never; theme: Record<keyof typeof THEMES, string> }
|
||||
)
|
||||
}
|
||||
|
||||
type ChartContextProps = {
|
||||
config: ChartConfig
|
||||
}
|
||||
|
||||
const ChartContext = React.createContext<ChartContextProps | null>(null)
|
||||
|
||||
function useChart() {
|
||||
const context = React.useContext(ChartContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error('useChart must be used within a <ChartContainer />')
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function ChartContainer({
|
||||
id,
|
||||
className,
|
||||
children,
|
||||
config,
|
||||
...props
|
||||
}: React.ComponentProps<'div'> & {
|
||||
config: ChartConfig
|
||||
children: React.ComponentProps<
|
||||
typeof RechartsPrimitive.ResponsiveContainer
|
||||
>['children']
|
||||
}) {
|
||||
const uniqueId = React.useId()
|
||||
const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`
|
||||
|
||||
return (
|
||||
<ChartContext.Provider value={{ config }}>
|
||||
<div
|
||||
data-slot="chart"
|
||||
data-chart={chartId}
|
||||
className={cn(
|
||||
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChartStyle id={chartId} config={config} />
|
||||
<RechartsPrimitive.ResponsiveContainer>
|
||||
{children}
|
||||
</RechartsPrimitive.ResponsiveContainer>
|
||||
</div>
|
||||
</ChartContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
|
||||
const colorConfig = Object.entries(config).filter(
|
||||
([, config]) => config.theme || config.color,
|
||||
)
|
||||
|
||||
if (!colorConfig.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<style
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: Object.entries(THEMES)
|
||||
.map(
|
||||
([theme, prefix]) => `
|
||||
${prefix} [data-chart=${id}] {
|
||||
${colorConfig
|
||||
.map(([key, itemConfig]) => {
|
||||
const color =
|
||||
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
|
||||
itemConfig.color
|
||||
return color ? ` --color-${key}: ${color};` : null
|
||||
})
|
||||
.join('\n')}
|
||||
}
|
||||
`,
|
||||
)
|
||||
.join('\n'),
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartTooltip = RechartsPrimitive.Tooltip
|
||||
|
||||
function ChartTooltipContent({
|
||||
active,
|
||||
payload,
|
||||
className,
|
||||
indicator = 'dot',
|
||||
hideLabel = false,
|
||||
hideIndicator = false,
|
||||
label,
|
||||
labelFormatter,
|
||||
labelClassName,
|
||||
formatter,
|
||||
color,
|
||||
nameKey,
|
||||
labelKey,
|
||||
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
|
||||
React.ComponentProps<'div'> & {
|
||||
hideLabel?: boolean
|
||||
hideIndicator?: boolean
|
||||
indicator?: 'line' | 'dot' | 'dashed'
|
||||
nameKey?: string
|
||||
labelKey?: string
|
||||
}) {
|
||||
const { config } = useChart()
|
||||
|
||||
const tooltipLabel = React.useMemo(() => {
|
||||
if (hideLabel || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [item] = payload
|
||||
const key = `${labelKey || item?.dataKey || item?.name || 'value'}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const value =
|
||||
!labelKey && typeof label === 'string'
|
||||
? config[label as keyof typeof config]?.label || label
|
||||
: itemConfig?.label
|
||||
|
||||
if (labelFormatter) {
|
||||
return (
|
||||
<div className={cn('font-medium', labelClassName)}>
|
||||
{labelFormatter(value, payload)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
return <div className={cn('font-medium', labelClassName)}>{value}</div>
|
||||
}, [
|
||||
label,
|
||||
labelFormatter,
|
||||
payload,
|
||||
hideLabel,
|
||||
labelClassName,
|
||||
config,
|
||||
labelKey,
|
||||
])
|
||||
|
||||
if (!active || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const nestLabel = payload.length === 1 && indicator !== 'dot'
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{!nestLabel ? tooltipLabel : null}
|
||||
<div className="grid gap-1.5">
|
||||
{payload.map((item, index) => {
|
||||
const key = `${nameKey || item.name || item.dataKey || 'value'}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
const indicatorColor = color || item.payload.fill || item.color
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.dataKey}
|
||||
className={cn(
|
||||
'[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5',
|
||||
indicator === 'dot' && 'items-center',
|
||||
)}
|
||||
>
|
||||
{formatter && item?.value !== undefined && item.name ? (
|
||||
formatter(item.value, item.name, item, index, item.payload)
|
||||
) : (
|
||||
<>
|
||||
{itemConfig?.icon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
!hideIndicator && (
|
||||
<div
|
||||
className={cn(
|
||||
'shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)',
|
||||
{
|
||||
'h-2.5 w-2.5': indicator === 'dot',
|
||||
'w-1': indicator === 'line',
|
||||
'w-0 border-[1.5px] border-dashed bg-transparent':
|
||||
indicator === 'dashed',
|
||||
'my-0.5': nestLabel && indicator === 'dashed',
|
||||
},
|
||||
)}
|
||||
style={
|
||||
{
|
||||
'--color-bg': indicatorColor,
|
||||
'--color-border': indicatorColor,
|
||||
} as React.CSSProperties
|
||||
}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-1 justify-between leading-none',
|
||||
nestLabel ? 'items-end' : 'items-center',
|
||||
)}
|
||||
>
|
||||
<div className="grid gap-1.5">
|
||||
{nestLabel ? tooltipLabel : null}
|
||||
<span className="text-muted-foreground">
|
||||
{itemConfig?.label || item.name}
|
||||
</span>
|
||||
</div>
|
||||
{item.value && (
|
||||
<span className="text-foreground font-mono font-medium tabular-nums">
|
||||
{item.value.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ChartLegend = RechartsPrimitive.Legend
|
||||
|
||||
function ChartLegendContent({
|
||||
className,
|
||||
hideIcon = false,
|
||||
payload,
|
||||
verticalAlign = 'bottom',
|
||||
nameKey,
|
||||
}: React.ComponentProps<'div'> &
|
||||
Pick<RechartsPrimitive.LegendProps, 'payload' | 'verticalAlign'> & {
|
||||
hideIcon?: boolean
|
||||
nameKey?: string
|
||||
}) {
|
||||
const { config } = useChart()
|
||||
|
||||
if (!payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex items-center justify-center gap-4',
|
||||
verticalAlign === 'top' ? 'pb-3' : 'pt-3',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{payload.map((item) => {
|
||||
const key = `${nameKey || item.dataKey || 'value'}`
|
||||
const itemConfig = getPayloadConfigFromPayload(config, item, key)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.value}
|
||||
className={
|
||||
'[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3'
|
||||
}
|
||||
>
|
||||
{itemConfig?.icon && !hideIcon ? (
|
||||
<itemConfig.icon />
|
||||
) : (
|
||||
<div
|
||||
className="h-2 w-2 shrink-0 rounded-[2px]"
|
||||
style={{
|
||||
backgroundColor: item.color,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{itemConfig?.label}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Helper to extract item config from a payload.
|
||||
function getPayloadConfigFromPayload(
|
||||
config: ChartConfig,
|
||||
payload: unknown,
|
||||
key: string,
|
||||
) {
|
||||
if (typeof payload !== 'object' || payload === null) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const payloadPayload =
|
||||
'payload' in payload &&
|
||||
typeof payload.payload === 'object' &&
|
||||
payload.payload !== null
|
||||
? payload.payload
|
||||
: undefined
|
||||
|
||||
let configLabelKey: string = key
|
||||
|
||||
if (
|
||||
key in payload &&
|
||||
typeof payload[key as keyof typeof payload] === 'string'
|
||||
) {
|
||||
configLabelKey = payload[key as keyof typeof payload] as string
|
||||
} else if (
|
||||
payloadPayload &&
|
||||
key in payloadPayload &&
|
||||
typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
|
||||
) {
|
||||
configLabelKey = payloadPayload[
|
||||
key as keyof typeof payloadPayload
|
||||
] as string
|
||||
}
|
||||
|
||||
return configLabelKey in config
|
||||
? config[configLabelKey]
|
||||
: config[key as keyof typeof config]
|
||||
}
|
||||
|
||||
export {
|
||||
ChartContainer,
|
||||
ChartTooltip,
|
||||
ChartTooltipContent,
|
||||
ChartLegend,
|
||||
ChartLegendContent,
|
||||
ChartStyle,
|
||||
}
|
||||
@@ -77,7 +77,7 @@ const ToastClose = React.forwardRef<
|
||||
<ToastPrimitives.Close
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'absolute right-2 top-2 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
|
||||
'absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600',
|
||||
className,
|
||||
)}
|
||||
toast-close=""
|
||||
|
||||
@@ -367,60 +367,6 @@ paths:
|
||||
$ref: "#/components/schemas/ProvenanceRecord"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
/v1/0pt/parsing/route:
|
||||
post:
|
||||
operationId: 0pt.route_parsing
|
||||
summary: >
|
||||
(TARGET) Parser-routing/selektiv OCR-beslut (BTI-DOC-02/03/04/05).
|
||||
Kontrakt-first — real kod i 0pt-motor/motor/parsing/routing.py
|
||||
(route_parser m.fl.), INTEGRATION_TESTED men ej driftsatt bakom
|
||||
denna route.
|
||||
x-siax-status: target
|
||||
security: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RouteParsingRequest"
|
||||
responses:
|
||||
"200":
|
||||
description: Routingbeslut (parser/OCR-gren) + ev. nyckeltalskonflikter mellan parsers
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RouteParsingResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
/v1/0pt/normalize:
|
||||
post:
|
||||
operationId: 0pt.normalize_value
|
||||
summary: >
|
||||
(TARGET) Lokal-medveten normalisering — belopp/skala/datum (BTI-NLP-03)
|
||||
och identifierare/checksummor (BTI-NLP-02). Kontrakt-first — real kod
|
||||
i 0pt-motor/motor/normalization/{amounts,identifiers}.py,
|
||||
INTEGRATION_TESTED men ej driftsatt bakom denna route.
|
||||
x-siax-status: target
|
||||
security: []
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/NormalizeValueRequest"
|
||||
responses:
|
||||
"200":
|
||||
description: Normaliserat värde — format_valid/review, aldrig en påhittad korrigering
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/NormalizeValueResponse"
|
||||
"400":
|
||||
$ref: "#/components/responses/BadRequest"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Internal service-to-service (Python-engine bridge) — P-002 internal OpenAPI.
|
||||
@@ -865,91 +811,3 @@ components:
|
||||
type: object
|
||||
additionalProperties:
|
||||
$ref: "#/components/schemas/FieldProvenance"
|
||||
RouteParsingRequest:
|
||||
type: object
|
||||
required: [digital_text_page]
|
||||
properties:
|
||||
digital_text_page:
|
||||
type: boolean
|
||||
description: True om sidan har ett digitalt textlager (ej scannad).
|
||||
ocr_available:
|
||||
type: boolean
|
||||
default: false
|
||||
parser_result:
|
||||
type: object
|
||||
description: Föregående parser-försök, om något (tom text = kandidat för OCR-gren).
|
||||
properties:
|
||||
parser:
|
||||
type: string
|
||||
text:
|
||||
type: string
|
||||
key_figures:
|
||||
type: object
|
||||
additionalProperties:
|
||||
type: number
|
||||
compare_with:
|
||||
type: object
|
||||
description: (Valfritt) ett andra parser-resultat att stämma av mot — avvikande nyckeltal blir en konflikt, aldrig en tyst ersättning.
|
||||
properties:
|
||||
parser:
|
||||
type: string
|
||||
text:
|
||||
type: string
|
||||
key_figures:
|
||||
type: object
|
||||
additionalProperties:
|
||||
type: number
|
||||
RouteParsingResponse:
|
||||
type: object
|
||||
required: [routing]
|
||||
properties:
|
||||
routing:
|
||||
type: string
|
||||
enum: [text_parser, ocr_branch, explicit_unavailable]
|
||||
conflicts:
|
||||
type: object
|
||||
description: Fält där de två parser-resultatens nyckeltal skiljer sig (present endast om compare_with skickades).
|
||||
additionalProperties: true
|
||||
NormalizeValueRequest:
|
||||
type: object
|
||||
required: [kind, value]
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum: [amount, percent, date, identifier]
|
||||
description: amount/percent/date = motor/normalization/amounts.py. identifier = motor/normalization/identifiers.py.
|
||||
value:
|
||||
type: string
|
||||
description: Rå textsträng att normalisera (belopp, procentsats, datum eller identifierare).
|
||||
locale:
|
||||
type: string
|
||||
description: (kind=amount, valfritt) comma_decimal|dot_decimal — auto-detekteras annars.
|
||||
unit:
|
||||
type: string
|
||||
description: (kind=amount|percent) t.ex. SEK/KSEK/MSEK/GSEK eller "%"/"pp".
|
||||
identifier_kind:
|
||||
type: string
|
||||
enum: [orgnr, cvr, vat, ocr]
|
||||
description: (kind=identifier, krävs) vilken identifierartyp som ska valideras.
|
||||
country:
|
||||
type: string
|
||||
description: (kind=identifier, krävs) ISO-3166 alpha-2, t.ex. SE/NO/DK.
|
||||
description: >
|
||||
Ett fält, en normalisering. amount/percent/date har alltid en explicit
|
||||
precision/skala (aldrig en påhittad dag eller sammanblandad enhet).
|
||||
identifier ger format_valid eller review — aldrig en tyst korrigerad
|
||||
checksumma; existens i register verifieras inte här.
|
||||
NormalizeValueResponse:
|
||||
type: object
|
||||
required: [kind, status]
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum: [amount, percent, date, identifier]
|
||||
status:
|
||||
type: string
|
||||
enum: [ok, format_valid, format_invalid, review, unparseable]
|
||||
result:
|
||||
type: object
|
||||
description: Normaliserat resultat, formen beror på kind (se motor/normalization/{amounts,identifiers}.py).
|
||||
additionalProperties: true
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
# P070 — VehIQ OLTP -> 0pt watermark extractor
|
||||
|
||||
Status: built, tested, verified read-only against production. **Not scheduled/activated in production.** Read "What activating this requires" before turning the workflow on.
|
||||
|
||||
## What this is
|
||||
|
||||
A controlled, incremental extractor implementing exactly the pattern Simon specified (`admin/vehiq` 2026-09-25 pass, "Locked architecture decisions from Simon" / `docs/adr/0035-bi-analytics-architecture-product-firewall.md`):
|
||||
|
||||
```
|
||||
OLTP operational tables -> read-only analytical extraction -> watermark ->
|
||||
0pt ingestion -> ClickHouse (opt_dataset_projection)
|
||||
```
|
||||
|
||||
Source: `app.dealer_stock_entry` and `app.deal` on production Postgres (`vehiq-db`, server10) — read-only `SELECT`, never a schema/config change, never touching `wal_level` or replication, never a permanent replica. Sink: `SiaxAnalyticsEngine.ingestProjection` (BI-P009, `opt_dataset_projection` in ClickHouse). Vehicle dimension: a narrow, keyed lookup against `vehiq.vehicle` (98M rows / 85GB) scoped to exactly the `vehicle_id`s referenced by the `dealer_stock_entry` batch just read — never `SELECT * FROM vehicle`, never a full scan.
|
||||
|
||||
## Why this lives in `admin/0pt`, not `admin/vehiq`
|
||||
|
||||
The task that produced this work described building it as a new package inside `admin/vehiq` (e.g. `packages/opt-ingest`). Before writing any code, this repo's own `docs/adr/0035-bi-analytics-architecture-product-firewall.md` (decisions 1, 2, 10 — decided the same day, one-way-door, CI-enforced by `tools/validate_engine_firewall.py`) was read and is unambiguous:
|
||||
|
||||
> VehIQ's own codebase must **never** get its own ClickHouse or DuckDB credentials, and must never import a ClickHouse/DuckDB client directly. ... Product code must never hammer the live OLTP Postgres with analytical queries directly.
|
||||
|
||||
And `admin/vehiq`'s `docs/CURRENT_STATE.md` ("Connection details for a future API0 connector", same pass) says explicitly:
|
||||
|
||||
> VehIQ's own codebase must never see any of this. This is 0pt's data plane; only a future `admin/api0` connector should hold these details.
|
||||
|
||||
Building the extractor inside `admin/vehiq` would have failed `validate_engine_firewall.py` the moment it imported a ClickHouse client or held a `CLICKHOUSE_*` env var, and would have been the exact "temporary VehIQ-owned data-access surface" ADR-0035 names as the failure mode it exists to prevent. So this extractor was built here instead — `admin/0pt`, 0pt's own data plane, a sibling of `admin/api0` (the mechanics belong next to the P060-P068 ingestion plane and the BI-P009/P010 ClickHouse engine that already live in this repo). **`admin/vehiq` was not modified by this work.**
|
||||
|
||||
This is a deliberate deviation from the task's literal repo suggestion, made because the suggestion conflicted with Simon's own same-day, explicit, locked architecture decision discovered while reading the target repo — not a judgment call made against that decision.
|
||||
|
||||
## Real production schema does not match the task's assumed column names
|
||||
|
||||
The task (and `admin/vehiq`'s `docs/CURRENT_STATE.md`) assumed all three OLTP tables carry a generic `updated_at` ("the columns already exist"). Verified live against production (server10, `vehiq-db`, read-only `information_schema.columns`, 2026-09-25) — **this is not true**:
|
||||
|
||||
| table | live columns | usable watermark |
|
||||
|---|---|---|
|
||||
| `app.dealer_stock_entry` | `id, tenant_id, vehicle_id, lot_location, floorplan_status, listed_at, sold_at` | `listed_at` (NOT NULL, insert-time only) |
|
||||
| `app.deal` | `id, tenant_id, party_id, vehicle_id, sale_price_minor, currency, status, created_at` | `created_at` (NOT NULL DEFAULT now(), insert-time only) |
|
||||
| `app.listing` | `id, tenant_id, vehicle_id, asking_price_minor, currency, channels, status` | **none** |
|
||||
|
||||
**`app.listing` has no timestamp column of any kind today.** `admin/vehiq` migration `0084_listing_deal_lifecycle_timestamps.sql` (already written, adds `published_at`/`unpublished_at` to `listing` and `closed_at`/`listing_id` to `deal`) exists in the repo but is **not yet applied to production** (verified: those columns are absent live). Until it lands, there is no honest way to build a watermark connector for `app.listing` — one is not built here. **This extractor covers `dealer_stock_entry` and `deal` only, not `listing`.**
|
||||
|
||||
**Caveat on the two sources that ARE built:** `listed_at`/`created_at` are set once, at INSERT. Neither table has a column that advances when an *existing* row changes (`sold_at`/`floorplan_status` on `dealer_stock_entry`; `status` on `deal`). This extractor reliably sees every new row; it does **not** see an in-place UPDATE to a row it already read, because that row has already passed the watermark. Closing this gap needs either `listing_id`/`closed_at` (migration 0084, once applied) plus an equivalent for `dealer_stock_entry`, or a generic `updated_at` + trigger — a schema decision for Simon, not something this pass made unilaterally (per the hard "never a schema/config change" rule).
|
||||
|
||||
Also found and corrected while building: `vehiq.vehicle`'s primary key column is `vehicle_id`, not `id` (verified via schema introspection only — no vehicle data rows were read to establish this).
|
||||
|
||||
## Where the code lives
|
||||
|
||||
- `src/connectors/postgres-watermark-connector.ts` — the P061 `Connector` implementing `WHERE watermark_col > $1 OR (watermark_col = $1 AND key_col > $2) ORDER BY watermark_col, key_col LIMIT $3` (the `OR` tuple form, not a bare `>`, so a same-timestamp tie at a page boundary is not silently dropped — see the file's own header for the bug this avoids). Explicit column allow-list, never `SELECT *`. `validate()` structurally refuses any config pointed at `vehiq.vehicle`.
|
||||
- `src/connectors/postgres-keyed-lookup-connector.ts` — the narrow vehicle-dimension connector. Config carries an already-resolved, finite `keys` array; `connect()` refuses an empty list rather than defaulting to a full read; every query is `WHERE vehicle_id = ANY($1)` chunked to `keys_per_query` (default 500).
|
||||
- `src/connectors/postgres-query-impl.ts` — the real `postgres` (postgres.js) implementation of the connectors' injectable `QueryImpl`, used only by the orchestration script. Refuses to execute anything whose first keyword isn't `SELECT`, independent of the DB role's own privileges.
|
||||
- `src/ingestion/projection-sink.ts` — adapts the P062 runner's `IngestionSink` onto `SiaxAnalyticsEngine.ingestProjection` (writes `opt_dataset_projection`). No ClickHouse import — only the `SiaxAnalyticsEngine` port type.
|
||||
- `src/ingestion/vehiq-oltp-ingest-runner.ts` — the orchestration: `previewVehiqOltpSource` (one bounded read-only read, never commits, safe against production at any time) and `runVehiqOltpIngestion` (the real P062-runner path).
|
||||
- `scripts/vehiq-oltp-ingest/run.ts` — thin CLI (`pnpm run vehiq:oltp-ingest`), env-driven, defaults to `preview` mode.
|
||||
- Tests: `tests/connectors/postgres-watermark-connector.test.ts`, `tests/connectors/postgres-keyed-lookup-connector.test.ts`, `tests/ingestion/vehiq-oltp-ingest-runner.test.ts`.
|
||||
|
||||
## Checkpoint field mapping
|
||||
|
||||
Simon's own specified checkpoint columns — `source, table, last_updated_at, last_id, batch_count, checksum, ingested_at` — mapped onto the **existing** P062 `IngestionCheckpoint` (reused, not duplicated, per the "no double truths" rule):
|
||||
|
||||
| Simon's field | Canonical field |
|
||||
|---|---|
|
||||
| `source` | `IngestionCheckpoint.source_id` |
|
||||
| `table` | `IngestionCheckpoint.partition_key` |
|
||||
| `last_updated_at` | decoded from `IngestionCheckpoint.cursor` (JSON `WatermarkCursor`) |
|
||||
| `last_id` | decoded from `IngestionCheckpoint.cursor` |
|
||||
| `checksum` | decoded from `IngestionCheckpoint.cursor` — sha256 of the page just landed |
|
||||
| `batch_count` | `IngestionCheckpoint.records_committed` (cumulative); a per-run page count is also in each run's `PartitionRunReport` |
|
||||
| `ingested_at` | `IngestionCheckpoint.committed_at` |
|
||||
|
||||
Durable storage: `createIngestionRepository(DATABASE_URL)` — Postgres-backed when `DATABASE_URL` (0pt's own metadata store) is set, in-memory only in non-production/tests. `run` mode refuses to start without `DATABASE_URL` explicitly, so a scheduled run can never silently fall back to re-reading everything from the beginning.
|
||||
|
||||
## Testing
|
||||
|
||||
Fixture-backed (no real infra): watermark + limit correctness, a same-timestamp tie at a page boundary, resume-from-checkpoint after a simulated crash (via a sink that throws mid-run, mirroring `tests/p0/ingestion-runner.test.ts`'s own technique), the empty-table case (zero rows, zero envelopes, no throw), and the narrow vehicle-dimension lookup asserted at the *query* level (every id ever bound into a query is a subset of the referenced set; a vehicle never referenced by the batch is never queried).
|
||||
|
||||
Also verified against a **real, disposable Postgres container** (not just fixtures), both seeded and truncated-to-empty, before touching production — caught and fixed two real bugs the fixture-only tests could not have caught:
|
||||
|
||||
1. `timestamptz` columns come back from the real driver as JS `Date` objects, not strings — the initial cursor-encoding logic did `String(date)` (locale-dependent, useless as a stored watermark) instead of `.toISOString()`. Fixed; regression test added (`tests/connectors/postgres-watermark-connector.test.ts`, "real Postgres driver value shapes").
|
||||
2. The same `Date`-vs-string mismatch tripped the P063 schema-conformance gate on every row (`field "listed_at" is object, expected string`) until the connector's `toRecord()` was made to normalize every `Date`-valued payload field to ISO before building the envelope.
|
||||
|
||||
**Verified read-only against actual production** (server10, `vehiq-db`, via `fleet`), 2026-09-25: the connector's exact SQL (`SELECT id, tenant_id, vehicle_id, lot_location, floorplan_status, listed_at, sold_at FROM app.dealer_stock_entry ORDER BY listed_at, id LIMIT 100` and the equivalent for `app.deal`) executed directly, read-only, and returned **zero rows, no error** — confirming both that the extractor's query shape is valid against the live schema and that there is genuinely nothing to extract yet. `vehiq.vehicle`'s `vehicle_id` primary-key column name was confirmed via `information_schema.columns` only — no vehicle data rows were read. **The compiled service itself was not run against production** — only its exact SQL, via read-only `psql`, matching this pass's "prove it does nothing, don't deploy a live service yet" scope.
|
||||
|
||||
## Deferred: full vehicle-dimension backfill
|
||||
|
||||
Not built or run in this pass, per the task's explicit instruction. If/when a full `dimension_vehicle` snapshot is ever wanted (as opposed to the permanent narrow per-batch lookup this extractor does forever), it needs its own deliberate decision:
|
||||
|
||||
- **Chunking**: page through `vehiq.vehicle` by primary key range (`vehicle_id > :last ORDER BY vehicle_id LIMIT :n`), never an unbounded scan — the same shape `PostgresWatermarkConnector` already implements, just pointed at a PK range instead of a timestamp (this connector's own `validate()` refuses `vehiq.vehicle` by name specifically to keep this a distinct, deliberate choice rather than an accidental default).
|
||||
- **Throttle**: an explicit delay between chunks, watching server10's `iostat`/`vmstat`/CPU while it runs — 98M rows / 85GB is enough to matter even read-only.
|
||||
- **Checksum + reconciliation**: a row-count and content checksum comparison between source and `opt_dataset_projection` after the backfill, recorded, before trusting it.
|
||||
- **Watermark handoff**: the backfill's end position must hand off cleanly to the narrow per-batch lookup this extractor already does, so nothing is double-counted or gapped at the boundary.
|
||||
|
||||
This mirrors the numbered runbook `admin/vehiq`'s `docs/CURRENT_STATE.md` already wrote for the general CDC case (not executed there either) — the shape is consistent, deliberately, rather than inventing a second convention.
|
||||
|
||||
## Deferred: `app.listing` extraction
|
||||
|
||||
Blocked on a schema decision, not an engineering gap: `app.listing` has no timestamp column today. Unblocking it needs one of:
|
||||
|
||||
1. Apply `admin/vehiq` migration `0084_listing_deal_lifecycle_timestamps.sql` (adds `published_at`/`unpublished_at`) — a decision for whoever owns that repo's migration pipeline, not this pass.
|
||||
2. Add a generic `updated_at` + trigger to `dealer_stock_entry`/`deal`/`listing` — closes both this gap and the "insert-only watermark misses in-place updates" caveat above in one move, but is a real schema change on production and needs Simon's explicit sign-off per the hard rule against touching production schema unsupervised.
|
||||
|
||||
Once either lands, adding a third `VehiqOltpSourceDef` entry to `VEHIQ_OLTP_SOURCES` (`src/ingestion/vehiq-oltp-ingest-runner.ts`) is the only code change needed — the connector, runner, sink and tests are all already generic across sources.
|
||||
|
||||
## What activating this in production actually requires
|
||||
|
||||
Nothing here is scheduled or running. To turn it on:
|
||||
|
||||
1. **A read-only Postgres role on `vehiq-db`** (server10) with `SELECT` on exactly `app.dealer_stock_entry` and `app.deal` (not the whole `app` schema, not `vehiq.vehicle` beyond what the narrow lookup needs) — creating this role is a production database change and should be coordinated explicitly, the same posture `admin/vehiq`'s own CDC runbook already takes for a bigger version of this same question. Its connection string becomes `VEHIQ_SOURCE_DATABASE_URL`.
|
||||
2. **`DATABASE_URL`** — 0pt's own metadata Postgres, for durable checkpoints. Already exists for every other 0pt capability; reuse it, do not provision a new one for this.
|
||||
3. **`OPT_ANALYTICS_CLICKHOUSE_BASE_URL` / `OPT_ANALYTICS_CLICKHOUSE_BASIC_AUTH`** — the already-deployed `opt-analytics-clickhouse` on server6 (internal-only, reachable from containers on the `coolify` network — see `admin/vehiq`'s `docs/CURRENT_STATE.md`, "0pt production ClickHouse 26.8 LTS"). A real least-privilege application user should be provisioned for this connector specifically, not the schema-admin `opt_admin` user mentioned there.
|
||||
4. **`VEHIQ_INGEST_MODE=run`** on the scheduled workflow (default is `preview`, which never writes).
|
||||
5. A decision on whether `.gitea/workflows/vehiq-oltp-ingest.yml`'s cron schedule should actually be enabled (it is present and correctly configured, but Gitea Actions secrets are not set on this repo by this pass — an unset `VEHIQ_SOURCE_DATABASE_URL` makes every scheduled run a clean no-op, so leaving the workflow file in place with no secrets configured is safe, but is not the same as "this is now extracting real data").
|
||||
|
||||
None of steps 1-3 were done in this pass — they require production credentials/role provisioning this pass does not have standing authority to create unsupervised.
|
||||
-277
@@ -1,277 +0,0 @@
|
||||
# 0pt — capability status (Master-DoD §56 status honesty)
|
||||
|
||||
> Classification scale (Master-DoD §2, exactly one per capability):
|
||||
> `MISSING → DOCUMENTED_ONLY → SKELETON → MOCK_ONLY → IMPLEMENTED → INTEGRATION_TESTED → LIVE_VERIFIED → PRODUCTION_READY`.
|
||||
> Only `PRODUCTION_READY` may be called DONE. Docs ≠ implementation.
|
||||
> Last full audit + re-classification: **2026-08-31** (SIAX Platforms P0 wave 2).
|
||||
|
||||
## How to read this
|
||||
|
||||
- **INTEGRATION_TESTED** here means: verified against a REAL dependency
|
||||
(live OpenSearch/ClickHouse container, or a recorded wire-contract double
|
||||
pinned to the sibling repo's real handler code on its `main`) in CI.
|
||||
- **LIVE_VERIFIED** requires a verification against the actual SIAX fleet
|
||||
deployment. No new capability in this wave claims it.
|
||||
- The unit/contract/integration suites are in `tests/` and run in
|
||||
`.gitea/workflows/ci.yml` (jobs `quality` + `integration`).
|
||||
|
||||
## Cross-product clients (Master-DoD §10 "Cross-product clients")
|
||||
|
||||
| Capability | Status | Evidence | Honest gaps |
|
||||
|---|---|---|---|
|
||||
| CL0UD client (policy evaluate, `POST /api/policy/evaluate`) | **INTEGRATION_TESTED** (contract) | `src/clients/cl0ud-client.ts`; `tests/contracts/cl0ud-client.contract.test.ts` pins the real camelCase `{data}` envelope; fail-closed (missing decision ⇒ deny) | Not yet exercised against a live CL0UD deployment (no reachable CL0UD URL this session ⇒ not LIVE_VERIFIED) |
|
||||
| CL0UD capability discovery (`GET /api/capabilities`) | **INTEGRATION_TESTED** (contract) | same suite | 0pt's own capabilities are not yet registered in CL0UD's registry (§3 gap) |
|
||||
| ST0RE client (artifact register, camelCase `/v1/st0re/artifacts/register`) | **INTEGRATION_TESTED** (contract) | `src/clients/st0re-client.ts`; `tests/contracts/st0re-client.contract.test.ts` | Raw-bytes upload still goes via LocalBlobStore interim (pre-existing, unchanged); presign upload path not consumed yet |
|
||||
| N0D client (create/get job, get result) | **INTEGRATION_TESTED** (contract) | `src/clients/n0d-client.ts`; `tests/contracts/n0d-client.contract.test.ts` pins `required_role`/`resource_requirements`/body `idempotency_key` | CloudEvents completion callback receiving endpoint not built in 0pt (poll path works) |
|
||||
| AUD0 client (events + OpenLineage ingest) | **INTEGRATION_TESTED** (contract) | `src/clients/aud0-client.ts`; `tests/contracts/aud0-client.contract.test.ts`; legacy lineage shape converts to real OpenLineage | No durable local outbox for AUD0 outages (§70 "durable local/outbox path" — emission failure is surfaced, not queued) |
|
||||
| **No production mock fallback (§3/§10)** | **INTEGRATION_TESTED** | `src/platform/dependency-mode.ts`; `tests/contracts/dependency-mode.contract.test.ts` drives NODE_ENV=production for all four factories ⇒ hard `DEPENDENCY_UNAVAILABLE` | — |
|
||||
|
||||
**Correction of prior state (2026-08-31):** the pre-existing clients' HTTP
|
||||
paths were verified against the sibling repos' actual `main` branches and
|
||||
THREE of four were wrong: cl0ud (`/v1/cl0ud/policies/evaluate` — never
|
||||
existed), st0re (snake_case body — would 400), aud0 lineage
|
||||
(`/v1/aud0/lineage/events` — never existed). All fixed and pinned by
|
||||
contract tests. The earlier MOCK_ONLY classification in the README was
|
||||
accurate.
|
||||
|
||||
## Data-OS capabilities (Master-DoD §10)
|
||||
|
||||
| Capability | Status | Evidence | Honest gaps |
|
||||
|---|---|---|---|
|
||||
| Source Registry — register/query/describe/health, rights/license/purpose, freshness, provenance | **IMPLEMENTED** | `src/services/source-registry-service.ts`, `src/types/source-registry.ts`; `tests/p0/source-registry.test.ts` (fail-closed purpose gate, cross-tenant NOT_FOUND) | In-memory persistence (per-process); no Postgres store yet — production boot must therefore configure one before this counts further. No API route surface yet |
|
||||
| Source rate-policy | **IMPLEMENTED** (pre-existing) | `src/services/source-rate-policy-service.ts` | unchanged this wave |
|
||||
| Search — OpenSearch adapter, index defs, bulk, tenant + purpose/rights filter, rebuild, generation switch | **INTEGRATION_TESTED** | `src/search/*`; unit `tests/p0/search-service.test.ts`; **real OpenSearch 2.11** `tests/integration/search-opensearch.integration.test.ts` incl. projection-disaster rebuild (§68-style) — runs in CI service container | Hybrid (vector) query not built; no metrics emission; index definitions in-memory |
|
||||
| Quality — versioned rules, runs, results, issues, score, trend, GE interchange | **IMPLEMENTED** (local engine) / **SKELETON** (GE delegation) | `src/quality/*`; `tests/p0/quality-service.test.ts`, `tests/p0/expectation-engine` cases | Local engine covers 7 GE core expectation types; everything else delegates via N0D job `0pt.quality.ge_run` whose EXECUTOR (0pt-motor GE runner) does not exist yet — delegated runs stay "delegated" until it does. Never fabricates results |
|
||||
| Dataset — create (pre-existing) + version/query/export with `st0re:artifact:` refs | **IMPLEMENTED** | `src/services/dataset-version-service.ts`; `tests/p0/dataset-version-service.test.ts` (idempotency §53, canonical refs §5) | Export assumes bytes already written by a job; no route surface; in-memory persistence |
|
||||
| Lineage — OpenLineage emission to AUD0's real ingest | **INTEGRATION_TESTED** (contract) | `src/lineage/*`; aud0 contract suite; emitted from dataset version/export, quality runs, search rebuilds | Emission is best-effort (never-throw); no outbox. AUD0-side ingestion verified against contract double, not live AUD0 |
|
||||
| Metadata — OpenMetadata projection (never canonical) | **IMPLEMENTED** | `src/metadata/openmetadata-adapter.ts`; `tests/contracts/metadata-features.contract.test.ts`; `projectAll` rebuild path | No live OpenMetadata exercised (no local container this pass); lineage/glossary/ownership projection not built — only dataset entities |
|
||||
| Analytics — ClickHouse, tenant-isolated, query limits, retention | **INTEGRATION_TESTED** | `src/analytics/clickhouse-analytics.ts`; **real ClickHouse 24.8** `tests/integration/analytics-clickhouse.integration.test.ts` (tenant isolation, closed DSL, TTL schema) — runs in CI service container | Closed metric-DSL only (no ad-hoc queries by design); no quota integration with CL0UD |
|
||||
| Features — registry + Feast adapter | **IMPLEMENTED** (online path, registry) / **SKELETON** (materialize/get-historical) | `src/features/feast-adapter.ts`; contract suite pins Feast's `get-online-features` wire shape | No live Feast server exercised; offline/materialization are N0D delegation contracts whose executor (0pt-motor) does not exist yet; point-in-time correctness therefore NOT yet proven |
|
||||
| Entity Resolution — candidate API, blocking, explanation, hard-rule hook, review handoff | **IMPLEMENTED** | `src/er/entity-resolution-service.ts`; `tests/p0/entity-resolution.test.ts` (hard rules override both directions, review band, blocking refusals) | Generic reference scorer (Jaccard+Levenshtein), NOT Splink probabilistic linkage — that is the `0pt.er.batch_resolution` N0D contract, executor pending in 0pt-motor. No persistence of review queues |
|
||||
| Graph (§10 Graph) | **MISSING** | — | Not started this wave (explicitly out of the delivered P0 subset; next in line per §10) |
|
||||
|
||||
## Canonical platform plumbing
|
||||
|
||||
| Capability | Status | Evidence |
|
||||
|---|---|---|
|
||||
| SiaxRequestContext + propagation headers (mirror of cl0ud `@siax/contract`) | **INTEGRATION_TESTED** (contract-pinned) | `src/platform/siax-context.ts`; `tests/contracts/siax-context.contract.test.ts` |
|
||||
| Canonical 12-code error model + typed `SiaxError` (§6) | **INTEGRATION_TESTED** (contract-pinned) | `src/platform/errors.ts`; same suite |
|
||||
| Canonical resource refs (§5) | **IMPLEMENTED** | `src/platform/resource-ref.ts`; `tests/p0/dataset-version-service.test.ts` |
|
||||
|
||||
## Pre-existing capabilities (unchanged this wave — prior classifications stand)
|
||||
|
||||
| Capability | Status | Note |
|
||||
|---|---|---|
|
||||
| Iceberg write boundary via ST0RE lakehouse | LIVE_VERIFIED (2026-07-13) | `docs/ICEBERG_WRITE_BOUNDARY.md`; untouched |
|
||||
| Document capture/extraction | IMPLEMENTED | LocalBlobStore interim persists bytes; ST0RE raw upload still pending |
|
||||
| Edge order/payment app (Next.js) | see `docs/architecture/ARCHITECTURE.md` | outside this wave's scope |
|
||||
| FastAPI engine (`services/api`) | IMPLEMENTED | outside this wave's scope |
|
||||
| `services/scrapers/*` (WAF-bypass stack) | **quarantined, pending deletion PR** | `feature/0pt-remove-noncompliant-scrapers` — NOT touched by this wave; nothing new wires it |
|
||||
|
||||
## Global gaps blocking PRODUCTION_READY (§3, tracked, not hidden)
|
||||
|
||||
1. Persistent stores REMAINING: quality runs/rules and feature views are
|
||||
still per-process in-memory (`resolveStoreMode` guarantees production
|
||||
boot FAILS rather than serving Maps). CLOSED since the last revision:
|
||||
dataset registry (`opt_datasets`) + immutable versions
|
||||
(`opt_dataset_versions`, monotonic under transaction lock, idempotency
|
||||
with payload-drift detection, cross-tenant ⇒ NOT_FOUND) and versioned
|
||||
search index definitions (`opt_search_index_definitions`, sequential
|
||||
schema versions, replay-idempotent, same-version-different-schema ⇒
|
||||
CONFLICT; OpenSearch remains a rebuildable projection, never canonical
|
||||
truth) are Postgres-canonical with real-Postgres tests.
|
||||
2. Capability registration in CL0UD + API0 discovery for the new
|
||||
capabilities (§3 "Capability är registrerad i CL0UD Capability
|
||||
Registry") — PARTIALLY CLOSED: the collaboration/meeting domain was
|
||||
canonicalized in CL0UD's registry (cl0ud #73/#74); 0pt's own
|
||||
capability set still needs the same registration.
|
||||
3. CLOSED: AUD0 outbox for evidence durability under AUD0 outage (§70) —
|
||||
durable Postgres outbox + dispatcher (at-least-once, bounded batch,
|
||||
backoff, dead-letter, SKIP LOCKED leasing, tenant binding, idempotency)
|
||||
+ real-Postgres tests; dispatcher uses explicit `durable:false` so it
|
||||
never re-enqueues its own delivery evidence.
|
||||
4. CLOSED for datasets/versions/search/ER: `app/api/0pt/datasets*`,
|
||||
`app/api/0pt/search/definitions` + tenant-safed query route, and
|
||||
`app/api/0pt/er/{candidates,batch}` (+ internal ER route) are live;
|
||||
clients cannot raise `rights_tag` via request body (fail-closed to
|
||||
`internal`). Quality routes exist (`bridge-run/issues/rules/runs`).
|
||||
5. 0pt-motor executors for the delegated jobs
|
||||
(`0pt.quality.ge_run`, `0pt.features.*`, `0pt.er.batch_resolution`).
|
||||
6. Observability: no metrics/traces emitted by the new services (§36).
|
||||
|
||||
---
|
||||
|
||||
## P060-P068 ingestion plane (added 2026-09-04)
|
||||
|
||||
Classification scale unchanged. Every row below states what was actually
|
||||
verified, and by which command.
|
||||
|
||||
| Requirement | BEFORE this pass | Status now | Evidence |
|
||||
|---|---|---|---|
|
||||
| **P060** Source Registry: durable canonical registry; restart preserves sources; an unclassified source cannot be activated | **PARTIAL / BROKEN.** The registry existed with Postgres persistence (`sql/002_source_registry.sql`, `src/repositories/postgres-source-registry-repository.ts`) and carried source_id/tenant/project/type/status/license/purpose/rights. It had NO authorization, NO schedule, NO checkpoint, NO schema, and no `owner` distinct from `created_by`. The activation DoD was inverted: `postgres-source-repository.ts:70` wrote `${input.status ?? "active"}`, so a source with no rights, no provenance and no authorization was ACTIVE the instant it was registered, and no activation operation existed at all | **INTEGRATION_TESTED** | `sql/007_ingestion_plane.sql` (authorization/schedule/schemas/checkpoints + `ALTER … SET DEFAULT 'pending'` + `owner_id`); `SourceRegistryService.classifySource`/`activateSource`; `tests/p0/source-activation-gate.test.ts` (11); `tests/api/0pt-p060-routes.test.ts` (9); `tests/p0/ingestion-plane-postgres.realinfra.test.ts` against a live Postgres 16 |
|
||||
| **P061** Connector contract: discover/validate/connect/checkpoint/read/resume/backfill/health/disconnect; two heterogeneous connectors pass one conformance suite | **MISSING.** `services/api/sources/connectors.py` had per-source `fetch_*()` functions only — no lifecycle, no cursor, no resume, no health, no disconnect, no conformance suite | **INTEGRATION_TESTED** | `src/connectors/connector.ts` (all nine operations); `src/connectors/conformance.ts` (15 checks); `HttpJsonConnector` (real node:http server, opaque cursor) and `JsonlFileConnector` (real file, line-offset cursor, CDC deletes) both pass the identical suite — `tests/p0/connector-conformance.test.ts`, which also proves the suite FAILS a fail-open connector |
|
||||
| **P062** CDC/batch/stream normalized to one envelope; restart resumes from a durable checkpoint without silent gaps | **MISSING**, and documented as such: `services/api/tests/test_known_gaps.py:10-19` skipped the CDC case because no CDC pipeline existed anywhere, and `workers/pipeline.py` had no persistence at all | **INTEGRATION_TESTED** | `src/types/ingestion.ts` (one envelope for all three modes); `src/ingestion/ingestion-runner.ts`; `tests/p0/ingestion-runner.test.ts` kills a run inside the sink and proves the resumed run covers all 10 records exactly once; same proof against real Postgres across fresh processes |
|
||||
| **P063** Schema versioning + compatibility policy; a breaking schema is detected before consumer corruption | **MISSING.** `schema_version` existed as a free-form string on datasets/Iceberg writes; there was no comparison, no policy, no versioned source schema | **INTEGRATION_TESTED** | `src/schema/compatibility.ts`, `src/schema/schema-registry.ts`; `tests/p0/schema-evolution.test.ts` (12); the runner's schema gate runs before the first read — `tests/p0/ingestion-runner.test.ts` asserts `sinkCalls === 0` on a break |
|
||||
| **P064** Quality rules behind the SIAX abstraction; failures block or quarantine per declared policy | **PARTIAL.** `src/quality/*` had rules, runs, results, issues, scores and a GE-compatible engine, but a failing rule only opened an ISSUE — the data flowed on regardless. `grep -ri quarantin src/` found one unrelated hit | **INTEGRATION_TESTED** | `src/quality/quality-policy.ts` composes the EXISTING `ExpectationEngine` (not a second engine) and adds the consequence; block / quarantine / warn each proved in `tests/p0/ingestion-runner.test.ts`; quarantine durability proved against real Postgres |
|
||||
| **P065** Normalization/ER: only the canonical highway; no second simplified production engine | **CLOSED.** `services/api/workers/resolve.py` is now a thin adapter: Python no longer scores identity — it POSTs opaque records to `/api/0pt/internal/er/candidates` and applies ONLY explicit hard-rule `match` decisions (score/fuzzy can never merge records, even from a compromised bridge); canonical engine unreachable ⇒ records return UNMERGED, never fallback-scored. Company semantics `stable-identifiers.v3`: LEI global; org_nr hard identity only within the same registration_country; punctuation normalized; negative stable identity dominates every positive; fuzzy alone ⇒ human review, never auto-merge. Cluster-wide hard-negative constraints: A≈B ∧ B≈C never forces A≈C when canonical identity says A≠C | **INTEGRATION_TESTED** | `tests/p0/entity-resolution.test.ts` (v3 semantics incl. hard-negative transitivity), `tests/p0/entity-resolution-http.test.ts` (internal route fails closed: empty/wrong token ⇒ 401), `services/api/tests/test_resolve_determinism.py` (adapter contract: canonical edges only), shared request validation (`src/er/request-validation.ts`, records 2..5000), blocking pytest gate (`.gitea/workflows/python-engine.yml`) |
|
||||
| **P066** Iceberg | out of scope — ST0RE is owned by another workflow | **NOT TOUCHED** | Contract read only (`src/services/iceberg-write-service.ts`, `src/clients/st0re-lakehouse-client.ts`) |
|
||||
| **P067** Lineage: OpenLineage/AUD0 events; source → output lineage is queryable | **PARTIAL.** `src/lineage/lineage-emitter.ts` emitted OpenLineage to AUD0, but nothing in this repo could ANSWER a lineage question — no store, no query, no route | **INTEGRATION_TESTED** | `src/lineage/lineage-edge.ts`, `src/lineage/lineage-store.ts` (local queryable projection; AUD0 stays the system of record), `GET /api/0pt/lineage`; `tests/p0/ingestion-runner.test.ts` queries both directions and proves tenant scoping |
|
||||
| **P068** Durable bounded backfill/replay; repeated backfill is idempotent | **MISSING**, documented as such: `services/api/tests/test_known_gaps.py:44-52` skipped it because "no delivery-store persistence layer exists to dedupe a backfill against" | **INTEGRATION_TESTED** | `opt_ingestion_ledger` + `IngestionRunner.backfill`; `tests/p0/ingestion-runner.test.ts` (repeat emits 0, live checkpoint untouched, a real content change still re-emits); same against real Postgres |
|
||||
|
||||
### What was actually run (not "should pass")
|
||||
|
||||
- `pnpm run typecheck` — clean.
|
||||
- `pnpm run test` — **365 passed, 25 skipped** (was 311/18 before this pass).
|
||||
- `pnpm run build` — clean; the four new routes appear in the route table.
|
||||
- `pnpm run lint` — 12 errors / 5 warnings, **all pre-existing** (identical
|
||||
count on the base commit; advisory in CI). This pass adds none.
|
||||
- Real Postgres 16: `tests/p0/ingestion-plane-postgres.realinfra.test.ts`
|
||||
with `INGESTION_TEST_DATABASE_URL` — 7 passed.
|
||||
- **Real container restart**, run manually against that same database:
|
||||
`docker restart` the Postgres container, then re-read through the real
|
||||
repositories. Before and after were identical — 2 sources (one `active`
|
||||
with its owner, one `pending`), 1 checkpoint (cursor 6, 6 committed),
|
||||
6 ledger rows, 1 lineage edge, 4 quarantined records, 1 schema version.
|
||||
That is P060's "a restart preserves all sources", measured rather than
|
||||
asserted.
|
||||
|
||||
### A real bug this pass wrote and then caught
|
||||
|
||||
The first draft of `IngestionRepository` combined the idempotency check and
|
||||
its recording into one atomic call, made BEFORE the sink. The crash/resume
|
||||
test then delivered **7 of 10 records**: the page in flight when the sink
|
||||
died had already been marked delivered, so the resumed run skipped it as a
|
||||
duplicate — permanent, silent data loss. The fix is the `peekDeliveries` /
|
||||
`commitDeliveries` split, with both the ledger commit and the checkpoint
|
||||
commit after the sink resolves. Recorded here because the failure mode is
|
||||
the interesting artifact, not the fix.
|
||||
|
||||
### Honest gaps in the new plane (not hidden)
|
||||
|
||||
1. **Delivery is AT-LEAST-ONCE, not exactly-once.** Two concurrent runs on
|
||||
the same (source, partition) can both peek "new" and both emit.
|
||||
`envelope_id` is deterministic so a dedup-capable sink survives it. There
|
||||
is no per-(source, partition) run lock. Do not describe this plane as
|
||||
exactly-once.
|
||||
2. **No CDC *source* exists.** The envelope, the operations and the runner
|
||||
handle change events, and `JsonlFileConnector` emits real deletes from an
|
||||
`_op` field — but this repo still has no Debezium/WAL/replication-slot
|
||||
consumer. P062's contract is met; a CDC connector is still MISSING.
|
||||
3. **0pt does not schedule itself.** `opt_source_schedule` is a declaration
|
||||
ACT0 would read; there is no cron daemon here.
|
||||
4. **The sink is caller-supplied.** The runner stops at the sink; the
|
||||
lakehouse write boundary is ST0RE's (P066, another workflow's repo).
|
||||
5. **Nothing here is deployed.** See the deployment note below.
|
||||
6. **`QualityService`'s own rule/run/issue registry is still in-process
|
||||
Maps** (`src/quality/quality-service.ts:47-50`). The new *enforcement*
|
||||
path is durable; the older rule registry is not. Unchanged by this pass.
|
||||
7. **Python tests still run nowhere.** `grep -rn "pytest" .gitea/workflows
|
||||
.github/workflows` finds nothing — `services/api/tests/*` (9 files) has
|
||||
never been executed by CI. Flagged, not fixed (it needs a workflow change
|
||||
and a Python toolchain decision).
|
||||
|
||||
### Deployment reality, measured 2026-09-04
|
||||
|
||||
`https://0pt.app/api/health` answers **200** from **Vercel** with
|
||||
`{"db":"not_configured"}`, and `https://0pt.app/api/0pt/sources` answers
|
||||
**404** — the deployed build predates the entire `app/api/0pt/*` capability
|
||||
layer. `https://api.0pt.app/health` answers **404** (the FastAPI engine is
|
||||
not reachable), and `.gitea/workflows/cd.yml` still guards on
|
||||
`COOLIFY_APP_ID = TODO-no-coolify-app-provisioned-yet`. So: none of the
|
||||
capability layer — neither this pass's work nor P010/P014's — is running in
|
||||
production, and P060's durability guarantee cannot be exercised there,
|
||||
because production has no database configured and does not serve the routes.
|
||||
Verified with `curl`; not inferred.
|
||||
|
||||
### P065 — closure record (2026-09-07)
|
||||
|
||||
The removal plan below was executed in full and is verified in CI:
|
||||
|
||||
1. ✅ Canonical ER exposed as `POST /api/0pt/er/candidates` (public,
|
||||
tenant-safed) AND `POST /api/0pt/internal/er/candidates` (service-token,
|
||||
fails closed without `X-Internal-Token`).
|
||||
2. ✅ Python CI job: `.gitea/workflows/python-engine.yml` runs
|
||||
`services/api/tests` as a BLOCKING pytest gate.
|
||||
3. ✅ `workers/resolve.py` rewritten as the HTTP adapter — fail-closed to
|
||||
UNMERGED records when the bridge is unreachable; no fallback scorer
|
||||
remains. Cluster-wide hard-negative constraints prevent transitive
|
||||
matches from overriding canonical identity decisions.
|
||||
4. ✅ `services/api/tests/test_resolve_determinism.py` asserts the adapter
|
||||
contract: canonical match edges merge; review/non-match edges do not;
|
||||
hard negatives are respected transitively.
|
||||
|
||||
Residual honesty: the PYTHON-side tests run in CI, but the full
|
||||
adapter→Next.js route chain has not been exercised against a live deployed
|
||||
edge in this branch (the route's own fail-closed behavior is unit-proven).
|
||||
That keeps P065 at INTEGRATION_TESTED, not LIVE_VERIFIED.
|
||||
|
||||
---
|
||||
|
||||
## SLUTPRODUKTIONS-VERIFIERING 2026-09-22 (live-mätt, ej påstått)
|
||||
|
||||
**Prod: `https://0pt.app` på flottan (server6, Coolify-app `shxd6lepxuxfsjsp0ath3z1g`),
|
||||
container-image på exakt merge-SHA `df6ab70` via den signerade release-kedjan
|
||||
(cosign-attestation verifierad före redeploy). DNS A → 65.109.19.146,
|
||||
NS chris/maxine.ns.cloudflare.com — Vercel är borta.**
|
||||
|
||||
### Live-matris, mätt med curl (2026-09-22 04:09 UTC)
|
||||
|
||||
| Yta | Resultat |
|
||||
|---|---|
|
||||
| Front `/` + 10 nyckelsidor (bestall, katalog, kallor, tjanster, portal, admin, order) | 200 ×11 |
|
||||
| `/api/health` | 200 `{ok:true, db:"ok", engine:"ok"}` |
|
||||
| `/api/ready` | 200 (fail-closed-grinden: var 503 före DB-provisioneringen) |
|
||||
| `/api/0pt/*` (9 rutter) anonymt | **401 ×9** — S1-luckan (2026-08-07: anonym 200) är STÄNGD |
|
||||
| `/api/orders`, `/api/admin/metrics` anonymt | 401 |
|
||||
| `/api/subscriptions` | 200 `[]` (var 500: migration 014, se nedan) |
|
||||
| `POST /api/estimates` | 200 (edge räknar + engine-wire) |
|
||||
| `GET /api/catalog`, `/api/sources` | 200 (publika läsvyter, avsiktligt) |
|
||||
| `GET /api/vehicles` utan param | 400 (kräver reg-nr — korrekt) |
|
||||
| Security headers | HSTS(63072000+preload) · CSP · XFO DENY · nosniff · ingen X-Powered-By |
|
||||
|
||||
### Denna pass fixat (3 PR, alla mergerade + deployade live)
|
||||
|
||||
1. **PR #80** — G17 hook-pin re-bump `7725498 → a401880` (re-review: 0 diff under
|
||||
`ci/v2/reference-hooks/`). Release chain + gated deploy gröna igen.
|
||||
2. **PR #81 (fix för issue #53)**: 7 legacy money-routes (orders, orders/[id],
|
||||
subscriptions, payments/deposit, payments/release, webhooks/stripe,
|
||||
admin/metrics) mappar nu `SiaxError(DEPENDENCY_UNAVAILABLE, 503, retryable)`
|
||||
via `app/api/siax-error-mapping.ts` i stället för att läcka Next opaka 500.
|
||||
Stripe-webhooken svarar 503 `received:false reason:store_unavailable` på
|
||||
store-outage — aldrig tyst `received:true` för ett betalt event som inte
|
||||
processats. 3 nya tester pinar kontraktet.
|
||||
3. **PR #86**: `sql/014_subscriptions_created_at.sql` — `lib/subscriptions-store.ts`
|
||||
SELECT:ade `created_at` som `001_init.sql` aldrig definierat (42703 mätt live:
|
||||
GET /api/subscriptions har ALWAYS varit 500 mot Postgres). Kolonnen ADD:ad
|
||||
idempotent LIVE på 0pt-edge-postgres; route svarar nu 200 `[]`.
|
||||
4. **PR #87**: cd-gatens not-ready-regex — cosign 3.1.3 säger
|
||||
`no matching attestations:` (utan `found`); en transient not-ready misstolkades
|
||||
som hårt verify-fel. Fail-closed för riktiga attestfel oförändrad.
|
||||
5. **CI-infra reparerad**: repo-secrets `SIAX_CI_TOKEN` + `REGISTRY_TOKEN` var
|
||||
döda efter token-svepet (2026-09-22 eng0-introspect-rotation revoade 107+ tokens;
|
||||
fällan: 0pt:s repo-secret överrider org-secreten — org-PUT räcker inte). Nya
|
||||
siax-ci-tokens (`write:package,read:package` + all) mintade och satta via
|
||||
secrets-API (PUT 204, verifierade via lyckad release-kedja).
|
||||
|
||||
### 0pt-motor (engine, satellite)
|
||||
|
||||
- 6 containers Up på server6 (`motor-provisional`), core `/health` ok+pg+redis,
|
||||
delivery `/version` = fb67870, core revision = 6cfd433 — båda IN main.
|
||||
- CI grön på main (runs 55985/55987/56004) — healer-issue #38 (run 40562,
|
||||
2026-09-20) stängd som transient runner-flake (apt-GPG under last).
|
||||
- Bara `main` kvar i 0pt och 0pt-motor (8 + 6 stale grenar raderade — alla
|
||||
bevisade redan mergerade via `git merge-base --is-ancestor`).
|
||||
- motor/-executor-koden (signals/NER/normalization, 3507 rader nya sedan 6cfd433)
|
||||
konsumeras av `Dockerfile.motor`-imaget som ännu inte har ett driftsatt runtime
|
||||
i stacken (core/ingest/resolve/delivery importerar ej motor/ — verifierat
|
||||
import-graf). Byggs enligt `scripts/build-images.sh` + `verify-image.sh`-gaten
|
||||
när executor-ytan aktiveras — dokumenterat i `docs/runbook/deploy.md`.
|
||||
|
||||
### Kvarstår (ärligt, ej gömt)
|
||||
|
||||
1. **Stripe-creds** (Simon): live-keys → edge-envs `STRIPE_SECRET_KEY`/`STRIPE_WEBHOOK_SECRET`.
|
||||
Innan dess förblir payments 501 och issue #67:s staging-triage kan ej köras.
|
||||
2. **queue: not_configured** — ingen Redis i edge-stacken (ärligt rapporterat).
|
||||
3. **`0pt.siax.io`/`motor.siax.io`**: medvetet ej återupprättade (0pt.app + lokala
|
||||
127.0.0.1-portar är kanoniska ytor; issues #70/#35 stängda/avgjorda därefter).
|
||||
4. **motor.siax.io**: motor:s publika yta kräver Simon-beslut (traefik-labels + DNS).
|
||||
@@ -1,60 +0,0 @@
|
||||
# ADR-0001 — Server-renderad authz-resolution för orderåtgärder
|
||||
|
||||
**Status:** Accepted
|
||||
**Date:** 2026-09-29
|
||||
**Owners:** 0pt (simon@siax.io)
|
||||
**Related requirements:** DoD §21 (backend enforcement), §78 (error/why-UX), våg 3.6–3.7 (authz-ux/entitlement)
|
||||
**Related capabilities:** `@siax/contracts/authz-ux` 0.10.0, `@siax/ui` ActionGate 0.11.1
|
||||
|
||||
## Context
|
||||
Admin-ordkön behöver gate:a advance-aktionen. 0pt saknar klientsides-policy;
|
||||
`requireOrderOwner` är server-side. Att resolvé:a i klienten vore påhittad
|
||||
policy (DoD §15).
|
||||
|
||||
## Existing implementations
|
||||
- PATCH `/api/orders/{id}` enforcar ägarskap server-side (sanningsvärdet).
|
||||
- Admin-sidan hämtar ordrar via GET `/api/orders` (owner-scopad).
|
||||
|
||||
## Decision
|
||||
**Server-renderad resolution:** GET `/api/orders` returnerar per order ett
|
||||
frozen `advance_action` (ResolvedAction från `resolveAction`), derivat i
|
||||
`lib/order-flow.ts` ur kanoniskt flöde + sessionens ägarskap. Klienten
|
||||
renderar via `ActionGate` — ingen policylogik i UI-lagret. Ingen extra
|
||||
fetch: resolutionen rids med ordningssvaret.
|
||||
|
||||
## Ownership
|
||||
0pt äger flödet och resolutionen; DES1GN äger kontraktet (`authz-ux`) och
|
||||
renderingen (ActionGate). Product Firewall: 0pt importerar @siax/*, aldrig
|
||||
tvärtom.
|
||||
|
||||
## Contract
|
||||
`ResolvedAction {state, reason?}` — stängda uppsättningar enligt authz-ux.
|
||||
|
||||
## Provider boundary
|
||||
Framtida pay0-entitlement projiceras via `deriveEntitlement` in i samma
|
||||
resolve — ingen ny endpoint behövs.
|
||||
|
||||
## Dependency rules
|
||||
`@siax/ui`/`@siax/contracts` → 0pt. Aldrig reverse.
|
||||
|
||||
## Migration
|
||||
Enda konsument: admin-sidan (denna PR). Övriga ytor migreras per aktion.
|
||||
|
||||
## Alternatives considered
|
||||
- **Klientsides-resolution mot ny endpoint:** extra roundtrip, policy-läckage
|
||||
risk, mer kod — avvisad.
|
||||
- **Hårdkodad disabled i UI:** duplicerar serverns sanningsvärde — avvisad
|
||||
(DoD §21: backend är enforcement, UI är presentation).
|
||||
|
||||
## Risks
|
||||
Flödesändringar måste skriva i `lib/order-flow.ts` (enda källan) —
|
||||
lint-/test-täckning finns (tests/order-flow.test.ts).
|
||||
|
||||
## Testing / Evidence
|
||||
- `tests/order-flow.test.ts`: available för aktiva steg, read_only för
|
||||
terminala (incl. okända statusar i fri-text-DB) — 3/3.
|
||||
- Full svit 1138+3 godkända; typecheck grön.
|
||||
|
||||
## Rollback
|
||||
Ta bort `advance_action`-fältet + ActionGate-wrappen — klienten faller
|
||||
tillbaka till tidigare rendering (flödet oförändrat).
|
||||
@@ -1,61 +0,0 @@
|
||||
# ADR-0002 — Kanonisk orderstatus: kodnivå-union + guardad DB-constraint
|
||||
|
||||
**Status:** Accepted
|
||||
**Date:** 2026-09-29
|
||||
**Owners:** 0pt (simon@siax.io)
|
||||
**Related requirements:** C3 (kanonisera orderstatus), DoD §17 (backup-städ), §33 (migreringsordning), §35 (restore-drill)
|
||||
**Related artifacts:** `lib/order-flow.ts` (`ORDER_STATUSES`, `OrderStatus`, `isKnownOrderStatus`, `nextOrderStatus`), `sql/015_order_status_check.sql`
|
||||
|
||||
## Context
|
||||
|
||||
`orders.status` är fri text (`sql/001_init.sql` line ~92: `status text NOT NULL DEFAULT 'draft'`).
|
||||
Flödet draft→quoted→in_production→review→accepted→delivered är känt i kod, men
|
||||
DB:n nekar inga andra värden — fri text har redan orsakat minst en missvisande
|
||||
"klar"-visning i ordkön (okänd status renderades som "done/klar" utan att
|
||||
ordern faktiskt levererats).
|
||||
|
||||
**Prod-harvest ej körbar i session** (2026-09-29): ingen `DATABASE_URL`/`POSTGRES_URL`
|
||||
för 0pt finns i Infisical (varken default-env eller `/0pt`-sökvägar — körningen
|
||||
injicerade 246 secrets utan order-DB-URL). Statusfördelningen i prod är därför
|
||||
okänd här; migreringen är guardad och manuell.
|
||||
|
||||
## Existing implementations
|
||||
|
||||
- `lib/order-flow.ts` — NEXT_STATUS-flödet, `resolveAdvanceAction`, `buildOrderInboxItem`.
|
||||
- `app/admin/page.tsx` + `app/api/orders/route.ts` konsumerar flödet.
|
||||
- `tests/order-flow.test.ts` behandlar `cancelled` som terminal read_only-status.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Kodnivå-union är SSOT:** `type OrderStatus` = de sex flödesstatusarna +
|
||||
`cancelled` (används i tests som terminal status — därmed med, trots utebliven
|
||||
harvest). `ORDER_STATUSES` är den utömmande listan; `isKnownOrderStatus()`
|
||||
klassar fri text fail-closed. NEXT_STATUS/resolveAdvanceAction/
|
||||
buildOrderInboxItem konsumerar unionen via `nextOrderStatus()` — okänd
|
||||
status ger alltid read_only / ingen inbox-post, aldrig påhittat nästa steg.
|
||||
2. **DB guardas — inte typ-migreras:** `sql/015_order_status_check.sql` lägger
|
||||
`CHECK (status IN (...)) NOT VALID` (fas A, kort lås, nekar vid dirt-data via
|
||||
DO-preflight) och `VALIDATE CONSTRAINT` i separat session (fas B, SHARE UPDATE
|
||||
EXCLUSIVE + `lock_timeout='5s'`). KÖRS EJ mot prod i sessionen — Simon kör
|
||||
efter harvest-rapport och backup (`pg_dump -t orders` före fas A).
|
||||
|
||||
## Alternativ avvisade
|
||||
|
||||
- **Fortsatt fri text** — redan orsakat missvisande "klar"; ingen möjlighet att
|
||||
fela tidigt vid skrivning.
|
||||
- **Omedelbar NOT VALID utan harvest** — risk för prod-block: NOT VALID validerar
|
||||
inte befintliga rader, men VALIDATE-fasen (och varje ny UPDATE) krockar med
|
||||
okända statusar; utan känd statusfördelning är fas B en lotteri.
|
||||
- **Postgres `enum`-typ** — kräver typmigrering av kolumnen (ALTER TYPE-lås,
|
||||
ADD VALUE kan ej ske i transaktion i äldre PG), tyngre drift än en CHECK som
|
||||
kan utökas med en rad kod + en rullande migrering.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Ny status = en rad i `ORDER_STATUSES`/`NEXT_STATUS` + en uppföljningsmigrering
|
||||
som lägger till värdet i CHECK:en (drop+add NOT VALID, validate igen).
|
||||
- Rader med okänd status (om harvest hittar sådana) mappas i en EGEN, granskad
|
||||
migrering före fas A — preflighten nekar annars körning (fail-closed).
|
||||
- SQL-listan och kodlistan är dubbelbokning; testen i
|
||||
`tests/order-flow.test.ts` låser att alla `ORDER_STATUSES` har definierat
|
||||
beteende (nästa steg eller read_only).
|
||||
@@ -27,15 +27,15 @@
|
||||
|
||||
---
|
||||
|
||||
## B-2 ✅ LÖST 2026-09-30 — Coolify-app provisionerad, 0pt.app kanonisk prod
|
||||
## B-2 🔴 — Ingen Coolify-app provisionerad, inget Infisical-projekt
|
||||
|
||||
| Fält | Innehåll |
|
||||
|---|---|
|
||||
| **Vad blockerar** | *(Inget — löst.)* Tidigare: `cd.yml` saknade provisionerad Coolify-app (BACKLOG P1-5). Den rapporten var **falsk blocker**: den testade `0pt.siax.io` (fel domän) — 0pt.app är och var den kanoniska prod-ytan (`siax.config.json`: `"domain": "0pt.app"`). |
|
||||
| **Hur den löstes** | Coolify-app provisionerad + deployad via `cd.yml` (`COOLIFY_APP_ID` via repo-vars). Live-verifierat 2026-09-30: `GET https://0pt.app/api/health` → 200 (`db: ok`), `GET /admin` → 200, `GET /api/orders` → 401 fail-closed (`OPT_UNAUTHENTICATED`). main `e7d5ee3` är deployad. |
|
||||
| **Vem beslutar** | — |
|
||||
| **Nuvarande status** | **LÖST 2026-09-30.** 0pt.app är kanonisk prod-yta (verifierad). Eventuellt `0pt.siax.io`-alias är en separat DNS-fråga (ej blockerande; domänen svarar i dagsläget ej). |
|
||||
| **Bevis** | Live-prober 2026-09-30 (health 200 db:ok, /admin 200, /api/orders 401); `siax.config.json` domain `0pt.app`; `.gitea/workflows/cd.yml` deploy-väg; main `e7d5ee3` (PR #134). |
|
||||
| **Vad blockerar** | `.gitea/workflows/cd.yml` har fortfarande en literal platshållare: `COOLIFY_APP_ID: "TODO-no-coolify-app-provisioned-yet"`. Jobbet är medvetet guardat att lyckas grönt utan att faktiskt deploya (`exit 0` + varning om token/UUID saknas). `siax.repo.json`/`siax.config.json` saknar Infisical-referens. Detta matchar repots egna `docs/compliance/BACKLOG.md` (P1-5, P1-6) och `GOLDEN-STANDARD-REPORT.md` (D4 ❌, C8 ❌, D7 ➖). |
|
||||
| **Vad krävs för att lyfta den** | Skapa appen i `cloud.siax.io` (Coolify), sätt `COOLIFY_APP_ID` i `cd.yml` och `COOLIFY_TOKEN` som Gitea-repo-secret. Skapa ett Infisical-projekt `0pt` med env-mappning och migrera bort från Vercel-env i takt med cutover. |
|
||||
| **Vem beslutar** | Ingen produktbeslutsfråga i sig — operativt arbete som kräver admin-access till kontrollplanet (`cloud.siax.io` / `vault.siax.io`). |
|
||||
| **Nuvarande status** | Fortfarande öppen. Verifierad färsk denna session: `cd.yml` bär fortfarande TODO-platshållaren på nuvarande `main`-HEAD. Kontrollerat om ett parallellt P0-1-uppdrag i samma arbetsflöde redan hunnit provisionera en app/projekt — inget sådant syns i repots egna deploy-artefakter vid tidpunkten för denna verifiering. Denna session saknar `SIAX_TOKEN`/inloggning mot `cloud.siax.io`/Infisical, så ett levande skick bortom repots egna signaler kunde inte kontrolleras direkt — endast repo-interna bevis nedan är verifierade. |
|
||||
| **Bevis** | `.gitea/workflows/cd.yml` rad 25 (denna checkout); `docs/compliance/BACKLOG.md` P1-5/P1-6; `docs/compliance/GOLDEN-STANDARD-REPORT.md` D4/D7/C8. |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,74 +1,27 @@
|
||||
# EVIDENCE — FAS 8 · /api/health + dependencies
|
||||
|
||||
> Live-prober + källanalys **2026-09-30** (VERIFIERAT mot prod). Ersätter den
|
||||
> gamla Vercel-mätningen (2026-08-10) — 0pt.app är inte längre på Vercel.
|
||||
> Live-prober + källanalys 2026-08-10 (VERIFIERAT).
|
||||
|
||||
## Prod-topologi (Coolify, inte Vercel)
|
||||
|
||||
`0pt.app` = kanonisk prod via **Coolify på cloud.siax.io**, deployad av
|
||||
`.gitea/workflows/cd.yml` vid varje merge till `main` (repo-secret
|
||||
`COOLIFY_TOKEN`, repo-variable `COOLIFY_APP_ID` — riktig UUID, guarden
|
||||
passerar; se `docs/architecture/decisions/0001-deploy-target-coolify-not-vercel.md`).
|
||||
Inga Vercel-referenser är längre aktuella för prod.
|
||||
|
||||
## Live (0pt.app, prod — mätt 2026-09-30 08:0x UTC)
|
||||
## Live (0pt.app, prod-instansen — Vercel)
|
||||
|
||||
```
|
||||
GET https://0pt.app/api/health -> 200
|
||||
{"ok":false,"service":"0pt-web","db":"ok","queue":"not_configured",
|
||||
"engine":"error","stripe":"not_configured",
|
||||
"detail":{"engine":"This operation was aborted"},
|
||||
"ts":"2026-09-30T08:05:32.935Z"}
|
||||
|
||||
GET https://0pt.app/admin -> 200
|
||||
GET https://0pt.app/api/orders -> 401 fail-closed (OPT_UNAUTHENTICATED)
|
||||
GET https://0pt.app/api/health -> 200
|
||||
{"ok":true,"service":"0pt-web","db":"not_configured","queue":"not_configured","ts":"2026-08-10T01:58:31.043Z"}
|
||||
GET https://0pt.app/api/0pt -> 200 (anonymt) [lucka S1 bekräftad live]
|
||||
GET https://0pt.app/api/orders -> 200 (anonymt) [lucka S3 bekräftad live]
|
||||
```
|
||||
|
||||
Hälsokontraktet ljuger inte: `ok:false` speglar en verkligt degraderad
|
||||
beroendekoll (`engine:error`), db är på riktigt `ok` och authen fail-close:ar.
|
||||
Vad som återstår är att åtgärda orsaken, inte att måla grönt (se nedan).
|
||||
## Källkod (app/api/health/route.ts)
|
||||
|
||||
## Engine-kollens rotorsak — konfig, inte kod
|
||||
Health-svar innehåller `db` + `queue`-fält som reflekterar `DATABASE_URL` /
|
||||
`REDIS_URL`-närvaro — beroendestatus rapporteras, men `ok` är alltid `true`
|
||||
(liveness, ej readiness). Gap D2: en instans utan databas är "grön".
|
||||
|
||||
- `lib/health-checks.ts#checkEngine` gör en riktig HTTP-roundtrip mot
|
||||
`${ENGINE_URL}/health` (AbortController, 2 s timeout). Kontraktet:
|
||||
`not_configured` när `ENGINE_URL` ej är satt; `error` när den ÄR satt men
|
||||
misslyckas (t.ex. abort/non-2xx); `ok` först vid lyckad roundtrip.
|
||||
- Prod-symptomet `"This operation was aborted"` = timeout-aborten mot en
|
||||
**oprovisionerad host**: `ENGINE_URL` pekar på `http://0pt-engine:8000`,
|
||||
ett namn utan DNS-post i flottan (mätt 2026-09-25 och åter 09-30; ingen
|
||||
sådan container på server5–11).
|
||||
- **Infisical /0pt (prod): 0 nycklar matcher `ENGINE_URL`** (räknat
|
||||
2026-09-30 via `siax-secrets export --env prod --path /0pt`). Värdet sitter
|
||||
alltså i **Coolify-appens egen env**, inte i valvet.
|
||||
- Beslut per konvention: kollen är redan ärlig och icke-blockerande när
|
||||
motorn ej provisionerats — `ENGINE_URL` borttaget ⇒ `engine:"not_configured"`
|
||||
och `ok:true`, utan kodändring. Sålänge URL:en är satt men död är
|
||||
`error` den korrekta, ärliga statusen. Regressionstest finns i
|
||||
`tests/lib/health-checks.test.ts` (unset → not_configured; satt+abort →
|
||||
error med abort-meddelandet i `detail`).
|
||||
- Åtgärd (konfig, Simon-gate): ta bort `ENGINE_URL` (och ev. oanvänd
|
||||
`INTERNAL_TOKEN` för motorn) från Coolify-appens env → omdeploy. Tills
|
||||
FastAPI-motorn (`services/api`) faktiskt provisioneras ska ingen
|
||||
`ENGINE_URL` finnas i prod.
|
||||
## Bygge (next build, lokal — samma som CI)
|
||||
|
||||
## Källkod (app/api/health/route.ts + lib/health-checks.ts)
|
||||
|
||||
- Routen är **liveness**: alltid 200 så länge processen svarar. Bodyns `ok`
|
||||
är den ärliga signalen: `false` när en konfigurerad dependency fail:ar.
|
||||
- Per-dependency: `ok` | `error` (med `detail`) | `not_configured` |
|
||||
`not_integrated` (endast `queue`/REDIS_URL — ingen Redis-klient wired i
|
||||
repot; aldrig fabricerad `ok`).
|
||||
- Readiness (`/api/ready`) fail-close:ar på `db != ok` och på varje
|
||||
`error` — konfigurerad-men-död räknas inte som "valfri".
|
||||
|
||||
## Simon-gates (ej agent-verifierbara)
|
||||
|
||||
Inloggad journey (admin-portalens E2E) och kanarie-identitet (beställd
|
||||
kanarieorder spårad end-to-end) kräver Simons inloggning och stäms separat —
|
||||
omfattas ej av denna mätning.
|
||||
|
||||
## Historik
|
||||
|
||||
2026-08-10 mättes 0pt.app på Vercel (`{"ok":true,"db":"not_configured",...}`
|
||||
hardcoded-grönt — BACKLOG P0-3, sedan fixat). Den deploymenten är inaktuell; alla prod-utsagor i denna fil gäller Coolify-cutovern.
|
||||
```
|
||||
ƒ Proxy (Middleware) <- Next 16 bygger middleware.ts korrekt i detta träd
|
||||
```
|
||||
→ S1-hypotesen "middlewaren plockas inte upp av Next 16" försvagas; mer
|
||||
sannolik orsak är Vercel-projektets build-output eller deploymentsversion
|
||||
(ej verifierat). Se BACKLOG P0-1.
|
||||
|
||||
@@ -1,36 +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` | `0PT` | befintlig `siax.repo.json` (VERSALER per REPO-08) |
|
||||
| `codeowners` | `["@sax3l"]` | befintlig `siax.repo.json` |
|
||||
| `category` | `platform` | befintlig `siax.repo.json` |
|
||||
| `subcategory` | `data-os` | befintlig `siax.repo.json` |
|
||||
| `operationalState` | `running` | befintlig `siax.repo.json` |
|
||||
| `domains` | `2 st` | befintlig `siax.repo.json` |
|
||||
| `children` | `4 st` | befintlig `siax.repo.json` |
|
||||
| `packageName` | `@siax/0pt` | befintlig `siax.repo.json` |
|
||||
|
||||
## Måste verifieras av människa
|
||||
|
||||
- [ ] Rätta den BEFINTLIGA `siax.repo.json` — den validerar inte mot schemat (REPO-03/04) och scaffolden skriver inte över den (AR-1): (roten): obligatoriskt fält saknas: tier; (roten): obligatoriskt fält saknas: runtime; (roten): obligatoriskt fält saknas: canonical; (roten): obligatoriskt fält saknas: parentRepo; (roten): obligatoriskt fält saknas: capabilities; (roten): obligatoriskt fält saknas: surfaces; (roten): obligatoriskt fält saknas: identity; (roten): obligatoriskt fält saknas: persistence; (roten): obligatoriskt fält saknas: deployment; (roten): obligatoriskt fält saknas: observability; (roten): obligatoriskt fält saknas: reliability; (roten): obligatoriskt fält saknas: engines; (roten): obligatoriskt fält saknas: licenses; (roten): obligatoriskt fält saknas: productionEvidence; /standardVersion: måste vara "3.0", är "2.0"; (roten): okänt fält "codeowners" (additionalProperties: false); (roten): obligatoriskt fält saknas: canonical
|
||||
|
||||
## Kontroller som scaffolden AVSIKTLIGT lämnar röda
|
||||
|
||||
Inga — de tre fall den här sektionen annars varnar för (`appId` satt till `null`, ett genererat kontraktsskelett, ett nyskrivet `backup-restore.md` utan datum) gäller inte i denna körning. Se "Måste verifieras" ovan för vad som faktiskt återstår.
|
||||
|
||||
|
||||
---
|
||||
|
||||
_Genererad av `siax-scaffold` (siax-standard). Varje `TODO:` i filen måste
|
||||
fyllas i av en människa. Samlad lista: `docs/compliance/SCAFFOLD-TODO.md`._
|
||||
@@ -1,81 +0,0 @@
|
||||
# Document workbench — upload → structure → validated export
|
||||
|
||||
The customer-facing slice that turns an uploaded file into evidence-bound data.
|
||||
|
||||
## Routes
|
||||
|
||||
| Route | Purpose | Fails closed with |
|
||||
|---|---|---|
|
||||
| `POST /api/0pt/documents/upload` | multipart upload of the original bytes into DOC0, recorded in a durable attempt journal before dispatch | `503 DOC0_NOT_CONFIGURED`, `503 PROJECT_AUTHORIZATION_NOT_CONFIGURED`, `503 UPLOAD_JOURNAL_NOT_CONFIGURED` |
|
||||
| `POST /api/0pt/documents/structure` | re-reads the DOC0 segment index, calls INF0, validates every field against an exact source span, reserves/settles credits | `503 WORKBENCH_NOT_CONFIGURED`, `503 MODEL_POLICY_NOT_CONFIGURED`, `503 CREDITS_NOT_CONFIGURED`, `402 INSUFFICIENT_CREDITS` |
|
||||
| `GET /api/0pt/documents/models` | the server-approved model routes and limits | `503 MODEL_POLICY_NOT_CONFIGURED` |
|
||||
| `GET /api/0pt/credits/balance` | tenant credit balance | `503 CREDITS_NOT_CONFIGURED` |
|
||||
| `GET /api/0pt/credits/packs` | sellable packs from the server-owned price book | `503 PRICE_BOOK_NOT_CONFIGURED` |
|
||||
| `POST /api/0pt/credits/checkout` | Stripe Checkout session + server price snapshot | `503 PRICE_BOOK_NOT_CONFIGURED`, `503 STRIPE_NOT_CONFIGURED` |
|
||||
| `POST /api/webhooks/stripe` | re-reads the session and payment intent, then grants credits idempotently | non-2xx until processed |
|
||||
|
||||
UI: `/portal/dokument` (upload, structure, review, download) and `/portal/krediter`
|
||||
(balance, packs, checkout). The portal signs in through Zitadel OIDC
|
||||
(`/api/auth/login` → `/api/auth/callback`); the resulting signed session cookie
|
||||
is accepted by middleware as a verified principal (Bearer still wins).
|
||||
|
||||
## Invariants
|
||||
|
||||
1. **Tenant and actor come only from middleware's verified headers.** A customer
|
||||
route never trusts `tenant_id`/`actor_id` from the body.
|
||||
2. **Project access is checked by OpenFGA** (`@siax/access`), the same primitive
|
||||
DOC0 uses. Until the central relationship store is deployed, an explicit
|
||||
server-owned grant list (`OPT_PROJECT_GRANTS`) can be used instead.
|
||||
Unconfigured or unavailable means *denied*, never allowed.
|
||||
3. **The model never sees unverified text.** `Doc0SourceClient` verifies
|
||||
version, tenant, checksum, segment hashes and that the index was not
|
||||
truncated before anything is sent to INF0.
|
||||
4. **Every returned value must point at an exact span** in the source; otherwise
|
||||
the result is `needs_review` and nothing is exported.
|
||||
5. **Credits are reserved before the model runs and settled to measured usage.**
|
||||
An unknown model outcome keeps the reservation for reconciliation instead of
|
||||
releasing it.
|
||||
6. **No price is ever read from the client.** The price book is a versioned,
|
||||
server-owned JSON document (`OPT_CREDIT_PRICE_BOOK`).
|
||||
7. **Trial credits are a grant, not a payment.** `OPT_TRIAL_CREDITS=N` grants N
|
||||
credits once per tenant (`kind='grant'`, idempotency key `trial:<tenant>`),
|
||||
so the ledger is fully exercised before any real purchase. It is never read
|
||||
from a client and never looks like a Stripe payment.
|
||||
8. **Pilot mode is explicit.** `OPT_CREDITS_MODE=off` skips reserve/settle and
|
||||
reports `credits: null`. It is not a silent fallback and it does not enable
|
||||
purchases; unset/`on` requires the price book and the ledger.
|
||||
|
||||
## Reusable packages
|
||||
|
||||
- `packages/siax-access` (`@siax/access`) — framework-neutral OpenFGA
|
||||
relationship checks and a fail-closed `isProjectAccessAllowed`. Intended for
|
||||
DOC0, N0D and every other SIAX product instead of per-repo copies of
|
||||
`project-relationships.ts`.
|
||||
- `src/document-workbench/*` — upload coordination, DOC0 source reading, INF0
|
||||
admission, structured-output validation, export and credit ledger. These
|
||||
modules have no Next.js imports and can be lifted into a published package
|
||||
unchanged.
|
||||
|
||||
## Which AI path is used
|
||||
|
||||
Order:
|
||||
1. **Decision server model** (`DECISION_OLLAMA_URL` + `DECISION_OLLAMA_MODEL`) —
|
||||
the self-hosted Ollama on server-decision-01, used while the external model
|
||||
API is on hold. Internal only, no provider key, no per-token cost.
|
||||
2. **Live LiteLLM gateway** (`INF0_GATEWAY_LITELLM_KEY`).
|
||||
3. Native `INF0_URL` surface.
|
||||
|
||||
Admission — tenant/project scope, model allow-list, data class,
|
||||
external-transfer policy and token limits — runs locally in every path before
|
||||
the request leaves the process. Evidence spans are computed deterministically
|
||||
from the returned values when a small local model omits offsets: a value must
|
||||
occur exactly once in the source, otherwise the result is `needs_review`.
|
||||
|
||||
## What is still deliberately not claimed
|
||||
|
||||
- The output is `mechanically_validated`, not proven complete or semantically
|
||||
correct. OCR quality and coverage require review.
|
||||
- Refunds and chargebacks do not automatically revoke credits; no such handler
|
||||
is wired.
|
||||
- Format breadth is limited by DOC0's parser. A file DOC0 cannot parse is
|
||||
reported, never guessed.
|
||||
@@ -1,87 +0,0 @@
|
||||
# 0pt — produktionsberedskap
|
||||
|
||||
> Standardiserad gap-analys enligt SIAX Master Definition of Done.
|
||||
> Dokumentet är evidens, inte ett leveransgodkännande. Endast `PRODUCTION_READY` får kallas klart.
|
||||
|
||||
## Identitet
|
||||
|
||||
- Repo: `https://git.siax.io/admin/0pt.git`
|
||||
- Manifest: `siax.repo.v3.json` — `0PT`, operationalState `running`
|
||||
- Default branch: `main`
|
||||
- Bedömd nivå: **LIVE_VERIFIED** (manifestets DoD-anspråk: ja)
|
||||
- UI: ja — app, public
|
||||
- CI-arbetsflöden: 9
|
||||
|
||||
## Git- och arbetsyteläge
|
||||
|
||||
- Aktuell branch: `main` — ahead 0 / behind 0
|
||||
- Ocommittade filer: 0 · otrackade: 0
|
||||
- Worktrees: 1
|
||||
- Lokala grenar: 1 · remote: 17
|
||||
|
||||
## Livebevis (observerat 2026-11-10T03:05:09)
|
||||
|
||||
| Värd | HTTP | Klass | Titel | SIAX-tokens |
|
||||
|---|---|---|---|---|
|
||||
| `0pt.app` | 200 | public-ok | 0pt — your data | nej |
|
||||
| `api.0pt.app` | 200 | public-ok | 0pt — your data | nej |
|
||||
|
||||
401/403 är förväntat för autentiserade ytor; det är inte ett produktionsfel.
|
||||
0 betyder DNS/TLS/anslutning misslyckades och är alltid ett gap. SIAX-tokens avser markörer i serverad HTML; ett SPA-bygge kan bära dem i CSS/JS och då är kolumnen indikativ, inte bevis.
|
||||
|
||||
## Kod- och UI-signaler
|
||||
|
||||
- Trackade filer: 954
|
||||
- Testfiler: 178 · E2E: 0 · Playwright: False · Cypress: False
|
||||
- API-kontrakt: contracts/openapi.yaml
|
||||
- Migrationer: 0 · Health-referenser: 69
|
||||
- `@siax/ui`/tokens: True · a11y-verktyg: False · design-conformance: True
|
||||
- UI-tillståndsfiler: app/error.tsx, app/not-found.tsx
|
||||
- TODO/FIXME: 10
|
||||
- Exempel:
|
||||
- `.gitea/CODEOWNERS:10:# TODO: lägg till migrationskatalogen när den finns, t.ex.`
|
||||
- `.gitea/workflows/cd.yml:15:# The placeholder guard below remains as a fail-closed guard, not as a TODO.`
|
||||
- `.gitea/workflows/cd.yml:34: COOLIFY_APP_ID: ${{ vars.COOLIFY_APP_ID || 'TODO-no-coolify-app-provisioned-yet' }}`
|
||||
- `.gitea/workflows/cd.yml:91: if [ "$COOLIFY_APP_ID" = "TODO-no-coolify-app-provisioned-yet" ]; then`
|
||||
- `README.md:85: `TODO-no-coolify-app-provisioned-yet` literal. Both guard conditions in`
|
||||
|
||||
## Gap mot PRODUCTION_READY
|
||||
|
||||
- `NO_BACKUP_POLICY`
|
||||
|
||||
## Prioriterad backlogg
|
||||
|
||||
| Prio | Åtgärd | Konkret nästa steg |
|
||||
|---|---|---|
|
||||
| P1 | Backup | Definiera frekvens, retention, mål och kryptering i `siax.backup`. |
|
||||
| P1 | E2E i webbläsare | Lägg Playwright-flöde för inloggning och kärnflöde mot riktig miljö. |
|
||||
| P1 | Tillgänglighetsgrind | Aktivera eslint-plugin-jsx-a11y/axe och en blockerande WCAG 2.2-kontroll. |
|
||||
| P2 | Statusdokument | Lägg `docs/STATUS.md` med nivå, bevis, kända gap och nästa steg. |
|
||||
| P2 | Teknisk skuld | Prioritera bland 10 TODO/FIXME-markeringar; stäng eller gör dem spårbara som issues. |
|
||||
|
||||
## Checklista före PRODUCTION_READY
|
||||
|
||||
- [ ] Canonical owner och produktgräns dokumenterad
|
||||
- [ ] Versionerat API-/eventkontrakt med drift-check
|
||||
- [ ] Tenant-isolering verifierad med negativt test
|
||||
- [ ] Observability: metrics, loggar, spårning och larm
|
||||
- [ ] Backup och verkligt återställningstest
|
||||
- [ ] Live-E2E med verklig konsument, inte mock
|
||||
- [ ] Deployad commit-SHA och build-ID utlästa ur runtime
|
||||
- [ ] UI/UX granskad mot DES1GN och WCAG 2.2 där UI finns
|
||||
|
||||
## Verifieringskommandon
|
||||
|
||||
```bash
|
||||
mise run check && mise run verify && mise run build
|
||||
siax-doctor design --repo . --fail-on=block
|
||||
curl -fsS https://<prod-host>/health && curl -fsS https://<prod-host>/ready
|
||||
```
|
||||
|
||||
## Standardreferenser
|
||||
|
||||
- `siax-standard/standard/MASTER-DEFINITION-OF-DONE.md`
|
||||
- `siax-standard/standard/SIAX-REPO-OPERATIONS-CONTRACT.md`
|
||||
- `siax-standard/standard/registry/REUSE_FIRST_POLICY.md`
|
||||
|
||||
_Genererad 2026-11-10T03:03:34 från git, manifest, kodsignaler och live-prober. Omgenereras av `scripts/estate-production-audit.py`._
|
||||
@@ -103,5 +103,3 @@ psql -d opt < backup # eller: pg_restore -d opt opt-YYYY-MM-DD.dump
|
||||
1. Provisionera tillfällig Postgres (pgvector:pg16).
|
||||
2. `pg_restore` senaste dump. 3. Sätt `DATABASE_URL` i dev-instans.
|
||||
4. Verifiera orderflöde + en källfråga. 5. Logga resultatet i `docs/compliance/EVIDENCE/`.
|
||||
|
||||
**Senast bevisad restore: 2026-09-03** — P014-restoreövningen i docs/runbook/backup-restore.md avsnitt P014 (exekverad 2026-09-03): verklig backup -> isolerad engångstarget (pgvector/pgvector:pg16) -> restore, körd mot faktisk infrastruktur, inga persistenta artefakter kvarlämnade.
|
||||
|
||||
+51
-72
@@ -1,84 +1,63 @@
|
||||
# Runbook: Deploy — 0pt
|
||||
|
||||
> Status 2026-11-02: **live on the SIAX fleet (Coolify)** at `https://0pt.app`.
|
||||
> The automatic chain and the manual path are both verified: a signed image is
|
||||
> attested, Coolify is called, the container restarts on the new commit, and
|
||||
> `/api/version` reports it.
|
||||
> Mål: sätta 0pt.app på SIAX-flottan (Coolify) och avveckla Vercel i ordning.
|
||||
> Status 2026-08-10: `siax.config.json` deklarerar `target: coolify`; ingen
|
||||
> Coolify-app provisionerad; live-instansen körs fortfarande på Vercel.
|
||||
|
||||
## Pipeline (automatic)
|
||||
## 1. Förutsättningar (blockerare för cutover)
|
||||
|
||||
```
|
||||
git push main
|
||||
├─ ci.yml quality (typecheck, contrast, tests, build)
|
||||
│ integration (live OpenSearch + ClickHouse)
|
||||
│ security (Trivy, blocking)
|
||||
├─ security.yml push/PR/weekly scan
|
||||
├─ release.yml build + SBOM + blocking vuln scan + cosign attest + push
|
||||
│ → git.cloud.siax.io/sax3l/0pt:sha-<12>
|
||||
└─ cd.yml waits for THIS commit's attestation, verifies it against
|
||||
cosign.pub, then POSTs to Coolify
|
||||
prod-smoke.yml every 30 min: ready + db/stripe + running commit == main
|
||||
```
|
||||
- [ ] Coolify-app provisionerad i `cloud.siax.io` (build_pack: dockerfile,
|
||||
repo `git.siax.io/sax3l/0pt`, gren `main`).
|
||||
- [ ] `COOLIFY_APP_ID` (appens UUID) ifylld i `.gitea/workflows/cd.yml`.
|
||||
- [ ] `COOLIFY_TOKEN`-secret satt på repot (Gitea → Settings → Actions → Secrets).
|
||||
- [ ] Env-secrets inlagda i Coolify-appen från Infisical-projektet `0pt`
|
||||
(se backup/restore + incident runbooks).
|
||||
- [ ] DNS-cutover planerad: `0pt.app` → Coolify-appens ingress (eller Caddy).
|
||||
|
||||
- One run per ref (`concurrency`); `push` is main-only, PRs are covered by the
|
||||
`pull_request` event. Deploys have their own non-cancelling group so two
|
||||
runs never race the same app.
|
||||
- Dependency caches: pnpm store (Node jobs), npm (doc0/n0d), pip (0pt-motor).
|
||||
## 1b. Signerad-artefakt-grind (tillagd 2026-09-14, samma mönster som cl0ud/st0re/h0st)
|
||||
|
||||
## Manual deploy (proven)
|
||||
`.gitea/workflows/release.yml` (nytt) bygger, SBOM:ar (syft), signerar
|
||||
(cosign) och evidensbokför varje push till `main`, och pushar till
|
||||
`git.cloud.siax.io/sax3l/0pt:sha-<12>`. `cd.yml`s `deploy`-jobb har nu ett
|
||||
extra steg (efter guard-steget i punkt 1 ovan) som kräver att exakt denna
|
||||
commits avbildning finns i registret och att dess cosign-signatur
|
||||
verifierar (mot committad `cosign.pub`) innan Coolify överhuvudtaget
|
||||
anropas.
|
||||
|
||||
Trigger the same, signed path — do not POST to Coolify directly unless the
|
||||
pipeline itself is broken:
|
||||
Detta är byggt FÖRE Coolify-appen finns (se blockerarna i punkt 1) — så att
|
||||
grinden redan är på plats den dag appen provisioneras, i stället för att bli
|
||||
ett separat uppföljningsarbete. Samma ärliga begränsning som cl0ud/st0re/
|
||||
h0st: när appen väl provisioneras som `dockerfile` build pack (så som
|
||||
`siax.config.json` föreskriver) kör Coolify sin EGEN oberoende
|
||||
`docker build` från git-källan, inte den signerade avbildningen —
|
||||
`/api/v1/deploy` saknar digest-parameter helt. Sann digest-pinning skulle
|
||||
kräva att appen provisioneras som Coolifys separata `dockerimage`-resurstyp
|
||||
i stället, ett beslut som inte är fattat än. Se `.gitea/workflows/cd.yml`s
|
||||
"SIGNED-ARTIFACT GATE"-kommentar för den fullständiga skrivningen.
|
||||
|
||||
**Inte satt på `sax3l/0pt` ännu:** repo-secrets `REGISTRY_USER`,
|
||||
`REGISTRY_TOKEN`, `COSIGN_PRIVATE_KEY`, `COSIGN_PASSWORD`, `SIAX_CI_TOKEN` —
|
||||
`release.yml` fail-closed:ar på sin första körning tills dessa finns.
|
||||
|
||||
## 2. Deploy (när appen finns)
|
||||
|
||||
1. Push till `main` → `.gitea/workflows/cd.yml` POSTar till
|
||||
`https://cloud.siax.io/api/v1/deploy?uuid=$COOLIFY_APP_ID&force=false`,
|
||||
efter att den signerade-artefakt-grinden i punkt 1b gått grön.
|
||||
2. Följ run i Gitea Actions; verifiera att den slutar grön.
|
||||
3. Verifiera hälsa: `curl https://0pt.app/api/health` → `ok:true` och
|
||||
`db: configured` (när Postgres kopplats in).
|
||||
|
||||
## 3. Manuell redeploy (nöd)
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: token $GITEA_TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{"ref":"main"}' \
|
||||
https://git.siax.io/api/v1/repos/admin/0pt/actions/workflows/cd.yml/dispatches
|
||||
curl -fsS -X POST "https://cloud.siax.io/api/v1/deploy?uuid=<UUID>&force=true" \
|
||||
-H "Authorization: Bearer $COOLIFY_TOKEN"
|
||||
```
|
||||
|
||||
Emergency only (bypasses the attestation gate; still builds the branch head):
|
||||
## 4. Vercel-avveckling (EFFER att Coolify kör stabilt)
|
||||
|
||||
```bash
|
||||
curl -X POST -H "Authorization: Bearer $COOLIFY_API_TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{"uuid":"<COOLIFY_APP_ID>"}' https://cloud.siax.io/api/v1/deploy
|
||||
```
|
||||
|
||||
## Verify a deploy
|
||||
|
||||
```bash
|
||||
curl -s https://0pt.app/api/ready # {"ready":true,"db":"ok","stripe":"ok",...}
|
||||
curl -s https://0pt.app/api/health # liveness envelope
|
||||
curl -s https://0pt.app/api/version # {"commit":"<sha>"}
|
||||
```
|
||||
|
||||
`commit` must equal the current `main` SHA. `prod-smoke.yml` enforces exactly
|
||||
that every 30 minutes; a green deploy is never confused with a current service.
|
||||
|
||||
## Rollback
|
||||
|
||||
Coolify builds from the branch head, so a rollback is a normal revert:
|
||||
|
||||
```bash
|
||||
git revert --no-edit <bad-sha> && git push origin main
|
||||
```
|
||||
|
||||
That runs the same chain and deploys the reverted tree. Coolify's own
|
||||
"redeploy previous deployment" is the break-glass alternative.
|
||||
|
||||
## Configuration (names only — values live in Coolify/Infisical)
|
||||
|
||||
- Coolify app: `dockerfile` build pack, repo `git.siax.io/sax3l/0pt`, branch
|
||||
`main`, health check `/api/health`, domains `0pt.app` + `api.0pt.app`.
|
||||
- Repository variable: `COOLIFY_APP_ID`.
|
||||
- Repository secrets: `COOLIFY_TOKEN`, `REGISTRY_USER`, `REGISTRY_TOKEN`,
|
||||
`COSIGN_PRIVATE_KEY`, `COSIGN_PASSWORD`, `SIAX_CI_TOKEN`.
|
||||
- App env: `DATABASE_URL`, `STRIPE_SECRET_KEY`, `AUTH_SECRET`… see `.env.example`
|
||||
for the full, documented list (DOC0, INF0/decision Ollama, OpenFGA/project
|
||||
grants, model policy, credit price book, OIDC).
|
||||
|
||||
## Known limitation
|
||||
|
||||
Coolify rebuilds from source; `/api/v1/deploy` has no digest parameter, so the
|
||||
verified digest is recorded as provenance for the deploy rather than pinned as
|
||||
the running bytes. True digest pinning would require a Coolify `dockerimage`
|
||||
resource — an infrastructure decision, not a CI-YAML change.
|
||||
1. Verifiera att ingen verklig trafik/data ligger bakom (2026-08-10:
|
||||
`/api/health` visar `db/queue: not_configured` — marknads-/dev-läge).
|
||||
2. Peka DNS om till Coolify. 3. Behåll Vercel-projektet tills certifierad
|
||||
paritet (katalog, orderflöde, betalningar). 4. Avveckla först därefter.
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
# Legacy instance audit — 0pt (server5) and L0RE (server5) — 2026-11-07
|
||||
|
||||
Canonical runtimes: **0pt on server6** (Coolify app `shxd6lepxuxfsjsp0ath3z1g`,
|
||||
`0pt.app`) and **L0RE on server9** (`l0re.siax.io`). This document records the
|
||||
older instances on server5 and their disposition. It is not production
|
||||
documentation for either product.
|
||||
|
||||
## 1. 0pt legacy (server5)
|
||||
|
||||
| Item | Value |
|
||||
|---|---|
|
||||
| Containers | `0pt-api` (`0pt-api:c46ebbf`, created 2026-11-05), `0pt-web` (`:18080`) |
|
||||
| Database | `0pt-pg`, user/db `opt`, 11 MB |
|
||||
| Exposure | `0pt-web` only on `100.124.7.55:18080`; no DNS record, no reverse proxy |
|
||||
| Consumers | none found (`/etc/siax`, `/opt/siax`, site0 and L0RE deploy configs) |
|
||||
| Unique data | 32 canonical facts (30 GLEIF web observations + `body_type` YDL405 + `passmark.find_prime_numbers.v10`) |
|
||||
|
||||
**Data reconciliation:** all 32 facts were exported and re-imported through the
|
||||
canonical API (`POST /api/0pt/canonical/facts`) into the server6 deployment.
|
||||
Replay returned `duplicates: 32`, so the import is idempotent. Production now
|
||||
holds 34 facts (32 migrated + 2 verification observations) and 4 entities.
|
||||
|
||||
**Backup:** `server5:/var/backups/0pt-legacy/opt_legacy_20261107.dump.zst`
|
||||
(custom format, 32 KB) + offsite `server11:/home/backup/0pt/`.
|
||||
|
||||
**Action taken:** `docker update --restart=no` + `docker stop` for `0pt-api` and
|
||||
`0pt-web`. `0pt-pg` left running for forensics/rollback. `0pt.app` verified 200
|
||||
after the stop (served by server6).
|
||||
|
||||
**Full removal (requires owner decision):** snapshot/destroy `0pt-pg` volume
|
||||
after the retention window, remove the legacy compose project, revoke the old
|
||||
`INTERNAL_TOKEN` if it was ever stored on server5.
|
||||
|
||||
## 2. L0RE orphan (server5)
|
||||
|
||||
Documented separately in `admin/l0re` PR #485
|
||||
(`docs/runbook/l0re-orphan-decommission-20261107.md`): API stopped with
|
||||
`restart=no`, dump + restore proof (8 propositions/62 assertions), no unique
|
||||
legitimate data (pilot facts already re-projected to production). `l0re-pg` and
|
||||
`l0re-opensearch` remain for forensics.
|
||||
|
||||
## 3. Single-runtime rule
|
||||
|
||||
One primary runtime per logical service. A container image of a product running
|
||||
outside its registered Coolify app is a finding, not a fallback. Both server5
|
||||
instances were reachable only from the host, which is why the split survived
|
||||
until this audit.
|
||||
@@ -1,78 +0,0 @@
|
||||
# 0pt workload identity — målbild, nuläge och övergång
|
||||
|
||||
Status: **design klar, provisionering blockerad** (2026-11-07).
|
||||
Ägare: CL0UD (identitet) / 0pt (konsument).
|
||||
|
||||
## 1. Nuläge
|
||||
|
||||
0pt autentiserar maskin-till-maskin med en **delad hemlighet**:
|
||||
|
||||
- `X-Internal-Token` mot `INTERNAL_TOKEN` (samma värde i engine och edge).
|
||||
- Tenant-auktoritet kommer från serverkonfigurationen `INTERNAL_SERVICE_TENANTS`
|
||||
(se `src/auth/internal-service-tenant.ts`), aldrig från en klientheader.
|
||||
- Tom allowlist ⇒ ingen tenant-auktoritet ⇒ tenant-scopade skrivningar 403.
|
||||
|
||||
Det här är säkert men grovkornigt: en enda hemlighet representerar hela
|
||||
engine-processen, och varje ny konsument kräver en manuell allowlist-post.
|
||||
|
||||
## 2. Målbild (CL0UD workload identity)
|
||||
|
||||
CL0UD äger redan maskineriet:
|
||||
|
||||
- `POST /account/service-accounts` skapar en service account (identitet).
|
||||
- `POST /account/service-accounts/{id}/workload-token` mints en **kortlivad**
|
||||
(10 min default, 1 h max) workload-token vars `capabilities` är en delmängd av
|
||||
service accountens `platform.cl0ud_service_account_scopes.allowedCapabilities`.
|
||||
- `@siax/platform-core` `auth/workload.ts` är verifieringsadaptern; publika
|
||||
nycklar via JWKS.
|
||||
- `packages/capability-registry/src/workload-identities.ts` deklarerar
|
||||
arbetsbelastningsnamn och `aud:*`-audiences. Modulen är uttryckligen **inte**
|
||||
provisionerad och **inte** inkopplad i utfärdande eller verifiering än.
|
||||
|
||||
För 0pt innebär det:
|
||||
|
||||
| Egenskap | Idag | Mål |
|
||||
|---|---|---|
|
||||
| Credential | delad `INTERNAL_TOKEN` | CL0UD-workload-token, `aud:0pt`, 10 min |
|
||||
| Tenant | serverkonfigurerad allowlist | `tenant_id`-claim i verifierad token |
|
||||
| Capabilities | route-lista i middleware | `capabilities`-claim (t.ex. `0pt.canonical.write`) |
|
||||
| Rotation | manuell | automatisk (kortlivad token) |
|
||||
| Spårbarhet | delad hemlighet | per-arbetsbelastning (`0pt-engine`, `site0-pipeline`) |
|
||||
|
||||
## 3. Integrationsdesign (när provisionering är möjlig)
|
||||
|
||||
1. **Verifiering före route-logik.** Middleware accepterar
|
||||
`Authorization: Bearer <workload-token>` för `INTERNAL_SERVICE_ROUTES` om
|
||||
signaturen verifieras mot CL0UD JWKS, `aud` innehåller `0pt` och `exp` är
|
||||
giltig. Ingen klientheader får bidra till tenant.
|
||||
2. **Tenant från claim, inte från allowlist.** `tenant_id` i den verifierade
|
||||
tokenen sätts som `x-0pt-verified-tenant`; `INTERNAL_SERVICE_TENANTS`
|
||||
används endast för legacy `X-Internal-Token`.
|
||||
3. **Capabilities per route.** Route-metadata (`0pt.canonical.write`,
|
||||
`0pt.quality.run`) jämförs med tokenens `capabilities`. Saknad capability ⇒
|
||||
403, inte 401 (identiteten är giltig, behörigheten räcker inte).
|
||||
4. **Dual-accept under övergång.** Båda credentialtyperna accepteras tills
|
||||
engine och site0-pipeline mintar workload-tokens; därefter tas
|
||||
`X-Internal-Token` bort i en egen release med negativt test.
|
||||
5. **Negativa tester i samma svit som idag**
|
||||
(`tests/auth/internal-token-tenant-scope.test.ts`): fel `aud` ⇒ 401, utgången
|
||||
token ⇒ 401, tenant utanför claim ⇒ 403, saknad capability ⇒ 403.
|
||||
|
||||
## 4. Blockerare
|
||||
|
||||
- `/account/service-accounts` svarar **307 → /login** utan operator-session;
|
||||
ingen giltig `SIAX_TOKEN` finns i Infisical-miljön.
|
||||
- Zitadel admin-PAT (`/opt/siax-access/zitadel-admin-pat`) är invalid
|
||||
(AUTH-7fs1e), så nya machine users kan inte mintas via det flödet.
|
||||
- `workload-identities.ts` är deklaration-only: ingen identitet är
|
||||
`provisioned: true`.
|
||||
|
||||
Åtgärd kräver en operatörsinloggning i CL0UD-konsolen (eller en ny giltig
|
||||
admin-PAT) och är därför **EXTERNALLY_BLOCKED** från agentsidan.
|
||||
|
||||
## 5. Vad som inte ska göras
|
||||
|
||||
- Ingen egen JWT-signering i 0pt.
|
||||
- Ingen parallell identitetsplattform.
|
||||
- Ingen klientheader som bär tenant.
|
||||
- Ingen långlivad delad hemlighet som "tillfällig" lösning utan slutdatum.
|
||||
+14
-123
@@ -18,8 +18,6 @@
|
||||
// fabricated check; reporting "not_configured" would
|
||||
// hide that a value was provided. This is its own
|
||||
// honest state rather than either of those two.
|
||||
import net from "node:net";
|
||||
import tls from "node:tls";
|
||||
import { dbUrl, getSql } from "./db";
|
||||
import { getStripe } from "./stripe";
|
||||
import { hasEngine } from "./engine";
|
||||
@@ -137,96 +135,15 @@ export async function checkStripe(
|
||||
}
|
||||
|
||||
/**
|
||||
* Redis/queue reachability.
|
||||
*
|
||||
* This used to report `not_integrated` because no code opened REDIS_URL. The
|
||||
* readiness probe now performs a real round trip (AUTH when the URL carries a
|
||||
* password, then PING -> +PONG) using only `node:net`/`node:tls`, so a queue
|
||||
* that is configured but dead fails readiness instead of hiding behind
|
||||
* `not_integrated`. The probe is injectable for tests.
|
||||
* Redis/queue: presence-only, honestly. No queue client library is a
|
||||
* dependency of this package (grep-verified against package.json) and no
|
||||
* code path in this repo reads REDIS_URL to open a connection -- so there is
|
||||
* no real check to run. Reporting "ok" would fabricate a probe that doesn't
|
||||
* exist; this reports "not_integrated" instead of silently upgrading to a
|
||||
* pretend pass.
|
||||
*/
|
||||
export type QueueProbe = (redisUrl: string, timeoutMs: number) => Promise<void>;
|
||||
|
||||
export function redisPing(redisUrl: string, timeoutMs: number): Promise<void> {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(redisUrl);
|
||||
} catch {
|
||||
reject(new Error("Invalid REDIS_URL"));
|
||||
return;
|
||||
}
|
||||
if (url.protocol !== "redis:" && url.protocol !== "rediss:") {
|
||||
reject(new Error("Unsupported REDIS_URL scheme"));
|
||||
return;
|
||||
}
|
||||
const port = url.port ? Number(url.port) : 6379;
|
||||
if (!Number.isSafeInteger(port) || port <= 0 || port > 65535) {
|
||||
reject(new Error("Invalid REDIS_URL port"));
|
||||
return;
|
||||
}
|
||||
const socket =
|
||||
url.protocol === "rediss:"
|
||||
? tls.connect({ host: url.hostname, port, servername: url.hostname })
|
||||
: net.connect({ host: url.hostname, port });
|
||||
let settled = false;
|
||||
const done = (error?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
socket.destroy();
|
||||
if (error) reject(error);
|
||||
else resolve();
|
||||
};
|
||||
const timer = setTimeout(() => done(new Error("redis ping timed out")), timeoutMs);
|
||||
let buffer = "";
|
||||
socket.on("error", (error: Error) => done(error));
|
||||
socket.on("close", () => {
|
||||
if (!settled) done(new Error("redis connection closed before PONG"));
|
||||
});
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
buffer += chunk.toString("utf8");
|
||||
if (buffer.includes("+PONG")) {
|
||||
done();
|
||||
return;
|
||||
}
|
||||
if (buffer.startsWith("-")) {
|
||||
done(new Error(`redis error: ${buffer.trim()}`));
|
||||
return;
|
||||
}
|
||||
// AUTH succeeded (or was unnecessary) but PING has not answered yet.
|
||||
});
|
||||
socket.on("connect", () => {
|
||||
const password = url.password ? decodeURIComponent(url.password) : "";
|
||||
if (url.username && url.username !== "default" && !password) {
|
||||
done(new Error("redis username without password is not supported"));
|
||||
return;
|
||||
}
|
||||
// RESP arrays: correct for any password content, unlike inline commands.
|
||||
const encode = (parts: string[]): string =>
|
||||
`*${parts.length}\r\n${parts
|
||||
.map((part) => `$${Buffer.byteLength(part, "utf8")}\r\n${part}\r\n`)
|
||||
.join("")}`;
|
||||
const payload =
|
||||
(password ? encode(["AUTH", password]) : "") + encode(["PING"]);
|
||||
socket.write(payload);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function checkQueue(
|
||||
probe: QueueProbe = redisPing,
|
||||
timeoutMs: number = DEFAULT_TIMEOUT_MS,
|
||||
): Promise<DepResult> {
|
||||
const redisUrl = process.env.REDIS_URL;
|
||||
if (!redisUrl) return { status: "not_configured" };
|
||||
const start = Date.now();
|
||||
try {
|
||||
await withTimeout(probe(redisUrl, timeoutMs), timeoutMs + 250, "redis ping");
|
||||
return { status: "ok", latencyMs: Date.now() - start };
|
||||
} catch (err) {
|
||||
return { status: "error", detail: errMessage(err), latencyMs: Date.now() - start };
|
||||
}
|
||||
export function checkQueue(): DepResult {
|
||||
return { status: process.env.REDIS_URL ? "not_integrated" : "not_configured" };
|
||||
}
|
||||
|
||||
export interface DependencyResults {
|
||||
@@ -237,13 +154,8 @@ export interface DependencyResults {
|
||||
}
|
||||
|
||||
export async function checkAllDependencies(): Promise<DependencyResults> {
|
||||
const [db, engine, stripe, queue] = await Promise.all([
|
||||
checkDatabase(),
|
||||
checkEngine(),
|
||||
checkStripe(),
|
||||
checkQueue(),
|
||||
]);
|
||||
return { db, engine, stripe, queue };
|
||||
const [db, engine, stripe] = await Promise.all([checkDatabase(), checkEngine(), checkStripe()]);
|
||||
return { db, engine, stripe, queue: checkQueue() };
|
||||
}
|
||||
|
||||
/** True when any dependency that IS configured/integrated is broken. */
|
||||
@@ -253,31 +165,10 @@ export function hasDegradedDependency(deps: DependencyResults): boolean {
|
||||
|
||||
/**
|
||||
* Readiness (unlike liveness) treats "not configured" for the deps this app
|
||||
* cannot serve real traffic without as not-ready too. `db` is the only
|
||||
* dependency that is load-bearing merely by being absent -- engine/stripe/
|
||||
* queue are optional integrations the app is designed to run WITHOUT (see
|
||||
* .env.example), so "not_configured" for those stays ready.
|
||||
*
|
||||
* But "optional to run without" is not the same as "optional to run BROKEN".
|
||||
* A dependency in the "error" state was deliberately configured by an
|
||||
* operator AND then failed a live round trip -- somebody asked for it and it
|
||||
* is not answering. Readiness fails closed on that too.
|
||||
*
|
||||
* Measured 2026-09-25 on the production deployment (0pt.app / api.0pt.app),
|
||||
* which is exactly the hole this closes:
|
||||
*
|
||||
* GET /api/health -> HTTP 200 {"ok":false, ..., "engine":"error",
|
||||
* "detail":{"engine":"This operation was aborted"}}
|
||||
* GET /api/ready -> HTTP 200 {"ready":true, "db":"ok", "engine":"error"}
|
||||
*
|
||||
* ENGINE_URL pointed at `http://0pt-engine:8000`, a hostname with no DNS
|
||||
* record anywhere on the fleet (`getent hosts 0pt-engine` -> nothing; no such
|
||||
* container on server5-11). The data engine -- 0pt's whole product -- had
|
||||
* been absent for the container's entire 17.9 h uptime, and every signal
|
||||
* above it was green. `ok:false` in a 200 body is not a signal; nothing reads
|
||||
* bodies.
|
||||
* cannot serve real traffic without as not-ready too. Only `db` is load-bearing
|
||||
* today -- engine/stripe/queue are optional integrations the app is designed
|
||||
* to run without (see .env.example).
|
||||
*/
|
||||
export function isReady(deps: DependencyResults): boolean {
|
||||
if (deps.db.status !== "ok") return false;
|
||||
return !Object.values(deps).some((d) => d.status === "error");
|
||||
return deps.db.status === "ok";
|
||||
}
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
// DES1GN ADR D3 (§31): bulk-import dispatch-policy — ETT objekt, en sanning.
|
||||
//
|
||||
// Import-routen (/api/orders/import) är inline-exekvering med hårt tak. Rader
|
||||
// över maxRows är DES1GN D3:s signal för N0D-dispatch (job_type
|
||||
// 0pt.import_execute_job / capability 0pt.import_execute i n0d:s
|
||||
// JOB_TYPE_REGISTRY). TILLS descriptor-gaten släpper (N0D-worker
|
||||
// UNVERIFIED) svarar routen 413 med n0d_dispatch_required + hint — aldrig
|
||||
// tyst trunkering, aldrig tyst dispatch.
|
||||
export const IMPORT_DISPATCH_POLICY = {
|
||||
/** Inline-tak i import-routen (oförändrat beteendekontrakt, 0pt#53). */
|
||||
maxInlineRows: 500,
|
||||
/** N0D-dispatch-signal: rader över detta är ett N0D-jobb, inget HTTP-anrop. */
|
||||
maxRows: 5000,
|
||||
/** Byte-tak för hela CSV-kroppen (UTF-8). */
|
||||
maxBytes: 1_000_000,
|
||||
/** Format-allowlist — endast RFC 4180 CSV i dag. */
|
||||
allowedFormats: ["csv"] as readonly string[],
|
||||
} as const;
|
||||
|
||||
export type ImportDispatchPolicy = typeof IMPORT_DISPATCH_POLICY;
|
||||
|
||||
export type ImportDispatchVerdict =
|
||||
| { verdict: "inline" }
|
||||
| { verdict: "unsupported_format"; format: string }
|
||||
| { verdict: "byte_cap_exceeded"; bytes: number; maxBytes: number }
|
||||
| { verdict: "row_cap_exceeded"; rows: number; maxInlineRows: number }
|
||||
| { verdict: "dispatch_n0d"; rows: number; maxRows: number };
|
||||
|
||||
/** Ren funktion — inga I/O, fullt deterministisk, testad per kombination. */
|
||||
export function evaluateImportDispatch(
|
||||
input: { format: string; bytes: number; rows: number },
|
||||
policy: ImportDispatchPolicy = IMPORT_DISPATCH_POLICY,
|
||||
): ImportDispatchVerdict {
|
||||
if (!policy.allowedFormats.includes(input.format)) {
|
||||
return { verdict: "unsupported_format", format: input.format };
|
||||
}
|
||||
if (input.bytes > policy.maxBytes) {
|
||||
return { verdict: "byte_cap_exceeded", bytes: input.bytes, maxBytes: policy.maxBytes };
|
||||
}
|
||||
if (input.rows > policy.maxRows) {
|
||||
return { verdict: "dispatch_n0d", rows: input.rows, maxRows: policy.maxRows };
|
||||
}
|
||||
if (input.rows > policy.maxInlineRows) {
|
||||
return { verdict: "row_cap_exceeded", rows: input.rows, maxInlineRows: policy.maxInlineRows };
|
||||
}
|
||||
return { verdict: "inline" };
|
||||
}
|
||||
-151
@@ -1,151 +0,0 @@
|
||||
/**
|
||||
* Zitadel OIDC Authorization Code + PKCE for the 0pt portal.
|
||||
*
|
||||
* The portal previously had no way to obtain a verified principal: the
|
||||
* `/api/0pt/*` routes require a Bearer token, but the browser only had the
|
||||
* dev-only HMAC session cookie. This module implements the standard web login
|
||||
* so a real user can reach the document workspace.
|
||||
*
|
||||
* Secrets (client id/secret, AUTH_SECRET) are server-only env values.
|
||||
*/
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose';
|
||||
import { deriveTenantId, zitadelIssuer } from '@/src/auth/zitadel';
|
||||
|
||||
export const OIDC_STATE_COOKIE = '0pt_oidc';
|
||||
export const OIDC_SESSION_TTL_SECONDS = 60 * 60 * 24 * 7;
|
||||
|
||||
export interface OidcConfig {
|
||||
issuer: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
redirectUri: string;
|
||||
}
|
||||
|
||||
export function appBaseUrl(): string {
|
||||
const configured = process.env.NEXT_PUBLIC_APP_URL;
|
||||
if (configured && /^https?:\/\//.test(configured)) return configured.replace(/\/+$/, '');
|
||||
return 'http://localhost:3000';
|
||||
}
|
||||
|
||||
export function readOidcConfig(): OidcConfig | undefined {
|
||||
const issuer = (process.env.ZITADEL_ISSUER || zitadelIssuer()).replace(/\/+$/, '');
|
||||
const clientId = process.env.ZITADEL_OIDC_CLIENT_ID;
|
||||
const clientSecret = process.env.ZITADEL_OIDC_CLIENT_SECRET;
|
||||
if (!clientId || !clientSecret || !/^https:\/\//.test(issuer)) return undefined;
|
||||
return {
|
||||
issuer,
|
||||
clientId,
|
||||
clientSecret,
|
||||
redirectUri: `${appBaseUrl()}/api/auth/callback`,
|
||||
};
|
||||
}
|
||||
|
||||
function base64url(buffer: Buffer): string {
|
||||
return buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
export function createPkce(): { verifier: string; challenge: string } {
|
||||
const verifier = base64url(randomBytes(48));
|
||||
const challenge = base64url(createHash('sha256').update(verifier).digest());
|
||||
return { verifier, challenge };
|
||||
}
|
||||
|
||||
export function createOidcState(): { state: string; nonce: string } {
|
||||
return { state: base64url(randomBytes(24)), nonce: base64url(randomBytes(24)) };
|
||||
}
|
||||
|
||||
export function authorizeUrl(config: OidcConfig, state: string, nonce: string, challenge: string): string {
|
||||
const params = new URLSearchParams({
|
||||
client_id: config.clientId,
|
||||
redirect_uri: config.redirectUri,
|
||||
response_type: 'code',
|
||||
scope: 'openid profile email urn:zitadel:iam:user:resourceowner',
|
||||
state,
|
||||
nonce,
|
||||
code_challenge: challenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
return `${config.issuer}/oauth/v2/authorize?${params.toString()}`;
|
||||
}
|
||||
|
||||
interface TokenResponse {
|
||||
id_token?: unknown;
|
||||
access_token?: unknown;
|
||||
token_type?: unknown;
|
||||
}
|
||||
|
||||
export async function exchangeCode(
|
||||
config: OidcConfig,
|
||||
code: string,
|
||||
verifier: string,
|
||||
): Promise<{ idToken: string; accessToken?: string }> {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
redirect_uri: config.redirectUri,
|
||||
client_id: config.clientId,
|
||||
client_secret: config.clientSecret,
|
||||
code_verifier: verifier,
|
||||
});
|
||||
const response = await fetch(`${config.issuer}/oauth/v2/token`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body,
|
||||
cache: 'no-store',
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (!response.ok) throw new Error('token_exchange_failed');
|
||||
const data = (await response.json()) as TokenResponse;
|
||||
if (typeof data.id_token !== 'string' || !data.id_token) {
|
||||
throw new Error('token_missing_id_token');
|
||||
}
|
||||
return {
|
||||
idToken: data.id_token,
|
||||
...(typeof data.access_token === 'string' ? { accessToken: data.access_token } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
let jwks: ReturnType<typeof createRemoteJWKSet> | undefined;
|
||||
let jwksIssuer: string | undefined;
|
||||
|
||||
function keySet(issuer: string) {
|
||||
if (!jwks || jwksIssuer !== issuer) {
|
||||
jwks = createRemoteJWKSet(new URL(`${issuer}/oauth/v2/keys`));
|
||||
jwksIssuer = issuer;
|
||||
}
|
||||
return jwks;
|
||||
}
|
||||
|
||||
export interface VerifiedIdToken {
|
||||
sub: string;
|
||||
tenantId: string;
|
||||
email?: string;
|
||||
claims: JWTPayload;
|
||||
}
|
||||
|
||||
export async function verifyIdToken(
|
||||
config: OidcConfig,
|
||||
idToken: string,
|
||||
expectedNonce: string,
|
||||
accessToken?: string,
|
||||
): Promise<VerifiedIdToken> {
|
||||
const { payload } = await jwtVerify(idToken, keySet(config.issuer), {
|
||||
issuer: config.issuer,
|
||||
audience: config.clientId,
|
||||
});
|
||||
if (typeof payload.sub !== 'string' || !payload.sub) {
|
||||
throw new Error('id_token_missing_sub');
|
||||
}
|
||||
if (expectedNonce && payload.nonce !== expectedNonce) {
|
||||
throw new Error('id_token_nonce_mismatch');
|
||||
}
|
||||
const tenantId = deriveTenantId(payload);
|
||||
if (!tenantId) throw new Error('id_token_missing_tenant');
|
||||
return {
|
||||
sub: payload.sub,
|
||||
tenantId,
|
||||
...(typeof payload.email === 'string' ? { email: payload.email } : {}),
|
||||
claims: payload,
|
||||
};
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
import { createInboxItem, type InboxItem } from "@siax/contracts/inbox";
|
||||
import { resolveAction, type ResolvedAction } from "@siax/contracts/authz-ux";
|
||||
|
||||
/**
|
||||
* Kanonisk orderstatus (ADR-0002, C3 2026-09-29): kodnivå-union som är den
|
||||
* ENDA sanningskällan för vilka statusar som existerar. DB-kolumnen är fortfarande
|
||||
* `text` (sql/001_init.sql line ~92) men guardas av sql/015_order_status_check.sql
|
||||
* (CHECK ... NOT VALID + VALIDATE i två steg, körs EJ automatiskt mot prod).
|
||||
* 'cancelled' ingår: tests/order-flow.test.ts behandlar den som terminal status.
|
||||
*/
|
||||
export type OrderStatus =
|
||||
| "draft"
|
||||
| "quoted"
|
||||
| "in_production"
|
||||
| "review"
|
||||
| "accepted"
|
||||
| "delivered"
|
||||
| "cancelled";
|
||||
|
||||
/** Uttömmande, kanonisk lista — SQL-constrainten i sql/015 MÅSTE spegla denna. */
|
||||
export const ORDER_STATUSES = [
|
||||
"draft",
|
||||
"quoted",
|
||||
"in_production",
|
||||
"review",
|
||||
"accepted",
|
||||
"delivered",
|
||||
"cancelled",
|
||||
] as const satisfies readonly OrderStatus[];
|
||||
|
||||
/** Typ-vakt: fri text ur DB/payload klassas mot unionen (fail-closed mot read_only). */
|
||||
export function isKnownOrderStatus(status: string): status is OrderStatus {
|
||||
return (ORDER_STATUSES as readonly string[]).includes(status);
|
||||
}
|
||||
|
||||
/** Statusar som kan flyttas fram; delivered/cancelled är terminala. */
|
||||
type AdvanceableStatus = Exclude<OrderStatus, "delivered" | "cancelled">;
|
||||
|
||||
/** Kanoniskt flöde — servern äger resolutionen (ADR-0001), UI renderar. */
|
||||
export const NEXT_STATUS: Record<AdvanceableStatus, OrderStatus> = {
|
||||
draft: "quoted",
|
||||
quoted: "in_production",
|
||||
in_production: "review",
|
||||
review: "accepted",
|
||||
accepted: "delivered",
|
||||
};
|
||||
|
||||
/** Guardad nästa-status: okänd/terminal status → null (aldrig påhittat steg). */
|
||||
export function nextOrderStatus(status: string): OrderStatus | null {
|
||||
if (!isKnownOrderStatus(status)) return null;
|
||||
return NEXT_STATUS[status as AdvanceableStatus] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-renderad action-resolution för advance-steget (ADR-0001):
|
||||
* ägarskapenforces redan av requireOrderOwner på GET/PATCH; tillståndet
|
||||
* avgör read_only. Innan Session/roller finns i 0pt är permission alltid
|
||||
* granted för autentiserade ägare — hårdkoda aldrig denna resolve i klienten.
|
||||
* Okänd status (fri text ur DB innan sql/015-valideringen körts) → read_only.
|
||||
*/
|
||||
export function resolveAdvanceAction(status: string): ResolvedAction {
|
||||
if (nextOrderStatus(status)) {
|
||||
return resolveAction({ permission: "granted", entitlement: "active", approval: "not_required", readOnly: false });
|
||||
}
|
||||
return resolveAction({ permission: "granted", entitlement: "active", approval: "not_required", readOnly: true });
|
||||
}
|
||||
|
||||
/** Orderstatus som utgör en inkorgspost (våg 3.3: orders kö = inbox). */
|
||||
const INBOX_ELIGIBLE: Partial<Record<OrderStatus, { kind: "task" | "approval"; priority: "normal" | "high" }>> = {
|
||||
draft: { kind: "task", priority: "normal" },
|
||||
quoted: { kind: "task", priority: "normal" },
|
||||
in_production: { kind: "task", priority: "normal" },
|
||||
review: { kind: "approval", priority: "high" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Server-renderad inkorgspost (ADR-0001-mönstret): en order som väntar på
|
||||
* nästa steg projiceras på universal-inbox-konvolverna. Terminala statusar
|
||||
* (delivered/cancelled) och okända statusar ger ingen post — inboxen är
|
||||
* öppna arbetsobjekt.
|
||||
*/
|
||||
export function buildOrderInboxItem(order: {
|
||||
order_id: string;
|
||||
status: string;
|
||||
flow: string;
|
||||
total_ore?: number | null;
|
||||
}): InboxItem | null {
|
||||
const next = nextOrderStatus(order.status);
|
||||
const eligible = isKnownOrderStatus(order.status) ? INBOX_ELIGIBLE[order.status] : undefined;
|
||||
if (!eligible || !next) return null;
|
||||
return createInboxItem({
|
||||
id: `order:${order.order_id}`,
|
||||
kind: eligible.kind,
|
||||
tenantId: "0pt",
|
||||
subject: `Order ${order.order_id.slice(0, 8)} — ${order.status} → ${next}`,
|
||||
priority: eligible.priority,
|
||||
createdAt: new Date().toISOString(),
|
||||
source: { system: "0pt", channel: "order-queue" },
|
||||
entity: { type: "order", id: order.order_id },
|
||||
actions: [{ id: "advance", label: `→ ${next}` }],
|
||||
});
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
// Klient-adapter: kernel-transport (@siax/collaboration CollaborationTransport)
|
||||
// över 0pts host-API (/api/admin/order-notes). Admin-ytan pratar ALDRIG med
|
||||
// fetch direkt — allt går genom denna adapter, så offline-läge och
|
||||
// versionskonflikter hanteras på ETT ställe:
|
||||
// - offline: send() är ett medvetet NO-OP som kastar OfflineError — utkastet
|
||||
// behålls i UI:t och användaren får en varning. Ingen tyst förlust.
|
||||
// - 409: ConflictError med serverns aktuella version -> UI laddar om.
|
||||
// Presence går via kernelns upsertPresence (status offline/online per författare).
|
||||
import {
|
||||
nextLamportClock,
|
||||
upsertPresence,
|
||||
type CollaborationOperation,
|
||||
type CollaborationTransport,
|
||||
type PresenceState,
|
||||
} from "@siax/collaboration";
|
||||
|
||||
export interface OrderNoteDto {
|
||||
note_id: string;
|
||||
order_id: string;
|
||||
author_id: string;
|
||||
body: string;
|
||||
version: number;
|
||||
clock: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export class OfflineError extends Error {
|
||||
constructor() {
|
||||
super("Offline: note change was NOT sent — draft kept locally, nothing lost");
|
||||
this.name = "OfflineError";
|
||||
}
|
||||
}
|
||||
|
||||
export class ConflictError extends Error {
|
||||
constructor(
|
||||
public readonly noteId: string,
|
||||
public readonly currentVersion: number,
|
||||
) {
|
||||
super(`Note ${noteId} changed server-side (current version ${currentVersion})`);
|
||||
this.name = "ConflictError";
|
||||
}
|
||||
}
|
||||
|
||||
export class OrderNotesTransport implements CollaborationTransport<{ body: string }> {
|
||||
private listeners = new Set<(op: CollaborationOperation<{ body: string }>) => void>();
|
||||
private presenceListeners = new Set<(p: PresenceState) => void>();
|
||||
private presence = new Map<string, PresenceState>();
|
||||
private localClock = 0;
|
||||
private offline = false;
|
||||
|
||||
constructor(readonly actorId: string) {}
|
||||
|
||||
setOffline(offline: boolean): void {
|
||||
this.offline = offline;
|
||||
this.setPresence({ participantId: this.actorId, status: offline ? "offline" : "online" });
|
||||
}
|
||||
|
||||
isOffline(): boolean {
|
||||
return this.offline;
|
||||
}
|
||||
|
||||
getPresence(): PresenceState[] {
|
||||
return [...this.presence.values()];
|
||||
}
|
||||
|
||||
setPresence(presence: PresenceState): void {
|
||||
this.presence = upsertPresence(this.presence, presence);
|
||||
for (const l of this.presenceListeners) l(presence);
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
this.setOffline(false);
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
this.setOffline(true);
|
||||
}
|
||||
|
||||
onOperation(listener: (op: CollaborationOperation<{ body: string }>) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
onPresence(listener: (p: PresenceState) => void): () => void {
|
||||
this.presenceListeners.add(listener);
|
||||
return () => this.presenceListeners.delete(listener);
|
||||
}
|
||||
|
||||
/** Replay a server op into local listeners + advance the Lamport clock. */
|
||||
observeRemote(operation: CollaborationOperation<{ body: string }>): void {
|
||||
this.localClock = nextLamportClock(this.localClock, operation.clock);
|
||||
this.setPresence({
|
||||
participantId: operation.actorId,
|
||||
status: this.presence.get(operation.actorId)?.status ?? "online",
|
||||
});
|
||||
for (const l of this.listeners) l(operation);
|
||||
}
|
||||
|
||||
async send(operation: CollaborationOperation<{ body: string }>): Promise<void> {
|
||||
if (this.offline) throw new OfflineError();
|
||||
this.localClock = nextLamportClock(this.localClock, operation.clock);
|
||||
for (const l of this.listeners) l(operation);
|
||||
}
|
||||
}
|
||||
|
||||
export interface NotesApiResult {
|
||||
notes: OrderNoteDto[];
|
||||
/** Version per note — the optimistic-concurrency handle the UI PATCHes with. */
|
||||
versions: Map<string, number>;
|
||||
}
|
||||
|
||||
export class OrderNotesClient {
|
||||
readonly transport: OrderNotesTransport;
|
||||
|
||||
constructor(actorId: string) {
|
||||
this.transport = new OrderNotesTransport(actorId);
|
||||
}
|
||||
|
||||
async load(orderId: string): Promise<NotesApiResult> {
|
||||
const res = await fetch(`/api/admin/order-notes?order_id=${encodeURIComponent(orderId)}`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) throw new Error(`load failed: ${res.status}`);
|
||||
const body = (await res.json()) as { notes: OrderNoteDto[] };
|
||||
const versions = new Map<string, number>();
|
||||
for (const note of body.notes) {
|
||||
versions.set(note.note_id, note.version);
|
||||
this.transport.observeRemote({
|
||||
id: note.note_id,
|
||||
actorId: note.author_id,
|
||||
clock: note.clock,
|
||||
type: "note.upsert",
|
||||
payload: { body: note.body },
|
||||
});
|
||||
}
|
||||
return { notes: body.notes, versions };
|
||||
}
|
||||
|
||||
async add(orderId: string, body: string): Promise<OrderNoteDto> {
|
||||
const op: CollaborationOperation<{ body: string }> = {
|
||||
id: `local_${crypto.randomUUID()}`,
|
||||
actorId: this.transport.actorId,
|
||||
clock: 0,
|
||||
type: "note.create",
|
||||
payload: { body },
|
||||
};
|
||||
await this.transport.send(op);
|
||||
const res = await fetch("/api/admin/order-notes", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ order_id: orderId, body }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`add failed: ${res.status}`);
|
||||
return (await res.json()) as OrderNoteDto;
|
||||
}
|
||||
|
||||
async update(note: OrderNoteDto, body: string, expectedVersion: number): Promise<OrderNoteDto> {
|
||||
await this.transport.send({
|
||||
id: note.note_id,
|
||||
actorId: "self",
|
||||
clock: note.clock,
|
||||
type: "note.update",
|
||||
payload: { body },
|
||||
});
|
||||
const res = await fetch("/api/admin/order-notes", {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ note_id: note.note_id, body, version: expectedVersion }),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
const err = (await res.json()) as { current_version?: number };
|
||||
throw new ConflictError(note.note_id, err.current_version ?? 0);
|
||||
}
|
||||
if (!res.ok) throw new Error(`update failed: ${res.status}`);
|
||||
return (await res.json()) as OrderNoteDto;
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
// Order notes — SIAX collaboration-kernelns första produktkonsument (spår C).
|
||||
//
|
||||
// Server-authoritative store över 0pts data-lager (Postgres när DATABASE_URL
|
||||
// är satt, annars samma dokumenterade in-memory-fallback som orders-store).
|
||||
// Kernel-semantik (@siax/collaboration 0.3.0):
|
||||
// - varje note ÄR en CollaborationOperation (id/actorId/clock/type/payload)
|
||||
// - nya operationer får sin klocka via nextLamportClock (max lokal/observerad + 1)
|
||||
// - listning återställs deterministiskt via mergeOperationLog/compareOperations
|
||||
// (klocka -> actorId -> id), så två repliker listar i SAMMA ordning
|
||||
// - samtidighet: optimistisk version; stale skrivning kastar
|
||||
// NoteVersionConflictError -> routen svarar 409 (conflict behavior).
|
||||
import {
|
||||
mergeOperationLog,
|
||||
nextLamportClock,
|
||||
type CollaborationOperation,
|
||||
} from "@siax/collaboration";
|
||||
|
||||
import { getSqlForDurableStore } from "@/lib/db";
|
||||
|
||||
export interface OrderNote {
|
||||
note_id: string;
|
||||
order_id: string;
|
||||
tenant_id: string | null;
|
||||
author_id: string;
|
||||
body: string;
|
||||
version: number;
|
||||
clock: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export class NoteVersionConflictError extends Error {
|
||||
constructor(
|
||||
public readonly noteId: string,
|
||||
public readonly expectedVersion: number,
|
||||
public readonly currentVersion: number,
|
||||
) {
|
||||
super(
|
||||
`Note "${noteId}" was updated by someone else: expected version ${expectedVersion}, current is ${currentVersion}`,
|
||||
);
|
||||
this.name = "NoteVersionConflictError";
|
||||
}
|
||||
}
|
||||
|
||||
export class NoteNotFoundError extends Error {
|
||||
constructor(public readonly noteId: string) {
|
||||
super(`Note "${noteId}" does not exist`);
|
||||
this.name = "NoteNotFoundError";
|
||||
}
|
||||
}
|
||||
|
||||
export class OrderNotFoundError extends Error {
|
||||
constructor(public readonly orderId: string) {
|
||||
super(`Order "${orderId}" does not exist`);
|
||||
this.name = "OrderNotFoundError";
|
||||
}
|
||||
}
|
||||
|
||||
// Non-durable fallback used only until a database is provisioned (same
|
||||
// decision as lib/orders-store.ts — resolveStoreMode fails hard in production
|
||||
// without a URL, so this path cannot silently swallow production writes).
|
||||
const mem = new Map<string, OrderNote>();
|
||||
|
||||
/** Kernel-projection: a note row IS a collaboration operation. */
|
||||
function toOperation(note: OrderNote): CollaborationOperation<{ body: string }> {
|
||||
return {
|
||||
id: note.note_id,
|
||||
actorId: note.author_id,
|
||||
clock: note.clock,
|
||||
type: "note.upsert",
|
||||
payload: { body: note.body },
|
||||
};
|
||||
}
|
||||
|
||||
/** Deterministic snapshot: kernel merge wins, never insertion order. */
|
||||
function snapshot(notes: Iterable<OrderNote>): OrderNote[] {
|
||||
const log = mergeOperationLog([...notes].map(toOperation));
|
||||
const byId = new Map([...notes].map((n) => [n.note_id, n]));
|
||||
return log
|
||||
.map((op) => byId.get(op.id))
|
||||
.filter((n): n is OrderNote => Boolean(n));
|
||||
}
|
||||
|
||||
function rowToNote(row: Record<string, unknown>): OrderNote {
|
||||
return {
|
||||
note_id: String(row.note_id),
|
||||
order_id: String(row.order_id),
|
||||
tenant_id: row.tenant_id === null || row.tenant_id === undefined ? null : String(row.tenant_id),
|
||||
author_id: String(row.author_id),
|
||||
body: String(row.body),
|
||||
version: Number(row.version),
|
||||
clock: Number(row.clock),
|
||||
created_at: new Date(row.created_at as string).toISOString(),
|
||||
updated_at: new Date(row.updated_at as string).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
type NotesSql = NonNullable<ReturnType<typeof getSqlForDurableStore>>;
|
||||
|
||||
async function maxClock(sql: NotesSql, orderId: string): Promise<number> {
|
||||
const rows = await sql`
|
||||
SELECT COALESCE(MAX(clock), 0) AS max_clock FROM order_notes WHERE order_id = ${orderId}
|
||||
`;
|
||||
return Number(rows[0]?.max_clock ?? 0);
|
||||
}
|
||||
|
||||
export async function listNotes(orderId: string): Promise<OrderNote[]> {
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) {
|
||||
return snapshot(
|
||||
[...mem.values()].filter((n) => n.order_id === orderId),
|
||||
);
|
||||
}
|
||||
const rows = await sql`
|
||||
SELECT * FROM order_notes WHERE order_id = ${orderId}
|
||||
`;
|
||||
return snapshot(rows.map(rowToNote));
|
||||
}
|
||||
|
||||
export interface AddNoteInput {
|
||||
order_id: string;
|
||||
tenant_id: string | null;
|
||||
author_id: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export async function addNote(input: AddNoteInput): Promise<OrderNote> {
|
||||
const body = input.body.trim();
|
||||
if (!body) throw new TypeError("note body must be non-empty");
|
||||
const note: OrderNote = {
|
||||
note_id: `note_${crypto.randomUUID()}`,
|
||||
order_id: input.order_id,
|
||||
tenant_id: input.tenant_id,
|
||||
author_id: input.author_id,
|
||||
body,
|
||||
version: 1,
|
||||
// Kernel: Lamport-klockan = max(lokal, observerad) + 1.
|
||||
clock: 1,
|
||||
created_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
note.clock = nextLamportClock(await peekMaxClock(input.order_id));
|
||||
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) {
|
||||
mem.set(note.note_id, note);
|
||||
return note;
|
||||
}
|
||||
const rows = await sql`
|
||||
INSERT INTO order_notes (note_id, order_id, tenant_id, author_id, body, version, clock, created_at, updated_at)
|
||||
VALUES (${note.note_id}, ${note.order_id}, ${note.tenant_id}, ${note.author_id}, ${note.body},
|
||||
${note.version}, ${note.clock}, ${note.created_at}, ${note.updated_at})
|
||||
RETURNING *
|
||||
`;
|
||||
return rowToNote(rows[0]);
|
||||
}
|
||||
|
||||
async function peekMaxClock(orderId: string): Promise<number> {
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) {
|
||||
let max = 0;
|
||||
for (const n of mem.values()) if (n.order_id === orderId && n.clock > max) max = n.clock;
|
||||
return max;
|
||||
}
|
||||
return maxClock(sql, orderId);
|
||||
}
|
||||
|
||||
export interface UpdateNoteInput {
|
||||
note_id: string;
|
||||
author_id: string;
|
||||
body: string;
|
||||
/** Optimistic concurrency: must equal the caller's seen version, else 409. */
|
||||
expected_version: number;
|
||||
}
|
||||
|
||||
export async function updateNote(input: UpdateNoteInput): Promise<OrderNote> {
|
||||
const body = input.body.trim();
|
||||
if (!body) throw new TypeError("note body must be non-empty");
|
||||
if (!Number.isInteger(input.expected_version) || input.expected_version < 1) {
|
||||
throw new TypeError("expected_version must be a positive integer");
|
||||
}
|
||||
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) {
|
||||
const current = mem.get(input.note_id);
|
||||
if (!current) throw new NoteNotFoundError(input.note_id);
|
||||
if (current.version !== input.expected_version) {
|
||||
throw new NoteVersionConflictError(input.note_id, input.expected_version, current.version);
|
||||
}
|
||||
const updated: OrderNote = {
|
||||
...current,
|
||||
body,
|
||||
version: current.version + 1,
|
||||
clock: nextLamportClock(current.clock),
|
||||
updated_at: new Date().toISOString(),
|
||||
};
|
||||
mem.set(updated.note_id, updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
const rows = await sql`
|
||||
UPDATE order_notes
|
||||
SET body = ${body},
|
||||
version = version + 1,
|
||||
clock = clock + 1,
|
||||
updated_at = ${new Date().toISOString()}
|
||||
WHERE note_id = ${input.note_id} AND version = ${input.expected_version}
|
||||
RETURNING *
|
||||
`;
|
||||
if (rows.length === 0) {
|
||||
const existing = await sql`SELECT * FROM order_notes WHERE note_id = ${input.note_id}`;
|
||||
if (existing.length === 0) throw new NoteNotFoundError(input.note_id);
|
||||
throw new NoteVersionConflictError(
|
||||
input.note_id,
|
||||
input.expected_version,
|
||||
Number(existing[0].version),
|
||||
);
|
||||
}
|
||||
return rowToNote(rows[0]);
|
||||
}
|
||||
|
||||
/** Direct read by note id — used by the route for server-authoritative tenant checks. */
|
||||
export async function findNote(noteId: string): Promise<OrderNote | null> {
|
||||
const sql = getSqlForDurableStore("order-notes");
|
||||
if (!sql) return mem.get(noteId) ?? null;
|
||||
const rows = await sql`SELECT * FROM order_notes WHERE note_id = ${noteId}`;
|
||||
return rows.length > 0 ? rowToNote(rows[0]) : null;
|
||||
}
|
||||
|
||||
/** Delete for tests: the in-memory fallback needs isolation between tests. */
|
||||
export function resetOrderNotesMemoryForTests(): void {
|
||||
mem.clear();
|
||||
}
|
||||
+32
-121
@@ -1,159 +1,70 @@
|
||||
/**
|
||||
* Next.js auth seam for /api/0pt. Browser/user calls use verified bearer/session.
|
||||
* Explicit machine routes accept: (1) legacy X-Internal-Token + server-configured
|
||||
* single-tenant scope, or (2) verified CL0UD workload JWT (tenant/capabilities
|
||||
* from claims, never client headers). Deny by default.
|
||||
* Next.js auth seam for the complete /api/0pt capability surface.
|
||||
*
|
||||
* Customer calls use verified Zitadel bearer identity and receive immutable
|
||||
* x-0pt-verified-* headers. Explicit machine routes may instead use the
|
||||
* shared X-Internal-Token convention; mutation handlers verify it again for
|
||||
* defence in depth.
|
||||
*/
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { assertAuthConfigSafe, resolveAuthContext } from '@/src/auth/context';
|
||||
import { SESSION_COOKIE, verifySession } from '@/lib/auth';
|
||||
import { verifyInternalServiceToken } from '@/src/auth/internal-token';
|
||||
import {
|
||||
SERVICE_CAPABILITIES_HEADER,
|
||||
SERVICE_TENANT_SCOPE_HEADER,
|
||||
resolveInternalServiceTenants,
|
||||
} from '@/src/auth/internal-service-tenant';
|
||||
import { isCl0udWorkloadConfigured, looksLikeCl0udWorkloadToken, verifyCl0udWorkloadToken } from '@/src/auth/cl0ud-workload';
|
||||
|
||||
assertAuthConfigSafe();
|
||||
export const config = { matcher: ['/api/0pt', '/api/0pt/:path*'] };
|
||||
|
||||
const EXEMPT_PATTERNS: RegExp[] = [/^\/api\/health(\/|$)/, /^\/api\/ready(\/|$)/, /^\/api\/admin\/metrics(\/|$)/];
|
||||
export const config = {
|
||||
matcher: ['/api/0pt', '/api/0pt/:path*'],
|
||||
};
|
||||
|
||||
const EXEMPT_PATTERNS: RegExp[] = [
|
||||
/^\/api\/health(\/|$)/,
|
||||
/^\/api\/ready(\/|$)/,
|
||||
/^\/api\/admin\/metrics(\/|$)/,
|
||||
];
|
||||
|
||||
/** Routes that may be reached with a service token instead of end-user bearer auth. */
|
||||
const INTERNAL_SERVICE_ROUTES: RegExp[] = [
|
||||
/^\/api\/0pt\/quality\/bridge-run$/,
|
||||
/^\/api\/0pt\/canonical\/facts$/,
|
||||
/^\/api\/0pt\/internal\/evidence-outbox\/dispatch$/,
|
||||
/^\/api\/0pt\/internal\/er\/candidates$/,
|
||||
/^\/api\/0pt\/search\/definitions$/,
|
||||
];
|
||||
|
||||
let _authDiagCount = 0;
|
||||
let internalScopeWarned = false;
|
||||
|
||||
/**
|
||||
* Headers that only middleware may set. Anything a client sends under these
|
||||
* names is a forgery attempt and is removed before forwarding — including on
|
||||
* the internal-token path, which previously passed the original header map
|
||||
* through unchanged.
|
||||
*/
|
||||
const VERIFIED_HEADERS = [
|
||||
'x-0pt-verified-tenant',
|
||||
'x-0pt-verified-sub',
|
||||
SERVICE_TENANT_SCOPE_HEADER,
|
||||
SERVICE_CAPABILITIES_HEADER,
|
||||
] as const;
|
||||
|
||||
function stripVerifiedHeaders(req: NextRequest): Headers {
|
||||
const forwarded = new Headers(req.headers);
|
||||
for (const name of VERIFIED_HEADERS) forwarded.delete(name);
|
||||
return forwarded;
|
||||
}
|
||||
|
||||
function bearerToken(req: NextRequest): string | null {
|
||||
const h = req.headers.get('authorization');
|
||||
if (!h?.toLowerCase().startsWith('bearer ')) return null;
|
||||
return h.slice(7).trim() || null;
|
||||
}
|
||||
|
||||
export async function middleware(req: NextRequest): Promise<NextResponse> {
|
||||
const path = req.nextUrl.pathname;
|
||||
if (EXEMPT_PATTERNS.some((re) => re.test(path))) return NextResponse.next();
|
||||
|
||||
if (INTERNAL_SERVICE_ROUTES.some((re) => re.test(path))) {
|
||||
// (1) Legacy shared internal token (engine/n8n). Tenant authority is SERVER
|
||||
// CONFIG (INTERNAL_SERVICE_TENANTS), never a client header: an inbound
|
||||
// `X-0pt-Internal-Tenant` is ignored and stripped. With no configured
|
||||
// tenants the principal has no tenant authority and tenant-scoped writes
|
||||
// fail closed with 403.
|
||||
if (verifyInternalServiceToken(req.headers)) {
|
||||
const forwarded = stripVerifiedHeaders(req);
|
||||
const tenants = resolveInternalServiceTenants();
|
||||
if (tenants.length > 1) {
|
||||
// The shared X-Internal-Token identifies ONE service process, not a set
|
||||
// of independently authenticated principals. A multi-tenant allowlist
|
||||
// would let any holder of that shared token choose between all listed
|
||||
// tenants, which is exactly the client-controlled authority this guard
|
||||
// exists to remove. Multi-tenant service access requires a verified
|
||||
// workload-identity binding (CL0UD delegation contract); until that
|
||||
// exists, an ambiguous configuration fails closed.
|
||||
console.error(
|
||||
'[0pt-auth] INTERNAL_SERVICE_TENANTS lists more than one tenant: refusing the internal request until workload-identity binding exists',
|
||||
);
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'OPT_UNAUTHENTICATED',
|
||||
message:
|
||||
'internal service tenant scope is ambiguous: configure exactly one tenant until a verified workload-identity binding exists',
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
forwarded.set(SERVICE_TENANT_SCOPE_HEADER, tenants.join(','));
|
||||
if (tenants.length === 1) {
|
||||
forwarded.set('x-0pt-verified-tenant', tenants[0]);
|
||||
} else if (tenants.length === 0 && !internalScopeWarned) {
|
||||
internalScopeWarned = true;
|
||||
console.warn(
|
||||
'[0pt-auth] INTERNAL_SERVICE_TENANTS is unset: the internal service principal has no tenant authority; tenant-scoped writes will be denied',
|
||||
);
|
||||
}
|
||||
return NextResponse.next({ request: { headers: forwarded } });
|
||||
}
|
||||
|
||||
// (2) CL0UD workload JWT (dual-accept): tenant and capabilities come from
|
||||
// verified claims only. Attempted only when the issuer is configured or the
|
||||
// presented token is issued by it; an invalid one is a 401, never a
|
||||
// fall-through to an unauthenticated dev path.
|
||||
const bt = bearerToken(req);
|
||||
if (bt && (isCl0udWorkloadConfigured() || looksLikeCl0udWorkloadToken(bt))) {
|
||||
try {
|
||||
const principal = await verifyCl0udWorkloadToken(bt);
|
||||
const forwarded = stripVerifiedHeaders(req);
|
||||
forwarded.set('x-0pt-verified-sub', principal.sub);
|
||||
forwarded.set('x-0pt-verified-tenant', principal.tenantId);
|
||||
forwarded.set(SERVICE_CAPABILITIES_HEADER, principal.capabilities.join(','));
|
||||
return NextResponse.next({ request: { headers: forwarded } });
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'workload token verification failed';
|
||||
return NextResponse.json({ error: 'OPT_UNAUTHENTICATED', message }, { status: 401 });
|
||||
}
|
||||
}
|
||||
if (INTERNAL_SERVICE_ROUTES.some((re) => re.test(path)) && verifyInternalServiceToken(req.headers)) {
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
if (_authDiagCount < 5) {
|
||||
_authDiagCount += 1;
|
||||
console.log(`[0pt-auth] middleware path=${path} auth_header=${!!req.headers.get('authorization')} auth_enforce=${process.env.AUTH_ENFORCE ?? 'unset'} request#${_authDiagCount}`);
|
||||
}
|
||||
|
||||
if (!req.headers.get('authorization')) {
|
||||
const session = await verifySession(req.cookies.get(SESSION_COOKIE)?.value);
|
||||
if (
|
||||
session &&
|
||||
typeof session.sub === 'string' &&
|
||||
typeof session.tenantId === 'string' &&
|
||||
typeof session.exp === 'number' &&
|
||||
session.exp > Date.now()
|
||||
) {
|
||||
const forwarded = stripVerifiedHeaders(req);
|
||||
forwarded.set('x-0pt-verified-sub', session.sub);
|
||||
forwarded.set('x-0pt-verified-tenant', session.tenantId);
|
||||
return NextResponse.next({ request: { headers: forwarded } });
|
||||
}
|
||||
const hasAuth = !!req.headers.get('authorization');
|
||||
console.log(
|
||||
`[0pt-auth] middleware path=${path} auth_header=${hasAuth} ` +
|
||||
`auth_enforce=${process.env.AUTH_ENFORCE ?? 'unset'} ` +
|
||||
`node_env=${process.env.NODE_ENV ?? 'unset'} request#${_authDiagCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
const decision = await resolveAuthContext(req.headers);
|
||||
if (!decision.ok) {
|
||||
return NextResponse.json({ error: decision.code, message: decision.message, ...(decision.details ? { details: decision.details } : {}) }, { status: decision.status });
|
||||
return NextResponse.json(
|
||||
{ error: decision.code, message: decision.message, ...(decision.details ? { details: decision.details } : {}) },
|
||||
{ status: decision.status },
|
||||
);
|
||||
}
|
||||
|
||||
const principal = decision.ctx.principal;
|
||||
if (principal) {
|
||||
const forwarded = stripVerifiedHeaders(req);
|
||||
const forwarded = new Headers(req.headers);
|
||||
forwarded.set('x-0pt-verified-sub', principal.sub);
|
||||
forwarded.set('x-0pt-verified-tenant', principal.tenantId);
|
||||
return NextResponse.next({ request: { headers: forwarded } });
|
||||
}
|
||||
|
||||
// No verified principal (explicit AUTH_ENFORCE=false development mode).
|
||||
// Never forward a client-named verified header, even in dev.
|
||||
return NextResponse.next({ request: { headers: stripVerifiedHeaders(req) } });
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
@@ -110,11 +110,6 @@ const securityHeaders = [
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
// @siax/contracts, @siax/config och @siax/tokens exporterar fortfarande
|
||||
// src/ (TS) enligt DES1GN-konventionen — Turbopack måste transpilera dem
|
||||
// (ActionGate-piloten, ADR-0001). @siax/ui 0.12.0+ (och @siax/charts 0.4.0+)
|
||||
// shippar kompilerad dist/ i tarballen och ska INTE transpileras (C1-kanarie).
|
||||
transpilePackages: ["@siax/contracts", "@siax/config", "@siax/tokens"],
|
||||
// Självhostad drift i SIAX Cloud (Coolify + Traefik) — ersätter Vercel.
|
||||
//
|
||||
// "standalone" får `next build` att packa en fristående Node-server i
|
||||
|
||||
Generated
+8372
File diff suppressed because it is too large
Load Diff
+10
-18
@@ -16,9 +16,7 @@
|
||||
"format:write": "prettier --write .",
|
||||
"typecheck:app": "tsc --noEmit -p tsconfig.json",
|
||||
"siax:doctor": "node scripts/siax-doctor.mjs",
|
||||
"deps:check": "depcruise src app components lib --config .dependency-cruiser.cjs",
|
||||
"vehiq:oltp-ingest": "tsx scripts/vehiq-oltp-ingest/run.ts",
|
||||
"check:contrast": "node scripts/ci/check-text-contrast.mjs"
|
||||
"deps:check": "depcruise src app components lib --config .dependency-cruiser.cjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.2.5",
|
||||
@@ -52,25 +50,19 @@
|
||||
"@radix-ui/react-toggle-group": "1.1.19",
|
||||
"@radix-ui/react-tooltip": "1.2.16",
|
||||
"@siax/0pt-decision": "workspace:*",
|
||||
"@siax/access": "workspace:*",
|
||||
"@siax/auth-zitadel": "0.1.1",
|
||||
"@siax/charts": "^0.5.0",
|
||||
"@siax/collaboration": "0.3.0",
|
||||
"@siax/config": "^0.2.1",
|
||||
"@siax/contracts": "^0.12.1",
|
||||
"@siax/import-export": "^0.2.2",
|
||||
"@siax/tokens": "^0.1.2",
|
||||
"@siax/ui": "^0.16.13",
|
||||
"@siax/ui": "^0.4.1",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "1.1.1",
|
||||
"cmdk": "1.0.4",
|
||||
"date-fns": "4.1.0",
|
||||
"embla-carousel-react": "8.5.1",
|
||||
"input-otp": "1.4.1",
|
||||
"jose": "^5.9.6",
|
||||
"lucide-react": "^0.454.0",
|
||||
"next": "16.4.1",
|
||||
"next": "16.3.4",
|
||||
"next-themes": "^0.4.6",
|
||||
"postgres": "^3.4.9",
|
||||
"react": "19.2.8",
|
||||
@@ -78,7 +70,8 @@
|
||||
"react-dom": "19.2.8",
|
||||
"react-hook-form": "^7.60.0",
|
||||
"react-resizable-panels": "^2.1.7",
|
||||
"sonner": "^2.0.6",
|
||||
"recharts": "2.15.4",
|
||||
"sonner": "^1.7.4",
|
||||
"stripe": "^22.2.3",
|
||||
"tailwind-merge": "^3.3.1",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
@@ -96,16 +89,15 @@
|
||||
"postcss": "^8.5.28",
|
||||
"prettier": "^3.9.6",
|
||||
"tailwindcss": "^4.1.9",
|
||||
"tsx": "^4.23.15",
|
||||
"tw-animate-css": "1.4.0",
|
||||
"typescript": "^5",
|
||||
"typescript-eslint": "^8.15.0",
|
||||
"vitest": "^3.2.7"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"sharp@<0.35.5": "0.35.5",
|
||||
"source-map-js@<1.2.2": "1.2.2"
|
||||
}
|
||||
"onlyBuiltDependencies": [
|
||||
"sharp",
|
||||
"esbuild"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"name": "@siax/access",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Universal, framework-neutral project/tenant relationship checks for SIAX Cloud (OpenFGA). Reused by 0pt, DOC0, N0D and other products instead of per-repo copies.",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"license": "UNLICENSED"
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
/**
|
||||
* @siax/access idempotency primitives — the universal SIAX contract for any
|
||||
* operation that must either happen exactly once or replay its receipt.
|
||||
*
|
||||
* This package is derived from the pattern proven in 0pt's durable upload
|
||||
* attempts (prepare -> claim -> dispatch -> store receipt -> replay), then
|
||||
* generalized so DOC0, N0D and future products can adopt the identical shape
|
||||
* instead of re-implementing it.
|
||||
*
|
||||
* Rules encoded here:
|
||||
* 1. An operation identity binds EVERY result-affecting input (tenant,
|
||||
* project, actor, payload version). A changed payload under the same key
|
||||
* is a CONFLICT, never a replay of someone else's receipt.
|
||||
* 2. One claimant per key: returning `false` from `start` means another
|
||||
* caller owns the dispatch, and only the stored receipt (or bounded
|
||||
* observation) may be answered.
|
||||
* 3. A stored receipt is replayed verbatim; the caller never invents one.
|
||||
* 4. Commit boundaries: NEVER write a network command before the claim is
|
||||
* durably persisted, and never lose the claim after the command may have
|
||||
* committed.
|
||||
*/
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
/** Stable JSON canonicalization (sorted array stays sorted; v-prefix bumped on contract change). */
|
||||
export function operationFingerprint(parts: readonly unknown[], version = "siax-idempotency-v1"): string {
|
||||
return createHash("sha256")
|
||||
.update(JSON.stringify([version, ...parts]))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
export interface OperationIdentity {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
/** Client-generated, transport-level key (<=256 visible ASCII). */
|
||||
idempotencyKey: string;
|
||||
/** Supply result-affecting inputs; the helper adds the scope fields itself. */
|
||||
payload: readonly unknown[];
|
||||
}
|
||||
|
||||
export function operationIdentity(operation: OperationIdentity): {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
idempotencyKey: string;
|
||||
fingerprint: string;
|
||||
} {
|
||||
if (
|
||||
!operation ||
|
||||
![operation.tenantId, operation.projectId, operation.actorId, operation.idempotencyKey].every(
|
||||
(value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._@:+-]{0,255}$/.test(value),
|
||||
) ||
|
||||
!Array.isArray(operation.payload)
|
||||
) {
|
||||
throw new Error("Invalid idempotent operation identity");
|
||||
}
|
||||
void operation.payload;
|
||||
return {
|
||||
tenantId: operation.tenantId,
|
||||
projectId: operation.projectId,
|
||||
actorId: operation.actorId,
|
||||
idempotencyKey: operation.idempotencyKey,
|
||||
fingerprint: operationFingerprint([
|
||||
operation.tenantId,
|
||||
operation.projectId,
|
||||
operation.actorId,
|
||||
...operation.payload,
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
export type OperationOutcome<R> =
|
||||
| { kind: "claimed"; execute: () => Promise<R> }
|
||||
| { kind: "replayed"; receipt: R }
|
||||
| { kind: "conflict"; expected?: string };
|
||||
|
||||
/** Structural contract for an attempt store. Matched by Postgres adapters per product. */
|
||||
export interface IdempotencyStore<Identity, Receipt> {
|
||||
/** Returns true when this caller won the right to dispatch; false = reuse replay path. */
|
||||
start(identity: Identity, fingerprint: string): Promise<boolean>;
|
||||
/** Persist after a verified downstream commit. Must never be called before. */
|
||||
save(identity: Identity, fingerprint: string, receipt: Receipt): Promise<void>;
|
||||
/** Load a stored receipt for replay (exact fingerprint match). */
|
||||
receipt(identity: Identity, fingerprint: string): Promise<Receipt | undefined>;
|
||||
}
|
||||
|
||||
export type IdempotentStoreItemIdentity<I> = {
|
||||
identity: I;
|
||||
fingerprint: string;
|
||||
};
|
||||
|
||||
export async function runIdempotentOperation<I, R>(input: {
|
||||
store: IdempotencyStore<I, R>;
|
||||
identity: I;
|
||||
fingerprint: string;
|
||||
/** Must be safe to call exactly once; a second call is never attempted here. */
|
||||
dispatch: () => Promise<R>;
|
||||
}): Promise<OperationOutcome<R>> {
|
||||
if (typeof input.dispatch !== "function") throw new Error("Dispatch is required");
|
||||
try {
|
||||
const won = await input.store.start(input.identity, input.fingerprint);
|
||||
if (!won) {
|
||||
const stored = await input.store.receipt(input.identity, input.fingerprint);
|
||||
return stored !== undefined
|
||||
? { kind: "replayed", receipt: stored }
|
||||
: { kind: "replayed", receipt: undefined as unknown as R };
|
||||
}
|
||||
} catch (error) {
|
||||
return { kind: "conflict", expected: error instanceof Error ? error.message : "store_unavailable" };
|
||||
}
|
||||
const receipt = await input.dispatch();
|
||||
try {
|
||||
await input.store.save(input.identity, input.fingerprint, receipt);
|
||||
} catch {
|
||||
/* The downstream commit is real; a journal-write failure must not turn a
|
||||
real receipt into an error. The next retry replays via the stored receipt
|
||||
if the save ever succeeds before a downstream resend. */
|
||||
}
|
||||
return { kind: "claimed", execute: async () => receipt };
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from './relationships';
|
||||
export * from './idempotency';
|
||||
@@ -1,235 +0,0 @@
|
||||
/**
|
||||
* @siax/access — universal project/tenant relationship checks for SIAX Cloud.
|
||||
*
|
||||
* This is the reusable extraction of the pattern first proven in DOC0's
|
||||
* `src/clients/project-relationships.ts`. It is deliberately framework-neutral
|
||||
* (no Next.js, Fastify, Prisma or product types) so every SIAX product can
|
||||
* consume the exact same authorization primitive instead of copying it:
|
||||
*
|
||||
* 0pt — document upload + structuring scope
|
||||
* DOC0 — document/version/signature scope
|
||||
* N0D — job submission scope
|
||||
* any app — tenant/project membership
|
||||
*
|
||||
* IMPORTANT: a relationship match is ONE input to authorization, never a
|
||||
* complete decision. The caller must independently bind tenant and actor to a
|
||||
* verified principal (never to request headers), enforce tenant/project
|
||||
* status, capability, data-handling policy and an authoritative tuple
|
||||
* lifecycle. `resolveRelationship` fails closed: only an explicit
|
||||
* `relationships_match` is treated as allowed.
|
||||
*/
|
||||
|
||||
export type RelationshipResult = 'allowed' | 'denied' | 'unavailable';
|
||||
|
||||
/** The outcome of the composite project check. */
|
||||
export type ProjectRelationshipResult = 'relationships_match' | 'denied' | 'unavailable';
|
||||
|
||||
export interface ProjectRelationshipScope {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
actorId: string;
|
||||
}
|
||||
|
||||
const objectId = /^[A-Za-z0-9][A-Za-z0-9._@+-]{0,127}$/;
|
||||
const ulid = /^[0-9A-HJKMNP-TV-Z]{26}$/;
|
||||
const maxResponseBytes = 16 * 1024;
|
||||
|
||||
export interface OpenFgaRelationshipsOptions {
|
||||
baseUrl: string;
|
||||
storeId: string;
|
||||
modelId: string;
|
||||
serviceToken: string;
|
||||
timeoutMs?: number;
|
||||
fetchImpl?: typeof fetch;
|
||||
/** Explicit test-only opt-in for an isolated loopback OpenFGA process. */
|
||||
testOnlyAllowLoopbackHttp?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only OpenFGA relationship reader. Never writes tuples, never caches,
|
||||
* and never retries: an unavailable authorization source must stay visible to
|
||||
* the caller so it can fail closed.
|
||||
*/
|
||||
export class OpenFgaRelationships {
|
||||
private readonly baseUrl: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
private readonly storeId: string;
|
||||
private readonly modelId: string;
|
||||
private readonly serviceToken: string;
|
||||
private readonly timeoutMs: number;
|
||||
|
||||
constructor(options: OpenFgaRelationshipsOptions) {
|
||||
const url = new URL(options.baseUrl);
|
||||
const loopbackTest =
|
||||
process.env.NODE_ENV === 'test' &&
|
||||
options.testOnlyAllowLoopbackHttp === true &&
|
||||
url.protocol === 'http:' &&
|
||||
url.hostname === '127.0.0.1';
|
||||
if (
|
||||
(!loopbackTest && url.protocol !== 'https:') ||
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
typeof options.storeId !== 'string' ||
|
||||
typeof options.modelId !== 'string' ||
|
||||
!ulid.test(options.storeId) ||
|
||||
!ulid.test(options.modelId) ||
|
||||
typeof options.serviceToken !== 'string' ||
|
||||
!/^[\x21-\x7e]{1,8192}$/.test(options.serviceToken) ||
|
||||
(options.timeoutMs !== undefined &&
|
||||
(!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs < 100 || options.timeoutMs > 30_000))
|
||||
) {
|
||||
throw new Error('Invalid trusted OpenFGA configuration');
|
||||
}
|
||||
this.baseUrl = url.toString().replace(/\/+$/, '');
|
||||
this.fetchImpl = options.fetchImpl ?? fetch;
|
||||
this.storeId = options.storeId;
|
||||
this.modelId = options.modelId;
|
||||
this.serviceToken = options.serviceToken;
|
||||
this.timeoutMs = options.timeoutMs ?? 5_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Both checks are necessary: project membership alone may inherit from a
|
||||
* different parent tenant if bad tuples associate a project with two
|
||||
* tenants. Returns `relationships_match` only when both hold.
|
||||
*/
|
||||
async checkProject(scope: ProjectRelationshipScope): Promise<ProjectRelationshipResult> {
|
||||
if (!scope || typeof scope !== 'object' || Array.isArray(scope)) {
|
||||
return 'denied';
|
||||
}
|
||||
const { tenantId, projectId, actorId } = scope;
|
||||
if (![tenantId, projectId, actorId].every((value) => typeof value === 'string' && objectId.test(value))) {
|
||||
return 'denied';
|
||||
}
|
||||
const actor = await this.checkTuple(`user:${actorId}`, 'member', `tenant:${tenantId}`);
|
||||
if (actor !== 'allowed') return actor === 'denied' ? 'denied' : 'unavailable';
|
||||
const parent = await this.checkTuple(`tenant:${tenantId}`, 'tenant', `project:${projectId}`);
|
||||
return parent === 'allowed' ? 'relationships_match' : parent;
|
||||
}
|
||||
|
||||
/** One raw relationship check. Public so products can map their own tuples. */
|
||||
async checkTuple(user: string, relation: string, object: string): Promise<RelationshipResult> {
|
||||
if (
|
||||
![user, relation, object].every(
|
||||
(value) => typeof value === 'string' && value.length > 0 && value.length <= 256,
|
||||
)
|
||||
) {
|
||||
return 'denied';
|
||||
}
|
||||
try {
|
||||
const response = await this.fetchImpl(`${this.baseUrl}/stores/${this.storeId}/check`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
authorization: `Bearer ${this.serviceToken}`,
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
authorization_model_id: this.modelId,
|
||||
consistency: 'HIGHER_CONSISTENCY',
|
||||
tuple_key: { user, relation, object },
|
||||
}),
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(this.timeoutMs),
|
||||
});
|
||||
if (!response.ok || !response.body) return 'unavailable';
|
||||
const reader = response.body.getReader();
|
||||
try {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const part = await reader.read();
|
||||
if (part.done) break;
|
||||
total += part.value.byteLength;
|
||||
if (total > maxResponseBytes) {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
return 'unavailable';
|
||||
}
|
||||
chunks.push(part.value);
|
||||
}
|
||||
const result: unknown = JSON.parse(
|
||||
new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)),
|
||||
);
|
||||
if (
|
||||
!result ||
|
||||
typeof result !== 'object' ||
|
||||
Array.isArray(result) ||
|
||||
typeof (result as { allowed?: unknown }).allowed !== 'boolean'
|
||||
) {
|
||||
return 'unavailable';
|
||||
}
|
||||
return (result as { allowed: boolean }).allowed ? 'allowed' : 'denied';
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
} catch {
|
||||
return 'unavailable';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical environment variable names used across the fleet. Reads are
|
||||
* explicit (no implicit defaults) so a missing value is visible.
|
||||
*/
|
||||
export const OPENFGA_ENV = {
|
||||
baseUrl: 'OPENFGA_API_URL',
|
||||
storeId: 'OPENFGA_STORE_ID',
|
||||
modelId: 'OPENFGA_MODEL_ID',
|
||||
serviceToken: 'OPENFGA_AUTH_TOKEN',
|
||||
} as const;
|
||||
|
||||
export interface ProjectAccessOptions {
|
||||
/** The already-configured relationship reader, or undefined when OpenFGA is not configured. */
|
||||
relationships?: OpenFgaRelationships;
|
||||
/**
|
||||
* Optional extra policy (project status, capability, data-handling). It runs
|
||||
* only after the relationship check matched; a rejection is final.
|
||||
*/
|
||||
additionalPolicy?: (scope: ProjectRelationshipScope) => Promise<boolean> | boolean;
|
||||
}
|
||||
|
||||
/** Fail closed: only an explicit match with no policy objection is allowed. */
|
||||
export async function isProjectAccessAllowed(
|
||||
scope: ProjectRelationshipScope,
|
||||
options: ProjectAccessOptions,
|
||||
): Promise<boolean> {
|
||||
if (!options.relationships) return false;
|
||||
const result = await options.relationships.checkProject(scope);
|
||||
if (result !== 'relationships_match') return false;
|
||||
if (options.additionalPolicy) {
|
||||
try {
|
||||
return (await options.additionalPolicy(scope)) === true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a relationship reader from a `NodeJS.ProcessEnv`-shaped object.
|
||||
* Returns `undefined` (fail closed) when any value is missing or invalid.
|
||||
*/
|
||||
export function openFgaFromEnv(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
fetchImpl?: typeof fetch,
|
||||
): OpenFgaRelationships | undefined {
|
||||
const baseUrl = env[OPENFGA_ENV.baseUrl];
|
||||
const storeId = env[OPENFGA_ENV.storeId];
|
||||
const modelId = env[OPENFGA_ENV.modelId];
|
||||
const serviceToken = env[OPENFGA_ENV.serviceToken];
|
||||
if (!baseUrl || !storeId || !modelId || !serviceToken) return undefined;
|
||||
try {
|
||||
return new OpenFgaRelationships({
|
||||
baseUrl,
|
||||
storeId,
|
||||
modelId,
|
||||
serviceToken,
|
||||
...(fetchImpl ? { fetchImpl } : {}),
|
||||
});
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
Generated
+572
-409
File diff suppressed because it is too large
Load Diff
@@ -1,74 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Blocking guard for finding UI-09 (measured 2026-09-26): 0pt.app carried 82
|
||||
* `color-contrast` violations at axe-core 4.10.2 impact=serious — the estate's
|
||||
* single largest a11y defect. Every one of them came from the same shape: a
|
||||
* Tailwind alpha modifier on a muted text colour.
|
||||
*
|
||||
* Measured WCAG 2.2 contrast against the two theme backgrounds in
|
||||
* styles/globals.css (--background: oklch(1 0 0) light / oklch(0.145 0 0) dark,
|
||||
* --muted-foreground: oklch(0.556 0 0) / oklch(0.708 0 0)):
|
||||
*
|
||||
* text-muted-foreground 4.73:1 light 7.63:1 dark PASS (AA needs 4.5)
|
||||
* text-muted-foreground/70 2.71:1 4.20:1 FAIL
|
||||
* text-muted-foreground/60 2.29:1 3.37:1 FAIL
|
||||
* text-muted-foreground/50 1.96:1 2.67:1 FAIL
|
||||
* text-muted-foreground/40 1.69:1 2.11:1 FAIL
|
||||
* text-muted-foreground/10 1.13:1 1.13:1 FAIL
|
||||
*
|
||||
* The unmodified token passes in both themes, so the fix is simply never to
|
||||
* fade it. Purely decorative text is exempt — but it has to SAY so: the element
|
||||
* must carry `aria-hidden`, which is also what makes axe skip it. The single
|
||||
* remaining case (app/bestall/page.tsx, the oversized "01" masthead numeral) is
|
||||
* `aria-hidden` + `select-none` + `pointer-events-none` and is allowed by that
|
||||
* rule.
|
||||
*
|
||||
* This is a source-level guard, not a browser run. The full axe-core job that
|
||||
* UI-09 also asks for needs a build + serve in CI and is tracked separately;
|
||||
* until it exists this stops the regression at the shape that caused it.
|
||||
*/
|
||||
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
||||
import { join, relative } from 'node:path';
|
||||
|
||||
const ROOT = new URL('../..', import.meta.url).pathname.replace(/\/$/, '');
|
||||
const SKIP = new Set(['node_modules', '.next', '.git', 'dist', 'build', 'coverage', '.turbo']);
|
||||
const EXT = /\.(tsx|ts|jsx|js|css)$/;
|
||||
/** Alpha-modified colour utilities on TEXT. Background/border alphas are fine. */
|
||||
const PATTERN = /\btext-(muted-foreground|foreground|primary|secondary|accent-foreground|card-foreground|popover-foreground)\/\d+/g;
|
||||
|
||||
function walk(dir, out = []) {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (SKIP.has(name)) continue;
|
||||
const p = join(dir, name);
|
||||
if (statSync(p).isDirectory()) walk(p, out);
|
||||
else if (EXT.test(name)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const violations = [];
|
||||
for (const file of walk(ROOT)) {
|
||||
const src = readFileSync(file, 'utf8');
|
||||
const lines = src.split('\n');
|
||||
lines.forEach((line, i) => {
|
||||
for (const m of line.matchAll(PATTERN)) {
|
||||
// Decorative text is exempt when the element declares itself hidden to AT.
|
||||
// The attribute may sit on an earlier line of the same JSX element.
|
||||
const window = lines.slice(Math.max(0, i - 6), i + 1).join('\n');
|
||||
if (/\baria-hidden\b/.test(window)) continue;
|
||||
violations.push({ file: relative(ROOT, file), line: i + 1, token: m[0], text: line.trim() });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (violations.length) {
|
||||
console.error(`\n✗ ${violations.length} alpha-faded text colour(s) found — WCAG 2.2 AA 1.4.3 (finding UI-09).\n`);
|
||||
for (const v of violations) {
|
||||
console.error(` ${v.file}:${v.line} ${v.token}`);
|
||||
console.error(` ${v.text.slice(0, 160)}`);
|
||||
}
|
||||
console.error('\n Use the unmodified token (text-muted-foreground = 4.73:1 light / 7.63:1 dark).');
|
||||
console.error(' If the text really is decoration, put aria-hidden on the element.\n');
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('✓ no alpha-faded text colours — WCAG 2.2 AA 1.4.3 contrast shape is clean (UI-09)');
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user