diff --git a/app/admin/page.tsx b/app/admin/page.tsx index 540423f..370497c 100644 --- a/app/admin/page.tsx +++ b/app/admin/page.tsx @@ -42,10 +42,13 @@ export default function AdminPage() { const load = useCallback(async () => { setError(false); try { - const [o, m] = await Promise.all([ - fetch("/api/orders", { cache: "no-store" }).then((r) => r.json()), - fetch("/api/admin/metrics", { cache: "no-store" }).then((r) => r.json()), + const [oRes, mRes] = await Promise.all([ + fetch("/api/orders", { cache: "no-store" }), + fetch("/api/admin/metrics", { cache: "no-store" }), ]); + if (!oRes.ok || !mRes.ok) throw new Error("fetch failed"); + const [o, m] = await Promise.all([oRes.json(), mRes.json()]); + if (!m || typeof m.total !== "number") throw new Error("bad metrics shape"); setOrders(mergeOrders(Array.isArray(o) ? o : []) as Order[]); setMetrics(m); } catch { diff --git a/app/api/0pt/documents/[documentId]/extraction/route.ts b/app/api/0pt/documents/[documentId]/extraction/route.ts index 746594f..783b4a8 100644 --- a/app/api/0pt/documents/[documentId]/extraction/route.ts +++ b/app/api/0pt/documents/[documentId]/extraction/route.ts @@ -15,7 +15,17 @@ export async function POST(request: NextRequest, { params }: { params: Promise<{ return NextResponse.json(result, { status: 201 }); } catch (error: unknown) { const message = error instanceof Error ? error.message : "Unknown error"; - return NextResponse.json({ error: message }, { status: 400 }); + if (/not configured/i.test(message)) { + return NextResponse.json({ error: message }, { status: 501 }); + } + if (/^Policy denied/i.test(message)) { + return NextResponse.json({ error: message }, { status: 403 }); + } + if (/^Policy requires approval/i.test(message)) { + return NextResponse.json({ error: message }, { status: 409 }); + } + const status = /not found/i.test(message) ? 404 : 400; + return NextResponse.json({ error: message }, { status }); } } diff --git a/app/api/0pt/lakehouse/mappings/[mappingId]/route.ts b/app/api/0pt/lakehouse/mappings/[mappingId]/route.ts index 5e76ca2..6010236 100644 --- a/app/api/0pt/lakehouse/mappings/[mappingId]/route.ts +++ b/app/api/0pt/lakehouse/mappings/[mappingId]/route.ts @@ -1,7 +1,5 @@ import { NextResponse } from "next/server"; -import { DatasetIcebergMappingService } from "@/src/services/dataset-iceberg-mapping-service"; - -const mappingService = new DatasetIcebergMappingService(); +import { mappingService } from "@/src/services/lakehouse-mapping-registry"; export async function GET(_request: Request, { params }: { params: Promise<{ mappingId: string }> }) { try { diff --git a/app/api/0pt/lakehouse/mappings/[mappingId]/writes/route.ts b/app/api/0pt/lakehouse/mappings/[mappingId]/writes/route.ts index 52fccdd..55eafdb 100644 --- a/app/api/0pt/lakehouse/mappings/[mappingId]/writes/route.ts +++ b/app/api/0pt/lakehouse/mappings/[mappingId]/writes/route.ts @@ -1,7 +1,5 @@ import { NextRequest, NextResponse } from "next/server"; -import { IcebergWriteService } from "@/src/services/iceberg-write-service"; - -const writeService = new IcebergWriteService(); +import { writeService } from "@/src/services/lakehouse-mapping-registry"; // Registers a new Iceberg snapshot (a write) through ST0RE's table registry // for an already-mapped dataset. See docs/ICEBERG_WRITE_BOUNDARY.md. diff --git a/app/api/0pt/lakehouse/mappings/route.ts b/app/api/0pt/lakehouse/mappings/route.ts index a843b54..939c6e9 100644 --- a/app/api/0pt/lakehouse/mappings/route.ts +++ b/app/api/0pt/lakehouse/mappings/route.ts @@ -1,14 +1,12 @@ import { NextRequest, NextResponse } from "next/server"; -import { IcebergWriteService } from "@/src/services/iceberg-write-service"; -import { DatasetIcebergMappingService } from "@/src/services/dataset-iceberg-mapping-service"; +import { mappingService, writeService } from "@/src/services/lakehouse-mapping-registry"; -// Shared instances so a mapping created via POST is visible to a later GET -// within the same server process, matching the in-memory-per-module -// convention already used by app/api/0pt/datasets and app/api/0pt/quality -// (Postgres persistence exists in sql/ but is not wired into route handlers -// in this pass -- same limitation those routes already have). -const mappingService = new DatasetIcebergMappingService(); -const writeService = new IcebergWriteService({ mappingService }); +// Shared instances (src/services/lakehouse-mapping-registry.ts) so a mapping +// created via POST is visible to a later GET, and to the sibling +// /{mappingId}/writes route, within the same server process -- matching the +// in-memory-per-module convention already used by app/api/0pt/datasets and +// app/api/0pt/quality (Postgres persistence exists in sql/ but is not wired +// into route handlers in this pass -- same limitation those routes already have). // POST registers a NEW Iceberg table in ST0RE's table registry (via // IcebergWriteService.mapDatasetToIcebergTable) and records the diff --git a/app/api/0pt/sources/[sourceId]/query/route.ts b/app/api/0pt/sources/[sourceId]/query/route.ts index f1b5d0f..3909eb4 100644 --- a/app/api/0pt/sources/[sourceId]/query/route.ts +++ b/app/api/0pt/sources/[sourceId]/query/route.ts @@ -10,8 +10,13 @@ * is not shared across route modules yet — see the "Singleton note" in * src/services/document-capture-service.ts for prior art on this same repo * limitation). A source registered via POST /api/0pt/sources will not be - * resolvable here until SourceService is backed by shared persistence - * (sql/002_p0_dataset_quality.sql already defines `opt_sources` for that). + * resolvable here until SourceService is backed by shared persistence. + * Correction: this comment previously claimed `sql/002_p0_dataset_quality.sql` + * already defined an `opt_sources` table for that. That file does not exist + * and never has (git log --all: zero commits, any branch, ever). sql/ today + * has only 001_init.sql and 004_iceberg_write_boundary.sql. The real fix — + * backing SourceService with real persistence — is still open; no migration + * for it exists yet. * Details: docs/P0_QUERY_SOURCE_FLOW.md. */ import { NextRequest, NextResponse } from "next/server"; diff --git a/app/api/ai/parse/route.ts b/app/api/ai/parse/route.ts index e4f94e6..aebfdec 100644 --- a/app/api/ai/parse/route.ts +++ b/app/api/ai/parse/route.ts @@ -24,7 +24,9 @@ const DEST: [RegExp, string][] = [ ]; export async function POST(req: NextRequest) { - const { text } = await req.json().catch(() => ({ text: "" })); + const parsed = await req.json().catch(() => ({ text: "" })); + const body = parsed && typeof parsed === "object" ? parsed : { text: "" }; + const { text } = body as { text?: string }; if (!text) return NextResponse.json({ error: { code: "bad_request", message: "text krävs" } }, { status: 400 }); const eng = await engineFetch("/ai/parse", { method: "POST", body: JSON.stringify({ text }) }); diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.ts index 7893d4b..8e1929e 100644 --- a/app/api/auth/login/route.ts +++ b/app/api/auth/login/route.ts @@ -1,3 +1,4 @@ +import { timingSafeEqual } from "node:crypto"; import { NextRequest, NextResponse } from "next/server"; import { signSession, SESSION_COOKIE } from "@/lib/auth"; @@ -9,7 +10,13 @@ export async function POST(req: NextRequest) { return NextResponse.json({ error: { code: "auth_not_configured", message: "AUTH_SECRET saknas" } }, { status: 501 }); } const devKey = process.env.DEV_LOGIN_KEY; - if (!devKey || key !== devKey) { + // 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 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 }); } if (!email) { diff --git a/app/api/estimates/route.ts b/app/api/estimates/route.ts index d2709fa..0028688 100644 --- a/app/api/estimates/route.ts +++ b/app/api/estimates/route.ts @@ -11,6 +11,9 @@ export async function POST(req: NextRequest) { } catch { return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 }); } + if (!body || typeof body !== "object") { + return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 }); + } // Defer to the FastAPI data engine when it's running; fall back to local math. const eng = await engineFetch("/estimates", { method: "POST", body: JSON.stringify(body) }); diff --git a/app/api/orders/[id]/route.ts b/app/api/orders/[id]/route.ts index b59c063..2d6a248 100644 --- a/app/api/orders/[id]/route.ts +++ b/app/api/orders/[id]/route.ts @@ -19,6 +19,9 @@ export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: strin } catch { return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON" } }, { status: 400 }); } + if (!body || typeof body !== "object") { + return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 }); + } const allowed = ["draft", "quoted", "deposit_pending", "in_production", "review", "revision", "accepted", "delivered"]; if (!body.status || !allowed.includes(body.status)) { return NextResponse.json({ error: { code: "bad_status", message: "Ogiltig status" } }, { status: 400 }); diff --git a/app/api/orders/route.ts b/app/api/orders/route.ts index c0c1183..a4cf033 100644 --- a/app/api/orders/route.ts +++ b/app/api/orders/route.ts @@ -9,6 +9,9 @@ export async function POST(req: NextRequest) { } catch { return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON" } }, { status: 400 }); } + if (!body || typeof body !== "object") { + return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON body" } }, { status: 400 }); + } const flow = body.flow || "custom"; const config = body.config || {}; const order = await createOrder(flow, config); diff --git a/app/api/payments/[order_id]/deposit/route.ts b/app/api/payments/[order_id]/deposit/route.ts index 5d9843e..b732790 100644 --- a/app/api/payments/[order_id]/deposit/route.ts +++ b/app/api/payments/[order_id]/deposit/route.ts @@ -1,4 +1,5 @@ import { NextRequest, NextResponse } from "next/server"; +import { getOrder } from "@/lib/orders-store"; // POST /api/payments/[order_id]/deposit // Returns { url } for Stripe Checkout. Returns 501 when STRIPE_SECRET_KEY is absent. @@ -13,19 +14,15 @@ export async function POST( return NextResponse.json({ error: "payment_not_configured" }, { status: 501 }); } - const origin = - request.headers.get("origin") ?? - process.env.NEXT_PUBLIC_APP_URL ?? - "http://localhost:3000"; + // Never derive from the client-supplied Origin header (SSRF + open-redirect vector) — + // request.nextUrl.origin reflects the actual request URL, not attacker-controlled input. + const origin = request.nextUrl.origin; - let depositOre = 44750; - try { - const orderRes = await fetch(`${origin}/api/orders/${order_id}`); - if (orderRes.ok) { - const order = (await orderRes.json()) as { deposit_ore?: number; total_ore?: number }; - depositOre = order.deposit_ore ?? Math.round((order.total_ore ?? 89500) / 2); - } - } catch {} + const order = await getOrder(order_id); + if (!order) { + return NextResponse.json({ error: { code: "not_found", message: "Order saknas" } }, { status: 404 }); + } + const depositOre = order.deposit_ore ?? Math.round((order.total_ore ?? 89500) / 2); const body = new URLSearchParams({ "payment_method_types[0]": "card", diff --git a/app/api/subscriptions/route.ts b/app/api/subscriptions/route.ts index ffab6f4..2846da1 100644 --- a/app/api/subscriptions/route.ts +++ b/app/api/subscriptions/route.ts @@ -7,7 +7,8 @@ export async function GET() { } export async function POST(req: NextRequest) { - const body = await req.json().catch(() => ({})); + const parsed = await req.json().catch(() => ({})); + const body = parsed && typeof parsed === "object" ? parsed : {}; if (!body.order_id) { return NextResponse.json({ error: { code: "bad_request", message: "order_id krävs" } }, { status: 400 }); } diff --git a/app/api/uploads/route.ts b/app/api/uploads/route.ts index e960d21..ce533f8 100644 --- a/app/api/uploads/route.ts +++ b/app/api/uploads/route.ts @@ -1,4 +1,4 @@ -import { NextRequest, NextResponse } from "next/server"; +import { NextResponse } from "next/server"; // GET /api/uploads — list uploaded files. Returns 501 until storage is configured. export async function GET() { @@ -10,9 +10,10 @@ export async function GET() { } // POST /api/uploads (docs/04) — issue a presigned R2 PUT URL. Env-guarded: -// returns 501 until R2 storage is configured. Client then PUTs the file directly. -export async function POST(req: NextRequest) { - const body = await req.json().catch(() => ({})); +// returns 501 until R2 storage is configured, and until presign generation +// is implemented — a configured-but-unimplemented state must not report +// success. Client then PUTs the file directly. +export async function POST() { const haveR2 = process.env.R2_ACCESS_KEY_ID && process.env.R2_BUCKET && process.env.R2_ENDPOINT; if (!haveR2) { return NextResponse.json( @@ -20,6 +21,10 @@ export async function POST(req: NextRequest) { { status: 501 }, ); } - // With R2 configured: build a presigned PUT (S3-compatible) and return it. - return NextResponse.json({ file_id: crypto.randomUUID(), put_url: null, name: body?.name ?? null }); + // TODO: presigned PUT generation not implemented yet — keep returning 501 + // instead of a fake 200/null success shape until real R2 presign wiring exists. + return NextResponse.json( + { error: { code: "storage_not_configured", message: "Presignerad uppladdning är inte implementerad än" } }, + { status: 501 }, + ); } diff --git a/app/api/vehicles/route.ts b/app/api/vehicles/route.ts index ee0dc1a..be3d78e 100644 --- a/app/api/vehicles/route.ts +++ b/app/api/vehicles/route.ts @@ -4,14 +4,14 @@ import { engineFetch } from "@/lib/engine"; // 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, ""); + 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 eng = await engineFetch(`/vehicles/${plate}`); if (eng && eng.ok) return NextResponse.json(await eng.json()); try { - const r = await fetch(`https://opendata.rdw.nl/resource/m9d7-ebf2.json?kenteken=${plate}`, { + 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", }); diff --git a/app/order/[id]/page.tsx b/app/order/[id]/page.tsx index 29cdcb2..bdc0b12 100644 --- a/app/order/[id]/page.tsx +++ b/app/order/[id]/page.tsx @@ -65,6 +65,10 @@ export default function ProductionPage() { }, [id]); const finish = () => { + if (timer.current) { + clearInterval(timer.current); + timer.current = null; + } setProgress([100, 100, 100, 100, 100]); setMarkets([100, 100, 100, 100]); setConf(94); diff --git a/lib/orders-store.ts b/lib/orders-store.ts index c54ca61..9afbcf7 100644 --- a/lib/orders-store.ts +++ b/lib/orders-store.ts @@ -30,6 +30,21 @@ export interface Order { // Non-durable fallback used only until a database is provisioned. const mem = new Map(); +// postgres.js (pinned v3.4.9) returns bigint (total_ore/deposit_ore/balance_ore) +// and numeric (est_confidence) columns as strings by default, not JS numbers. +// Coerce only these four fields on rows read back from SQL -- not the shared +// `sql` client's global type map, which would silently affect every other +// table's bigint/numeric columns too (e.g. jobs.pct, deliveries.avg_confidence). +function coerceOrder(row: Order): Order { + return { + ...row, + total_ore: Number(row.total_ore), + deposit_ore: Number(row.deposit_ore), + balance_ore: Number(row.balance_ore), + est_confidence: Number(row.est_confidence), + }; +} + function estimateFor(config: OrderConfig) { return computeEstimate({ markets: config.markets ?? [], @@ -74,7 +89,7 @@ export async function getOrder(id: string): Promise { const rows = await sql` SELECT order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at FROM orders WHERE order_id::text = ${id} LIMIT 1`; - return rows[0] ?? null; + return rows[0] ? coerceOrder(rows[0]) : null; } return mem.get(id) ?? null; } @@ -82,9 +97,10 @@ export async function getOrder(id: string): Promise { export async function listOrders(): Promise { const sql = getSql(); if (sql) { - return sql` + const rows = await sql` SELECT order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at FROM orders ORDER BY created_at DESC LIMIT 100`; + return rows.map(coerceOrder); } return [...mem.values()].sort((a, b) => b.created_at.localeCompare(a.created_at)); } @@ -95,7 +111,7 @@ export async function setStatus(id: string, status: string): Promise` UPDATE orders SET status = ${status}, updated_at = now() WHERE order_id::text = ${id} RETURNING order_id, flow, status, config, total_ore, deposit_ore, balance_ore, est_days, est_confidence, created_at`; - return rows[0] ?? null; + return rows[0] ? coerceOrder(rows[0]) : null; } const o = mem.get(id); if (o) { o.status = status; mem.set(id, o); } diff --git a/lib/subscriptions-store.ts b/lib/subscriptions-store.ts index cbea605..0747770 100644 --- a/lib/subscriptions-store.ts +++ b/lib/subscriptions-store.ts @@ -32,5 +32,5 @@ export async function listSubscriptions(): Promise { if (sql) { return sql`SELECT sub_id, order_id, cadence, webhook_url, status, next_run_at, created_at FROM subscriptions ORDER BY created_at DESC LIMIT 100`; } - return [...mem.values()]; + return [...mem.values()].sort((a, b) => b.created_at.localeCompare(a.created_at)); } diff --git a/services/api/orchestrator/main.py b/services/api/orchestrator/main.py index 321941e..5cf0f4e 100644 --- a/services/api/orchestrator/main.py +++ b/services/api/orchestrator/main.py @@ -26,6 +26,16 @@ app.add_middleware( _SOURCES = yaml.safe_load((Path(__file__).resolve().parent.parent / "sources" / "sources.yaml").read_text(encoding="utf-8"))["sources"] + +def _coerce_int(v: Any, default: int) -> int: + """int(v) raises on decimal-formatted strings/floats; coerce via float() first + and fall back to `default` on any unparseable, client-controlled input instead + of a 500.""" + try: + return int(float(v)) + except (TypeError, ValueError): + return default + # ── estimate model (mirrors apps/web lib/data.computeEstimate) ─────────────── FIELD_RATE = 240 ENTITY_MULT = {"Bolag": 1.0, "Beslutsfattare": 1.4, "Fordon": 1.2} @@ -90,13 +100,19 @@ async def sources_for(market: str): @app.get("/vehicles/{plate}") async def vehicle(plate: str): - v = await rdw_vehicle(plate) + try: + v = await rdw_vehicle(plate) + except Exception: + v = None return v or {"vehicle": None} @app.get("/screen") async def screen(q: str): - return await opensanctions_screen(q) + try: + return await opensanctions_screen(q) + except Exception: + return {"matches": [], "source": "opensanctions"} @app.post("/estimates") @@ -111,9 +127,9 @@ async def create_order(body: OrderIn): entity_type=body.config.get("type", "Bolag"), fields=body.config.get("fieldIds", []), enrichment=body.config.get("enrichmentIds", []), - volume=int(body.config.get("volume", 1000)), + volume=_coerce_int(body.config.get("volume", 1000), 1000), frequency=body.config.get("frequency", "Engångs"), - confidence_target=int(body.config.get("confidence", 92)), + confidence_target=_coerce_int(body.config.get("confidence", 92), 92), )) oid = str(uuid.uuid4()) _ORDERS[oid] = {"order_id": oid, "flow": body.flow, "status": "draft", "config": body.config, **est} diff --git a/services/api/workers/pipeline.py b/services/api/workers/pipeline.py index b30ebad..f503f91 100644 --- a/services/api/workers/pipeline.py +++ b/services/api/workers/pipeline.py @@ -43,7 +43,12 @@ async def _fetch(source_id: str, key: str) -> CompanyResult | None: async def run_job(order_id: str, config: dict[str, Any]) -> dict[str, Any]: markets: list[str] = config.get("markets", []) or ["NO"] threshold = float(config.get("confidence", 92)) / 100.0 - seeds: dict[str, list[str]] = config.get("seeds") or DEMO_SEEDS + # Use caller-supplied seeds when present (an explicit empty {} is honoured so a + # real job is never silently backfilled with DEMO_SEEDS), but treat an explicit + # null the same as "missing" -- `config.get("seeds") is not None` avoids a 500 + # (None.get) on client-controlled `{"seeds": null}`, which the old `... or ...` + # idiom tolerated and the `"seeds" in config` form regressed. + seeds: dict[str, list[str]] = config["seeds"] if config.get("seeds") is not None else DEMO_SEEDS records: list[dict[str, Any]] = [] per_market: dict[str, int] = {} diff --git a/services/api/workers/resolve.py b/services/api/workers/resolve.py index 92330fd..9927436 100644 --- a/services/api/workers/resolve.py +++ b/services/api/workers/resolve.py @@ -24,10 +24,28 @@ def resolve(records: list[dict[str, Any]], threshold: int = 92) -> list[dict[str match = o break if match: - # corroboration: independent source agreeing bumps confidence + level - match["confidence"] = min(0.99, match.get("confidence", 0.0) + 0.1) - match["agreed_sources"] = match.get("agreed_sources", 1) + 1 match.setdefault("merged_from", []).append(r.get("source")) + # Merge the losing record's per-field provenance regardless of source + # novelty below, so the surviving record's provenance always reflects + # every contributing record's fields. + existing_provenance = match.setdefault("provenance", []) + seen_provenance = {(p.get("field_name"), p.get("source_id")) for p in existing_provenance} + for p in r.get("provenance", []): + key = (p.get("field_name"), p.get("source_id")) + if key not in seen_provenance: + existing_provenance.append(p) + seen_provenance.add(key) + # Corroboration (confidence/agreed_sources bump) requires an + # *independent* source — two hits from the same connector must not + # count as two agreeing sources. + seen_sources = match.setdefault("_sources_seen", {match.get("source")} - {None}) + src = r.get("source") + if src is not None and src not in seen_sources: + match["confidence"] = min(0.99, match.get("confidence", 0.0) + 0.1) + match["agreed_sources"] = match.get("agreed_sources", 1) + 1 + seen_sources.add(src) else: - out.append({**r, "agreed_sources": 1}) + out.append({**r, "agreed_sources": 1, "_sources_seen": {r.get("source")} - {None}}) + for o in out: + o.pop("_sources_seen", None) return out diff --git a/src/adapters/document-intelligence-adapter.ts b/src/adapters/document-intelligence-adapter.ts index e841b99..2d030f8 100644 --- a/src/adapters/document-intelligence-adapter.ts +++ b/src/adapters/document-intelligence-adapter.ts @@ -162,6 +162,10 @@ export class DocumentIntelligenceAdapter { for (let i = 0; i < maxPollAttempts; i++) { await sleep(pollIntervalMs); const pollRes = await fetch(operationLocation, { headers: { "Ocp-Apim-Subscription-Key": this.config.apiKey } }); + if (!pollRes.ok) { + const text = await pollRes.text().catch(() => ""); + throw new Error(`Document Intelligence poll request failed: ${pollRes.status} ${text.slice(0, 300)}`); + } const json = (await pollRes.json()) as Record; if (json.status === "succeeded") { payload = json; diff --git a/src/services/external-writeback-service.ts b/src/services/external-writeback-service.ts index e8c893d..eb2d753 100644 --- a/src/services/external-writeback-service.ts +++ b/src/services/external-writeback-service.ts @@ -18,7 +18,11 @@ * `writeExternalRecord` runs, a human has already approved the write -- this * service still re-checks CL0UD policy (per docs/PRODUCT_PLAN.md section * 4.1's hard rule that CL0UD is always re-consulted, the same rule - * quality-check-service.ts/document-extraction-service.ts already follow), + * document-extraction-service.ts already follows -- confirmed by grepping + * this repo's src/services/ for evaluatePolicy()/Cl0udClient usage; the + * only other real service that does the same is iceberg-write-service.ts. + * An earlier version of this comment also cited `quality-check-service.ts` + * here; that file does not exist anywhere in this repo), * but does not itself re-verify the upstream Approval record (ACT0 owns * approvals; 0pt's own capability boundary is "did CL0UD say yes for THIS * call", same separation of concerns every other 0pt service in this repo diff --git a/src/services/lakehouse-mapping-registry.ts b/src/services/lakehouse-mapping-registry.ts new file mode 100644 index 0000000..9562487 --- /dev/null +++ b/src/services/lakehouse-mapping-registry.ts @@ -0,0 +1,19 @@ +import { DatasetService } from "./dataset-service"; +import { DatasetIcebergMappingService } from "./dataset-iceberg-mapping-service"; +import { IcebergWriteService } from "./iceberg-write-service"; + +/** + * Shared singleton instances for the lakehouse-mapping route group + * (app/api/0pt/lakehouse/mappings/*). Previously each route file in that + * group instantiated its own DatasetService/DatasetIcebergMappingService/ + * IcebergWriteService, so a mapping created via POST /mappings was invisible + * to GET /mappings/{id} and to POST /mappings/{id}/writes within the same + * server process (each held a distinct in-memory Map). Constructing all + * three here once, wired together, and importing them everywhere fixes that + * -- matching the in-memory-per-module convention this repo already uses + * elsewhere (see document-capture-service.ts's own singleton note), just + * applied consistently across this route group instead of per-file. + */ +export const datasetService = new DatasetService(); +export const mappingService = new DatasetIcebergMappingService({ datasetService }); +export const writeService = new IcebergWriteService({ datasetService, mappingService });