Compare commits

..
Author SHA1 Message Date
admin c134527509 WIP (auto-sweep): osparat arbete i 0pt-worktree
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 16s
CI (SIAX Cloud) / security (pull_request) Failing after 40s
Security Scan (SIAX Cloud) / security (pull_request) Failing after 32s
CI (SIAX Cloud) / integration (pull_request) Failing after 1m22s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m52s
2026-10-05 09:44:22 +02:00
121 changed files with 8969 additions and 8907 deletions
-82
View File
@@ -68,10 +68,6 @@ INTERNAL_TOKEN=change-me-internal-token
#
# Fleet Zitadel issuer (OIDC). Default when unset: https://id-customers.siax.io
ZITADEL_ISSUER=https://id-customers.siax.io
# 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.
@@ -206,81 +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=
# Central Keycloak (SIAX Portal)
KEYCLOAK_ISSUER=https://auth.portal.siax.dev/realms/portal
KEYCLOAK_EXPECTED_AUDIENCE=account
KEYCLOAK_AUTHORIZED_PARTY=siax-portal
+8 -16
View File
@@ -6,26 +6,18 @@ 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.
concurrency:
group: deploy-0pt-main
cancel-in-progress: false
jobs:
deploy:
runs-on: ubuntu-latest
+2 -12
View File
@@ -17,16 +17,10 @@ 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.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
quality:
runs-on: ubuntu-latest
@@ -240,13 +234,9 @@ jobs:
- 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' .
trivy fs --scanners vuln,secret --severity HIGH,CRITICAL --exit-code 1 .
sonar:
# SonarQube Community Build har inget separat PR-analysläge (en enda "main"-gren
+1 -7
View File
@@ -8,14 +8,9 @@ on:
schedule:
- cron: "0 4 * * *" # daily 04:00 UTC
concurrency:
group: nightly-${{ github.ref }}
cancel-in-progress: true
jobs:
quality:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@@ -39,7 +34,6 @@ jobs:
security:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- name: Install Trivy
@@ -51,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 .
-77
View File
@@ -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 * * * *"
concurrency:
group: prod-smoke
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
+2 -7
View File
@@ -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,11 +39,6 @@ on:
branches: [main]
workflow_dispatch:
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
env:
IMAGE_REPO: git.cloud.siax.io/sax3l/0pt
DOCKERFILE: Dockerfile
+2 -6
View File
@@ -19,16 +19,12 @@ name: Security Scan (SIAX Cloud)
# and docs/compliance/GOLDEN-STANDARD-REPORT.md control C6 for full context.
on:
push:
branches: ["main"]
branches: ["**"]
pull_request:
workflow_dispatch:
schedule:
- cron: "0 5 * * 1" # weekly Monday re-scan
concurrency:
group: security-${{ github.ref }}
cancel-in-progress: true
jobs:
security:
runs-on: ubuntu-latest
@@ -40,4 +36,4 @@ jobs:
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: |
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 .
-3
View File
@@ -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/
-11
View File
@@ -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
+4 -4
View File
@@ -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.
-5
View File
@@ -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.
-37
View File
@@ -1,37 +0,0 @@
import { NextResponse, type NextRequest } from 'next/server';
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
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 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 },
);
}
}
-146
View File
@@ -1,146 +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;
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 },
);
}
-36
View File
@@ -1,36 +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,
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 });
+12 -6
View File
@@ -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 ?? "",
},
);
-56
View File
@@ -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,
});
}
-443
View File
@@ -1,443 +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 { 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 (
!isValidScopeId(projectId) ||
!isValidScopeId(documentId) ||
!isValidScopeId(versionId) ||
typeof checksum !== 'string' ||
!/^[0-9a-f]{64}$/.test(checksum) ||
pipelineStage !== 'parsed' ||
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 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 },
);
}
}
-241
View File
@@ -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 },
);
}
-79
View File
@@ -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
View File
@@ -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;
}
+3 -11
View File
@@ -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 });
}
+20 -23
View File
@@ -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
View File
@@ -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 });
}
}
-24
View File
@@ -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' } },
);
}
+33 -97
View File
@@ -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 });
}
}
}
File diff suppressed because it is too large Load Diff
+175 -5
View File
@@ -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>
);
}
-150
View File
@@ -1,150 +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 [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; message?: string };
if (r.ok && body.packs) {
setPacks(body.packs);
setCurrency(body.currency ?? 'SEK');
} 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>
<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>
</li>
))}
</ul>
)}
{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>
);
}
+1 -2
View File
@@ -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" },

Some files were not shown because too many files have changed in this diff Show More