fix(recovery): restore source removed by production documentation merge
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* app/api/0pt/canonical/facts/route.ts
|
||||
* ====================================
|
||||
* POST — canonical structured-observation write (entities/facts/relations).
|
||||
* GET — tenant-scoped read for consumers (products, agents, L0RE projection).
|
||||
*
|
||||
* 0pt owns observed facts; L0RE owns epistemic propositions/projections and
|
||||
* consumes this API. Tenant is always cross-checked against the verified
|
||||
* principal (assertTenantMatchesVerified), never trusted from the body alone.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { canonicalWriteSchema, parseBody } from "@/src/validation/0pt-schemas";
|
||||
import { canonicalFactService } from "@/src/services/canonical-fact-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const parsed = parseBody(canonicalWriteSchema, await request.json());
|
||||
if (!parsed.ok) return NextResponse.json(parsed.body, { status: parsed.status });
|
||||
const body = parsed.data;
|
||||
const guard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (guard) return guard;
|
||||
const result = await canonicalFactService.write(body);
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
const limitRaw = searchParams.get("limit");
|
||||
const facts = await canonicalFactService.query({
|
||||
tenant_id: tenantId,
|
||||
entity_id: searchParams.get("entity_id") ?? undefined,
|
||||
entity_type: searchParams.get("entity_type") ?? undefined,
|
||||
identity_namespace: searchParams.get("identity_namespace") ?? undefined,
|
||||
identity_value: searchParams.get("identity_value") ?? undefined,
|
||||
predicate: searchParams.get("predicate") ?? undefined,
|
||||
limit: limitRaw ? Number(limitRaw) : undefined,
|
||||
});
|
||||
return NextResponse.json({ facts });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { ensureTrialCredits, readTrialCredits } from '@/src/document-workbench/trial-credits';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/** GET /api/0pt/credits/balance — the authenticated tenant's credit balance. */
|
||||
export async function GET(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
|
||||
const url = repositoryDatabaseUrl();
|
||||
if (!url) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_NOT_CONFIGURED',
|
||||
message: 'Credits are not available until the database is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const ledger = new PostgresCreditLedger(getRepositorySql(url));
|
||||
const trial = readTrialCredits();
|
||||
if (trial > 0) await ensureTrialCredits(ledger, verified.scope.tenantId, trial);
|
||||
const balance = await ledger.balance(verified.scope.tenantId);
|
||||
return NextResponse.json({ tenant_id: verified.scope.tenantId, ...balance });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Credit balance unavailable';
|
||||
const notConfigured = /RLS-enforced|isolation migration/i.test(message);
|
||||
return NextResponse.json(
|
||||
{ error: notConfigured ? 'CREDITS_NOT_CONFIGURED' : 'CREDITS_UNAVAILABLE', message },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { getStripe } from '@/lib/stripe';
|
||||
import { PostgresCreditPurchaseStore } from '@/src/document-workbench/credit-purchase-store';
|
||||
import { findPack, readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { isValidScopeId, resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
function appBaseUrl(request: NextRequest): string {
|
||||
const configured = process.env.NEXT_PUBLIC_APP_URL;
|
||||
if (configured && /^https:\/\//.test(configured)) return configured.replace(/\/+$/, '');
|
||||
return request.nextUrl.origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/0pt/credits/checkout { pack_id }
|
||||
*
|
||||
* Creates a Stripe Checkout Session and stores the server-owned price snapshot
|
||||
* BEFORE any credit exists. Credits are granted only when the Stripe webhook
|
||||
* re-reads the session and its payment intent and the ledger accepts the
|
||||
* idempotent verified-payment command.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
const { tenantId } = verified.scope;
|
||||
|
||||
if (process.env.OPT_CREDITS_MODE === 'off') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_DISABLED',
|
||||
message: 'Billing is not active yet (pilot mode). No payment can be taken.',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const book = readCreditPriceBook();
|
||||
if (!book) {
|
||||
return NextResponse.json(
|
||||
{ error: 'PRICE_BOOK_NOT_CONFIGURED', message: 'Credit purchases are not available yet' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return NextResponse.json(
|
||||
{ error: 'STRIPE_NOT_CONFIGURED', message: 'Payments are not available yet' },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const databaseUrl = repositoryDatabaseUrl();
|
||||
if (!databaseUrl) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_NOT_CONFIGURED',
|
||||
message: 'Credits are not available until the database is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'INVALID_BODY', message: 'JSON body required' }, { status: 400 });
|
||||
}
|
||||
const packId = (body as { pack_id?: unknown } | null)?.pack_id;
|
||||
if (typeof packId !== 'string' || !isValidScopeId(packId)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_PACK', message: 'A valid pack_id is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const pack = findPack(book, packId);
|
||||
if (!pack) {
|
||||
return NextResponse.json({ error: 'UNKNOWN_PACK', message: 'Unknown credit pack' }, { status: 404 });
|
||||
}
|
||||
|
||||
const purchaseId = crypto.randomUUID();
|
||||
const base = appBaseUrl(request);
|
||||
const metadata = {
|
||||
kind: '0pt_credit_purchase',
|
||||
tenant_id: tenantId,
|
||||
purchase_id: purchaseId,
|
||||
price_book_version: book.version,
|
||||
};
|
||||
|
||||
let session;
|
||||
try {
|
||||
session = await stripe.checkout.sessions.create({
|
||||
mode: 'payment',
|
||||
client_reference_id: tenantId,
|
||||
line_items: [
|
||||
{
|
||||
quantity: 1,
|
||||
price_data: {
|
||||
currency: book.currency.toLowerCase(),
|
||||
unit_amount: pack.amountMinor,
|
||||
product_data: { name: `${pack.credits} 0pt credits` },
|
||||
},
|
||||
},
|
||||
],
|
||||
metadata,
|
||||
payment_intent_data: { metadata },
|
||||
success_url: `${base}/portal/krediter?status=success&purchase=${encodeURIComponent(purchaseId)}`,
|
||||
cancel_url: `${base}/portal/krediter?status=cancelled`,
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: 'CHECKOUT_UNAVAILABLE', message: 'The payment provider could not start a checkout' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await new PostgresCreditPurchaseStore(getRepositorySql(databaseUrl)).create({
|
||||
tenantId,
|
||||
purchaseId,
|
||||
checkoutSessionId: session.id,
|
||||
amountMinor: pack.amountMinor,
|
||||
currency: book.currency,
|
||||
credits: pack.credits,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
// Never leave a payable session with no server-side snapshot behind it.
|
||||
try {
|
||||
await stripe.checkout.sessions.expire(session.id);
|
||||
} catch {
|
||||
/* best effort; the webhook will refuse the unmatched session */
|
||||
}
|
||||
const message = error instanceof Error ? error.message : 'Credit purchase could not be stored';
|
||||
return NextResponse.json({ error: 'CREDITS_NOT_CONFIGURED', message }, { status: 503 });
|
||||
}
|
||||
|
||||
if (!session.url) {
|
||||
return NextResponse.json(
|
||||
{ error: 'CHECKOUT_UNAVAILABLE', message: 'The payment provider returned no checkout URL' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
purchase_id: purchaseId,
|
||||
checkout_url: session.url,
|
||||
credits: pack.credits,
|
||||
amount_minor: pack.amountMinor,
|
||||
currency: book.currency,
|
||||
},
|
||||
{ status: 201 },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
/**
|
||||
* GET /api/0pt/credits/packs — sellable credit packs from the server-owned
|
||||
* price book. No price is ever accepted from the client.
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
|
||||
const book = readCreditPriceBook();
|
||||
if (!book) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'PRICE_BOOK_NOT_CONFIGURED',
|
||||
message: 'Credit packs are not available until the server price book is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
version: book.version,
|
||||
currency: book.currency,
|
||||
purchases_enabled: process.env.OPT_CREDITS_MODE !== 'off',
|
||||
packs: book.packs.map((pack) => ({
|
||||
id: pack.id,
|
||||
credits: pack.credits,
|
||||
amount_minor: pack.amountMinor,
|
||||
})),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
import { datasetService } from "@/src/services/datasets";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ datasetId: string }> },
|
||||
) {
|
||||
try {
|
||||
const { datasetId } = await params;
|
||||
const tenantId = new URL(request.url).searchParams.get("tenant_id")?.trim();
|
||||
if (!tenantId) throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "tenant_id is required");
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
|
||||
const dataset = await datasetService.getDataset(datasetId);
|
||||
if (dataset.tenant_id !== tenantId) {
|
||||
throw new SiaxError("NOT_FOUND", "0pt.dataset", `dataset ${datasetId} not found`);
|
||||
}
|
||||
return NextResponse.json(dataset);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
import { datasetVersionService } from "@/src/services/datasets";
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ datasetId: string; version: string }> },
|
||||
) {
|
||||
try {
|
||||
const { datasetId, version: rawVersion } = await params;
|
||||
const tenantId = new URL(request.url).searchParams.get("tenant_id")?.trim();
|
||||
if (!tenantId) throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "tenant_id is required");
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
|
||||
const version = Number(rawVersion);
|
||||
if (!Number.isSafeInteger(version) || version < 1) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "version must be a positive integer");
|
||||
}
|
||||
return NextResponse.json(await datasetVersionService.getVersion(datasetId, tenantId, version));
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
import { datasetVersionService } from "@/src/services/datasets";
|
||||
|
||||
function required(body: Record<string, unknown>, field: string): string {
|
||||
const value = body[field];
|
||||
if (typeof value !== "string" || !value.trim()) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", `${field} is required`);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ datasetId: string }> },
|
||||
) {
|
||||
try {
|
||||
const { datasetId } = await params;
|
||||
const raw = await request.json();
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "JSON object body is required");
|
||||
}
|
||||
const body = raw as Record<string, unknown>;
|
||||
const tenantId = required(body, "tenant_id");
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
if (!Array.isArray(body.artifact_refs) || !body.artifact_refs.every((value) => typeof value === "string")) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "artifact_refs must be a string array");
|
||||
}
|
||||
|
||||
const recordCount = body.record_count === undefined ? undefined : Number(body.record_count);
|
||||
const idempotencyKey = request.headers.get("idempotency-key")?.trim()
|
||||
|| (typeof body.idempotency_key === "string" ? body.idempotency_key.trim() : "")
|
||||
|| undefined;
|
||||
|
||||
const version = await datasetVersionService.createVersion({
|
||||
dataset_id: datasetId,
|
||||
tenant_id: tenantId,
|
||||
project_id: required(body, "project_id"),
|
||||
artifact_refs: body.artifact_refs,
|
||||
schema_version: required(body, "schema_version"),
|
||||
...(recordCount === undefined ? {} : { record_count: recordCount }),
|
||||
...(typeof body.description === "string" && body.description.trim()
|
||||
? { description: body.description.trim() }
|
||||
: {}),
|
||||
created_by: request.headers.get("x-0pt-verified-sub") ?? "local-dev",
|
||||
...(typeof body.correlation_id === "string" && body.correlation_id.trim()
|
||||
? { correlation_id: body.correlation_id.trim() }
|
||||
: {}),
|
||||
...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),
|
||||
});
|
||||
return NextResponse.json(version, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ datasetId: string }> },
|
||||
) {
|
||||
try {
|
||||
const { datasetId } = await params;
|
||||
const tenantId = new URL(request.url).searchParams.get("tenant_id")?.trim();
|
||||
if (!tenantId) throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "tenant_id is required");
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
return NextResponse.json(await datasetVersionService.listVersions(datasetId, tenantId));
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
import { datasetService } from "@/src/services/datasets";
|
||||
import type { DatasetStatus, DatasetType } from "@/src/types/dataset";
|
||||
|
||||
const DATASET_TYPES = new Set<DatasetType>(["raw", "structured", "enriched", "curated", "feature", "derived"]);
|
||||
const DATASET_STATUSES = new Set<DatasetStatus>(["active", "archived", "deprecated"]);
|
||||
|
||||
function actorId(request: NextRequest): string {
|
||||
return request.headers.get("x-0pt-verified-sub") ?? "local-dev";
|
||||
}
|
||||
|
||||
function stringField(body: Record<string, unknown>, field: string): string {
|
||||
const value = body[field];
|
||||
if (typeof value !== "string" || !value.trim()) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", `${field} is required`);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const raw = await request.json();
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "JSON object body is required");
|
||||
}
|
||||
const body = raw as Record<string, unknown>;
|
||||
const tenantId = stringField(body, "tenant_id");
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
|
||||
const datasetType = stringField(body, "dataset_type") as DatasetType;
|
||||
if (!DATASET_TYPES.has(datasetType)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "unsupported dataset_type");
|
||||
}
|
||||
const status = body.status === undefined ? undefined : String(body.status) as DatasetStatus;
|
||||
if (status !== undefined && !DATASET_STATUSES.has(status)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "unsupported status");
|
||||
}
|
||||
|
||||
const dataset = await datasetService.registerDataset({
|
||||
dataset_id: stringField(body, "dataset_id"),
|
||||
tenant_id: tenantId,
|
||||
project_id: stringField(body, "project_id"),
|
||||
name: stringField(body, "name"),
|
||||
dataset_type: datasetType,
|
||||
...(status ? { status } : {}),
|
||||
...(typeof body.description === "string" && body.description.trim()
|
||||
? { description: body.description.trim() }
|
||||
: {}),
|
||||
...(typeof body.correlation_id === "string" && body.correlation_id.trim()
|
||||
? { correlation_id: body.correlation_id.trim() }
|
||||
: {}),
|
||||
created_by: actorId(request),
|
||||
});
|
||||
return NextResponse.json(dataset, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id")?.trim();
|
||||
if (!tenantId) throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "tenant_id is required");
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
|
||||
const typeRaw = searchParams.get("dataset_type") ?? undefined;
|
||||
const statusRaw = searchParams.get("status") ?? undefined;
|
||||
if (typeRaw && !DATASET_TYPES.has(typeRaw as DatasetType)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "unsupported dataset_type");
|
||||
}
|
||||
if (statusRaw && !DATASET_STATUSES.has(statusRaw as DatasetStatus)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.dataset", "unsupported status");
|
||||
}
|
||||
|
||||
return NextResponse.json(await datasetService.listDatasets({
|
||||
tenant_id: tenantId,
|
||||
project_id: searchParams.get("project_id") ?? undefined,
|
||||
dataset_type: typeRaw as DatasetType | undefined,
|
||||
status: statusRaw as DatasetStatus | undefined,
|
||||
}));
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
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";
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
|
||||
try {
|
||||
const { documentId } = await params;
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(documentExtractionSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
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(),
|
||||
model_id: body.model_id,
|
||||
});
|
||||
return NextResponse.json(result, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ documentId: string }> }) {
|
||||
try {
|
||||
const { documentId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const extractions = await documentExtractionService.listExtractionsForDocument(documentId, tenantId);
|
||||
return NextResponse.json(extractions);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return NextResponse.json({ error: message }, { status: 404 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
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";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(documentCaptureSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
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: {
|
||||
tenantId: body.mailbox?.tenant_id,
|
||||
clientId: body.mailbox?.client_id,
|
||||
clientSecret: body.mailbox?.client_secret,
|
||||
mailboxAddress: body.mailbox?.mailbox_address,
|
||||
folder: body.mailbox?.folder,
|
||||
},
|
||||
since_iso: body.since_iso,
|
||||
top: body.top,
|
||||
max_pages: body.max_pages,
|
||||
},
|
||||
{
|
||||
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 ?? "",
|
||||
correlation_id: body.correlation_id ?? "",
|
||||
},
|
||||
);
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
// P014: `tenant_id` used to be optional here, and
|
||||
// DocumentCaptureService.listDocuments treats an absent tenant_id filter as
|
||||
// "no restriction" — so calling this with no query params at all returned
|
||||
// EVERY tenant's captured documents to any authenticated caller. Every
|
||||
// sibling list/get route in this file already requires tenant_id; this was
|
||||
// the one outlier. Now required, same as the rest of the surface.
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const projectId = searchParams.get("project_id") ?? undefined;
|
||||
const documents = await documentCaptureService.listDocuments({ tenant_id: tenantId, project_id: projectId });
|
||||
return NextResponse.json(documents);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
import { NextResponse, type NextRequest } from 'next/server';
|
||||
import { Doc0SourceClient, Doc0SourceUnavailableError } from '@/src/document-workbench/doc0-source-client';
|
||||
import { Inf0OutcomeUnknownError } from '@/src/document-workbench/inf0-gateway-client';
|
||||
import { createInf0Gateway } from '@/src/document-workbench/inf0-gateway';
|
||||
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
||||
import { ensureTrialCredits, readTrialCredits } from '@/src/document-workbench/trial-credits';
|
||||
import { creditsForUsage, readCreditPriceBook } from '@/src/document-workbench/price-book';
|
||||
import { structureDocument } from '@/src/document-workbench/structure-document';
|
||||
import { exportValidatedOutput } from '@/src/document-workbench/export-validated-output';
|
||||
import type {
|
||||
OutputFieldContract,
|
||||
OutputFieldType,
|
||||
} from '@/src/document-workbench/structured-output-validation';
|
||||
import { readDocumentWorkbenchRuntime } from '@/src/document-workbench/runtime-config';
|
||||
import { createProjectAuthorizer } from '@/src/document-workbench/project-access';
|
||||
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
||||
import { isValidScopeId, resolveVerifiedScope } from '@/src/http/verified-scope';
|
||||
|
||||
export const runtime = 'nodejs';
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const FIELD_TYPES: readonly OutputFieldType[] = ['string', 'integer', 'boolean', 'decimal', 'date'];
|
||||
const DATA_CLASSES = ['none', 'low', 'medium', 'high', 'restricted'] as const;
|
||||
|
||||
function csv(value: string | undefined): string[] {
|
||||
return (value ?? '')
|
||||
.split(',')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function modelPolicy() {
|
||||
const allowedModelIds = csv(process.env.OPT_ALLOWED_MODELS);
|
||||
const allowedDataClasses = csv(process.env.OPT_ALLOWED_DATA_CLASSES);
|
||||
const destination = process.env.OPT_MODEL_DESTINATION;
|
||||
const maxInputTokens = Number(process.env.OPT_MODEL_MAX_INPUT_TOKENS ?? '0');
|
||||
const maxOutputTokens = Number(process.env.OPT_MODEL_MAX_OUTPUT_TOKENS ?? '0');
|
||||
if (
|
||||
allowedModelIds.length === 0 ||
|
||||
allowedDataClasses.length === 0 ||
|
||||
(destination !== 'internal' && destination !== 'external') ||
|
||||
!Number.isSafeInteger(maxInputTokens) ||
|
||||
maxInputTokens <= 0 ||
|
||||
!Number.isSafeInteger(maxOutputTokens) ||
|
||||
maxOutputTokens <= 0
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
allowedModelIds,
|
||||
allowedDataClasses,
|
||||
destination: destination as 'internal' | 'external',
|
||||
externalTransferAllowed: process.env.OPT_EXTERNAL_TRANSFER_ALLOWED === 'true',
|
||||
maxInputTokens,
|
||||
maxOutputTokens,
|
||||
};
|
||||
}
|
||||
|
||||
function parseFields(raw: unknown): OutputFieldContract[] | undefined {
|
||||
if (!Array.isArray(raw) || raw.length === 0 || raw.length > 100) return undefined;
|
||||
const fields: OutputFieldContract[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const item of raw) {
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) return undefined;
|
||||
const field = item as Record<string, unknown>;
|
||||
if (
|
||||
typeof field.name !== 'string' ||
|
||||
!/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(field.name) ||
|
||||
seen.has(field.name) ||
|
||||
typeof field.type !== 'string' ||
|
||||
!FIELD_TYPES.includes(field.type as OutputFieldType)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
seen.add(field.name);
|
||||
fields.push({ name: field.name, type: field.type as OutputFieldType, required: true });
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
interface StructureBody {
|
||||
project_id?: unknown;
|
||||
document_id?: unknown;
|
||||
version_id?: unknown;
|
||||
checksum_sha256?: unknown;
|
||||
pipeline_stage?: unknown;
|
||||
instruction?: unknown;
|
||||
fields?: unknown;
|
||||
model_id?: unknown;
|
||||
data_class?: unknown;
|
||||
format?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/0pt/documents/structure
|
||||
*
|
||||
* Upload → DOC0 segments → INF0 model → mechanically validated, evidence-bound
|
||||
* output (optionally exported). Credits are reserved before the model runs and
|
||||
* settled to the measured usage afterwards.
|
||||
*
|
||||
* Nothing is trusted from the client except the requested target fields and
|
||||
* instruction. Source text is re-read from DOC0 and every returned value must
|
||||
* point at an exact span in that text.
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
const verified = resolveVerifiedScope(request);
|
||||
if ('response' in verified) return verified.response;
|
||||
const { tenantId, actorId } = verified.scope;
|
||||
|
||||
const runtimeConfig = readDocumentWorkbenchRuntime();
|
||||
const gateway = createInf0Gateway();
|
||||
if (!runtimeConfig.doc0 || !gateway) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'WORKBENCH_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until DOC0 and INF0 are configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
const policy = modelPolicy();
|
||||
if (!policy) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'MODEL_POLICY_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until the model policy is configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
// Explicit pilot switch: `OPT_CREDITS_MODE=off` runs structuring without a
|
||||
// wallet. It is deliberately NOT a silent fallback — the response reports
|
||||
// `credits: null` and the operator has named the mode.
|
||||
const creditsEnabled =
|
||||
process.env.OPT_CREDITS_MODE !== 'off' &&
|
||||
Boolean(readCreditPriceBook()) &&
|
||||
Boolean(repositoryDatabaseUrl());
|
||||
const priceBook = creditsEnabled ? readCreditPriceBook() : undefined;
|
||||
const databaseUrl = creditsEnabled ? repositoryDatabaseUrl() : undefined;
|
||||
if (!creditsEnabled && process.env.OPT_CREDITS_MODE !== 'off') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'CREDITS_NOT_CONFIGURED',
|
||||
message: 'Document structuring is not available until credits are configured',
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
let body: StructureBody;
|
||||
try {
|
||||
body = (await request.json()) as StructureBody;
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'INVALID_BODY', message: 'JSON body required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const projectId = body.project_id;
|
||||
const documentId = body.document_id;
|
||||
const versionId = body.version_id;
|
||||
const checksum = body.checksum_sha256;
|
||||
const pipelineStage = body.pipeline_stage;
|
||||
const instruction = body.instruction;
|
||||
const modelId = body.model_id;
|
||||
const dataClass = body.data_class ?? 'low';
|
||||
const format = body.format ?? 'json';
|
||||
|
||||
if (pipelineStage !== 'parsed') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'DOCUMENT_NOT_PARSED',
|
||||
message:
|
||||
'The document has no verified text layer yet (parse_failed or not parsed). OCR is required before structuring.',
|
||||
},
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
if (
|
||||
!isValidScopeId(projectId) ||
|
||||
!isValidScopeId(documentId) ||
|
||||
!isValidScopeId(versionId) ||
|
||||
typeof checksum !== 'string' ||
|
||||
!/^[0-9a-f]{64}$/.test(checksum) ||
|
||||
typeof instruction !== 'string' ||
|
||||
!instruction.trim() ||
|
||||
instruction.length > 4000 ||
|
||||
typeof modelId !== 'string' ||
|
||||
!policy.allowedModelIds.includes(modelId) ||
|
||||
typeof dataClass !== 'string' ||
|
||||
!(DATA_CLASSES as readonly string[]).includes(dataClass) ||
|
||||
(format !== 'json' && format !== 'csv')
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_REQUEST', message: 'Invalid document structure request' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const fields = parseFields(body.fields);
|
||||
if (!fields) {
|
||||
return NextResponse.json(
|
||||
{ error: 'INVALID_FIELDS', message: 'A valid field contract is required' },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const authorize = createProjectAuthorizer();
|
||||
if (!(await authorize({ tenantId, projectId, actorId }))) {
|
||||
return NextResponse.json(
|
||||
{ error: 'OPT_ACCESS_DENIED', message: 'Project access is not authorized' },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const correlationId = request.headers.get('x-request-id') ?? crypto.randomUUID();
|
||||
const context = {
|
||||
tenantId,
|
||||
projectId,
|
||||
actorId,
|
||||
capability: '0pt.document.structure.v1',
|
||||
correlationId,
|
||||
idempotencyKey: correlationId,
|
||||
};
|
||||
|
||||
let sources;
|
||||
try {
|
||||
sources = await new Doc0SourceClient({
|
||||
baseUrl: runtimeConfig.doc0.baseUrl,
|
||||
serviceToken: runtimeConfig.doc0.serviceToken,
|
||||
}).read({
|
||||
tenantId,
|
||||
projectId,
|
||||
actorId: runtimeConfig.doc0.actorId ?? actorId,
|
||||
requestId: correlationId,
|
||||
receipt: {
|
||||
documentId,
|
||||
versionId,
|
||||
checksumSha256: checksum,
|
||||
pipelineStage: 'parsed',
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Doc0SourceUnavailableError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'DOC0_SOURCE_UNAVAILABLE',
|
||||
message:
|
||||
'The extracted source could not be verified (version, checksum, page cap or tenant). Review or reconciliation is required.',
|
||||
},
|
||||
{ status: 422 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: 'DOC0_SOURCE_UNAVAILABLE', message: 'The extracted source is unavailable' },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
|
||||
console.log('[0pt-workbench] doc0 source read:', sources.sources.length, 'segments');
|
||||
const sourceChars = sources.sources.reduce((total, source) => total + source.text.length, 0);
|
||||
const estimatedInputTokens = Math.ceil(JSON.stringify(sources.sources).length / 4) + 1024;
|
||||
if (estimatedInputTokens > policy.maxInputTokens) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'SOURCE_TOO_LARGE',
|
||||
message: 'The document is larger than the configured model input limit',
|
||||
},
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
|
||||
const maximumCredits =
|
||||
creditsEnabled && priceBook
|
||||
? creditsForUsage(priceBook, {
|
||||
pages: Math.max(1, Math.ceil(sourceChars / 1800)),
|
||||
inputTokens: estimatedInputTokens,
|
||||
outputTokens: policy.maxOutputTokens,
|
||||
})
|
||||
: 0;
|
||||
const reservationId = crypto.randomUUID();
|
||||
const ledger =
|
||||
creditsEnabled && databaseUrl ? new PostgresCreditLedger(getRepositorySql(databaseUrl)) : undefined;
|
||||
if (ledger) {
|
||||
try {
|
||||
await ensureTrialCredits(ledger, tenantId, readTrialCredits());
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `reserve:${reservationId}`,
|
||||
kind: 'reserve',
|
||||
reference: reservationId,
|
||||
amount: maximumCredits,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Credit reservation failed';
|
||||
if (/Insufficient available credits/i.test(message)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'INSUFFICIENT_CREDITS',
|
||||
message: 'Not enough credits for this job',
|
||||
required_credits: maximumCredits,
|
||||
},
|
||||
{ status: 402 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json({ error: 'CREDITS_UNAVAILABLE', message }, { status: 503 });
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await structureDocument({
|
||||
gateway,
|
||||
request: {
|
||||
context,
|
||||
admission: {
|
||||
tenantId,
|
||||
projectId,
|
||||
jobId: `doc:${documentId}:${correlationId}`,
|
||||
modelId,
|
||||
dataClass,
|
||||
maxInputTokens: policy.maxInputTokens,
|
||||
maxOutputTokens: policy.maxOutputTokens,
|
||||
maximumCredits,
|
||||
},
|
||||
policy: {
|
||||
tenantId,
|
||||
projectId,
|
||||
allowedModelIds: policy.allowedModelIds,
|
||||
allowedDataClasses: policy.allowedDataClasses,
|
||||
destination: policy.destination,
|
||||
externalTransferAllowed: policy.externalTransferAllowed,
|
||||
maxInputTokens: policy.maxInputTokens,
|
||||
maxOutputTokens: policy.maxOutputTokens,
|
||||
},
|
||||
reservation: ledger
|
||||
? {
|
||||
tenantId,
|
||||
projectId,
|
||||
jobId: `doc:${documentId}:${correlationId}`,
|
||||
status: 'reserved',
|
||||
credits: maximumCredits,
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
countTokens: async (messages) => Math.ceil(JSON.stringify(messages).length / 4),
|
||||
instructions: instruction,
|
||||
fields,
|
||||
sources: sources.sources,
|
||||
});
|
||||
|
||||
const charged =
|
||||
ledger && priceBook
|
||||
? Math.min(
|
||||
maximumCredits,
|
||||
creditsForUsage(priceBook, {
|
||||
pages: Math.max(1, Math.ceil(sourceChars / 1800)),
|
||||
inputTokens: result.model.promptTokens,
|
||||
outputTokens: result.model.completionTokens,
|
||||
}),
|
||||
)
|
||||
: 0;
|
||||
let balance;
|
||||
if (ledger) {
|
||||
try {
|
||||
balance = (
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `settle:${reservationId}`,
|
||||
kind: 'settle',
|
||||
reference: reservationId,
|
||||
amount: charged,
|
||||
})
|
||||
).balance;
|
||||
} catch {
|
||||
// The model result is real; keep the reservation for reconciliation
|
||||
// rather than reporting a balance we could not write.
|
||||
balance = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
if (result.status !== 'mechanically_validated') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'needs_review',
|
||||
issues: result.issues,
|
||||
model: result.model,
|
||||
credits: ledger ? { reserved: maximumCredits, charged, balance } : null,
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
|
||||
const exported =
|
||||
format === 'json'
|
||||
? exportValidatedOutput({
|
||||
format: 'json',
|
||||
fields,
|
||||
sources: sources.sources,
|
||||
value: result.value,
|
||||
evidence: result.evidence,
|
||||
})
|
||||
: exportValidatedOutput({
|
||||
format: 'csv',
|
||||
fields,
|
||||
sources: sources.sources,
|
||||
value: result.value,
|
||||
evidence: result.evidence,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'mechanically_validated',
|
||||
value: result.value,
|
||||
evidence: result.evidence,
|
||||
model: result.model,
|
||||
credits: ledger ? { reserved: maximumCredits, charged, balance } : null,
|
||||
export:
|
||||
exported.status === 'ready'
|
||||
? { media_type: exported.mediaType, content: exported.content }
|
||||
: undefined,
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Inf0OutcomeUnknownError) {
|
||||
// Never release a reservation whose model call may have completed.
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'outcome_unknown',
|
||||
message:
|
||||
'The model call may have completed. The credit reservation is kept until its usage is reconciled.',
|
||||
reservation_id: reservationId,
|
||||
},
|
||||
{ status: 202 },
|
||||
);
|
||||
}
|
||||
if (ledger) {
|
||||
try {
|
||||
await ledger.apply({
|
||||
tenantId,
|
||||
idempotencyKey: `release:${reservationId}`,
|
||||
kind: 'release',
|
||||
reference: reservationId,
|
||||
amount: 0,
|
||||
});
|
||||
} catch {
|
||||
/* the reservation stays for reconciliation */
|
||||
}
|
||||
}
|
||||
const message = error instanceof Error ? error.message : 'Structuring failed';
|
||||
console.error('[0pt-workbench] structure failed:', message);
|
||||
return NextResponse.json(
|
||||
{ error: 'STRUCTURE_FAILED', message, reservation_id: reservationId },
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
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 },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
import { getBatchEntityResolutionService } from "@/src/services/entity-resolution";
|
||||
|
||||
function required(body: Record<string, unknown>, field: string): string {
|
||||
const value = body[field];
|
||||
if (typeof value !== "string" || !value.trim()) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.er", `${field} is required`);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const raw = await request.json();
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.er", "JSON object body is required");
|
||||
}
|
||||
const body = raw as Record<string, unknown>;
|
||||
const tenantId = required(body, "tenant_id");
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
|
||||
const idempotencyKey = request.headers.get("idempotency-key")?.trim()
|
||||
|| (typeof body.idempotency_key === "string" ? body.idempotency_key.trim() : "")
|
||||
|| undefined;
|
||||
const job = await getBatchEntityResolutionService().submitBatchResolution({
|
||||
tenant_id: tenantId,
|
||||
project_id: required(body, "project_id"),
|
||||
records_artifact_ref: required(body, "records_artifact_ref"),
|
||||
actor_id: request.headers.get("x-0pt-verified-sub") ?? "local-dev",
|
||||
...(typeof body.correlation_id === "string" && body.correlation_id.trim()
|
||||
? { correlation_id: body.correlation_id.trim() }
|
||||
: {}),
|
||||
...(idempotencyKey ? { idempotency_key: idempotencyKey } : {}),
|
||||
});
|
||||
return NextResponse.json(job, { status: 202 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { parseErCandidateRequest } from "@/src/er/request-validation";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { entityResolutionService } from "@/src/services/entity-resolution";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const input = parseErCandidateRequest(await request.json());
|
||||
const guard = assertTenantMatchesVerified(request, input.tenant_id);
|
||||
if (guard) return guard;
|
||||
return NextResponse.json(entityResolutionService.generateCandidates(input));
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { verifyInternalServiceToken } from "@/src/auth/internal-token";
|
||||
import {
|
||||
EntityResolutionService,
|
||||
type ErCandidateResult,
|
||||
type ErRecord,
|
||||
} from "@/src/er/entity-resolution-service";
|
||||
import { parseErCandidateRequest } from "@/src/er/request-validation";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
|
||||
const er = new EntityResolutionService();
|
||||
|
||||
function rawStringField(record: ErRecord, field: string): string | undefined {
|
||||
const value = record.fields[field];
|
||||
if (value === null || value === undefined) return undefined;
|
||||
const normalized = String(value).trim();
|
||||
return normalized || undefined;
|
||||
}
|
||||
|
||||
function stableIdentifier(record: ErRecord, field: string): string | undefined {
|
||||
const value = rawStringField(record, field);
|
||||
if (!value) return undefined;
|
||||
const normalized = value.toUpperCase().replace(/[^A-Z0-9]/g, "");
|
||||
return normalized || undefined;
|
||||
}
|
||||
|
||||
function countryIdentifier(record: ErRecord): string | undefined {
|
||||
const value = rawStringField(record, "registration_country") ?? rawStringField(record, "country");
|
||||
if (!value) return undefined;
|
||||
const normalized = value.toUpperCase().replace(/[^A-Z0-9]/g, "");
|
||||
return normalized || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Company identity hard rule v3.
|
||||
* - LEI is globally scoped.
|
||||
* - National registration numbers are comparable only within the same country.
|
||||
* - Any comparable stable-ID conflict dominates every positive match.
|
||||
*/
|
||||
er.registerHardRule({
|
||||
rule_id: "0pt.company.stable-identifiers.v3",
|
||||
decide(a, b) {
|
||||
let sharedMatch = false;
|
||||
|
||||
const aLei = stableIdentifier(a, "lei");
|
||||
const bLei = stableIdentifier(b, "lei");
|
||||
if (aLei && bLei) {
|
||||
if (aLei !== bLei) return "force_non_match";
|
||||
sharedMatch = true;
|
||||
}
|
||||
|
||||
const aCountry = countryIdentifier(a);
|
||||
const bCountry = countryIdentifier(b);
|
||||
const aOrg = stableIdentifier(a, "org_nr");
|
||||
const bOrg = stableIdentifier(b, "org_nr");
|
||||
if (aOrg && bOrg && aCountry && bCountry && aCountry === bCountry) {
|
||||
if (aOrg !== bOrg) return "force_non_match";
|
||||
sharedMatch = true;
|
||||
}
|
||||
|
||||
return sharedMatch ? "force_match" : "abstain";
|
||||
},
|
||||
});
|
||||
|
||||
function assertInternal(request: NextRequest): NextResponse | undefined {
|
||||
if (verifyInternalServiceToken(request.headers)) return undefined;
|
||||
return NextResponse.json(
|
||||
{ error: "UNAUTHENTICATED", message: "valid X-Internal-Token is required" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Company/Work boundary: fuzzy similarity is candidate evidence, never identity truth.
|
||||
* Only product hard rules backed by stable identifiers may emit `match` here.
|
||||
*/
|
||||
export function enforceCompanyReviewBoundary(result: ErCandidateResult): ErCandidateResult {
|
||||
const pairs = result.pairs.map((pair) =>
|
||||
pair.decided_by === "score" && pair.status === "match"
|
||||
? { ...pair, status: "pending_review" as const }
|
||||
: pair,
|
||||
);
|
||||
return {
|
||||
...result,
|
||||
pairs,
|
||||
review_queue: pairs.filter((pair) => pair.status === "pending_review"),
|
||||
};
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const denied = assertInternal(request);
|
||||
if (denied) return denied;
|
||||
|
||||
try {
|
||||
const result = await er.generateCandidates(parseErCandidateRequest(await request.json()));
|
||||
return NextResponse.json(enforceCompanyReviewBoundary(result));
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { verifyInternalServiceToken } from "@/src/auth/internal-token";
|
||||
import { createAud0Client } from "@/src/clients/aud0-client";
|
||||
import {
|
||||
Aud0OutboxDispatcher,
|
||||
createAud0OutboxRepositoryFromEnv,
|
||||
} from "@/src/evidence/aud0-outbox";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
|
||||
function assertInternal(request: NextRequest): NextResponse | undefined {
|
||||
if (verifyInternalServiceToken(request.headers)) return undefined;
|
||||
return NextResponse.json(
|
||||
{ error: "UNAUTHENTICATED", message: "valid X-Internal-Token is required" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
function repository() {
|
||||
const repo = createAud0OutboxRepositoryFromEnv();
|
||||
if (!repo) {
|
||||
throw new SiaxError(
|
||||
"DEPENDENCY_UNAVAILABLE",
|
||||
"0pt.aud0_outbox",
|
||||
"DATABASE_URL is required for durable evidence dispatch",
|
||||
);
|
||||
}
|
||||
return repo;
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const denied = assertInternal(request);
|
||||
if (denied) return denied;
|
||||
|
||||
try {
|
||||
const raw = await request.json().catch(() => ({})) as { limit?: unknown };
|
||||
const limit = raw.limit === undefined ? 100 : Number(raw.limit);
|
||||
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) {
|
||||
return NextResponse.json(
|
||||
{ error: "INVALID_REQUEST", message: "limit must be an integer between 1 and 500" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const repo = repository();
|
||||
// CRITICAL: the dispatcher must bypass the durable wrapper. Using the
|
||||
// default client here would enqueue the event again and could create an
|
||||
// infinite outbox loop instead of delivering to AUD0.
|
||||
const rawAud0 = createAud0Client(undefined, { durable: false });
|
||||
const dispatcher = new Aud0OutboxDispatcher(repo, rawAud0);
|
||||
const result = await dispatcher.sweep(limit);
|
||||
const stats = await repo.stats();
|
||||
return NextResponse.json({ result, stats });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const denied = assertInternal(request);
|
||||
if (denied) return denied;
|
||||
|
||||
try {
|
||||
return NextResponse.json(await repository().stats());
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { mappingService } from "@/src/services/lakehouse-mapping-registry";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
// P014: this lookup used to accept only `mappingId`, with NO tenant check
|
||||
// anywhere in the request path -- any authenticated caller could read
|
||||
// another tenant's dataset<->Iceberg-table mapping (namespace, table name,
|
||||
// storage URI) by guessing or enumerating IDs. Now requires `?tenant_id=`
|
||||
// and both checks it against the verified token and threads it into the
|
||||
// service so a foreign mapping_id 404s instead of leaking -- see
|
||||
// DatasetIcebergMappingService.getMapping's doc comment.
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ mappingId: string }> }) {
|
||||
try {
|
||||
const { mappingId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const mapping = await mappingService.getMapping(mappingId, tenantId);
|
||||
return NextResponse.json(mapping);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return NextResponse.json({ error: message }, { status: 404 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, requestIcebergWriteSchema } from "@/src/validation/0pt-schemas";
|
||||
import { writeService } from "@/src/services/lakehouse-mapping-registry";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
// Registers a new Iceberg snapshot (a write) through ST0RE's table registry
|
||||
// for an already-mapped dataset. See docs/ICEBERG_WRITE_BOUNDARY.md.
|
||||
//
|
||||
// `writeService` is the SHARED instance from
|
||||
// src/services/lakehouse-mapping-registry.ts -- this route used to construct
|
||||
// its own `new IcebergWriteService()`, which held a private in-memory mapping
|
||||
// registry, so a mapping created via POST /lakehouse/mappings was never
|
||||
// visible here and every write failed with "mapping not found".
|
||||
//
|
||||
// The body is validated against requestIcebergWriteSchema before it reaches
|
||||
// the service (Wave 2 hardening).
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ mappingId: string }> }) {
|
||||
try {
|
||||
const { mappingId } = await params;
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(requestIcebergWriteSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const result = await writeService.requestIcebergWrite({
|
||||
dataset_iceberg_mapping_id: mappingId,
|
||||
tenant_id: body.tenant_id,
|
||||
actor_id: body.actor_id,
|
||||
correlation_id: body.correlation_id,
|
||||
snapshot_type: body.snapshot_type,
|
||||
schema_version: body.schema_version,
|
||||
manifest_uri: body.manifest_uri,
|
||||
record_count: body.record_count,
|
||||
size_bytes: body.size_bytes,
|
||||
heavy: body.heavy,
|
||||
});
|
||||
return NextResponse.json(result, { status: 202 });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return NextResponse.json({ error: message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, mapDatasetToIcebergTableSchema } from "@/src/validation/0pt-schemas";
|
||||
import { mappingService, writeService } from "@/src/services/lakehouse-mapping-registry";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import type { IcebergTableFormat } from "@/src/clients/st0re-lakehouse-client";
|
||||
|
||||
// Shared instances come from 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. (Each route file
|
||||
// previously constructed its own DatasetIcebergMappingService/
|
||||
// IcebergWriteService, so a mapping created here was invisible to the writes
|
||||
// route -- every write failed with "mapping not found".) This still matches the
|
||||
// in-memory-per-module convention app/api/0pt/datasets and app/api/0pt/quality
|
||||
// use; 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
|
||||
// dataset_iceberg_mapping row that points at it -- this is 0pt's write-path
|
||||
// entrypoint, see docs/ICEBERG_WRITE_BOUNDARY.md.
|
||||
//
|
||||
// The body is validated against mapDatasetToIcebergTableSchema BEFORE it
|
||||
// reaches the service (Wave 2 hardening): an unvalidated request body used to
|
||||
// be passed straight into the capability call.
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(mapDatasetToIcebergTableSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const result = await writeService.mapDatasetToIcebergTable({
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
dataset_id: body.dataset_id,
|
||||
dataset_iceberg_mapping_id: body.dataset_iceberg_mapping_id,
|
||||
namespace: body.namespace,
|
||||
table_name: body.table_name,
|
||||
storage_uri: body.storage_uri,
|
||||
catalog_ref: body.catalog_ref,
|
||||
// mapDatasetToIcebergTableSchema types this as a plain string
|
||||
// (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). This cast changes no runtime behavior:
|
||||
// an unrecognized value flows through exactly as it did before
|
||||
// (ST0RE's own table-registration route is the actual validator) --
|
||||
// it only satisfies the type checker, which previously never saw this
|
||||
// file (nothing under tests/ imported it before P014's cross-tenant
|
||||
// regression tests).
|
||||
table_format: body.table_format as IcebergTableFormat | undefined,
|
||||
actor_id: body.actor_id,
|
||||
correlation_id: body.correlation_id,
|
||||
});
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
// P014: tenant_id used to be optional here, and
|
||||
// DatasetIcebergMappingService.listMappings treats an absent tenant_id
|
||||
// filter as "no restriction" -- omitting the query param returned every
|
||||
// tenant's dataset<->Iceberg-table mappings (namespace, table name, storage
|
||||
// URI). Now required and cross-checked, matching the rest of the surface.
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const mappings = await mappingService.listMappings({
|
||||
tenant_id: tenantId,
|
||||
project_id: searchParams.get("project_id") ?? undefined,
|
||||
dataset_id: searchParams.get("dataset_id") ?? undefined,
|
||||
});
|
||||
return NextResponse.json(mappings);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* app/api/0pt/lineage/route.ts
|
||||
* =============================
|
||||
* P067 DoD: "source -> output lineage is QUERYABLE". This is the query.
|
||||
*
|
||||
* GET /api/0pt/lineage?tenant_id=…&output_name=… -> what fed this output
|
||||
* GET /api/0pt/lineage?tenant_id=…&input_name=… -> what this input produced
|
||||
*
|
||||
* The answer comes from 0pt's local projection of the OpenLineage events it
|
||||
* emits to AUD0 (src/lineage/lineage-store.ts). AUD0 remains the system of
|
||||
* record; this endpoint exists because "emitted to AUD0" was never the same
|
||||
* thing as "answerable from 0pt", and before this route nothing in this repo
|
||||
* could answer either question.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { lineageStore } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
const outputName = searchParams.get("output_name") ?? undefined;
|
||||
const inputName = searchParams.get("input_name") ?? undefined;
|
||||
if (!tenantId) return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
if (!outputName && !inputName) {
|
||||
return NextResponse.json(
|
||||
{ error: "one of output_name or input_name is required — an unfiltered lineage dump is not a query" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
const limitRaw = searchParams.get("limit");
|
||||
const limit = limitRaw ? Math.min(Math.max(Number(limitRaw), 1), 500) : undefined;
|
||||
const edges = await lineageStore.query({
|
||||
tenant_id: tenantId,
|
||||
output_name: outputName,
|
||||
input_name: inputName,
|
||||
limit,
|
||||
});
|
||||
return NextResponse.json({ edges, count: edges.length });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* app/api/0pt/quality/bridge-run/route.ts
|
||||
* ==========================================
|
||||
* The P010 TS/Python split-brain bridge (BEFORE_STATE.md §2). This is the
|
||||
* ONE route the production Python engine
|
||||
* (services/api/workers/quality_bridge.py, called from
|
||||
* services/api/workers/pipeline.py) talks to. It:
|
||||
*
|
||||
* 1. auto-provisions a deterministic, tenant-scoped baseline rule set for
|
||||
* (tenant_id, dataset_id) the first time it's seen (src/quality/quality-bridge.ts) --
|
||||
* the Python engine never has to pre-register rules through the CRUD
|
||||
* surface just to get a quality read on an order's already-produced rows;
|
||||
* 2. runs QualityService.runQuality synchronously against the rows the
|
||||
* pipeline already produced (delivered, post the Python filter --
|
||||
* this is an ADVISORY second opinion, not a gate, until Simon decides
|
||||
* to wire per-row gating -- see quality_bridge.py's docstring for why
|
||||
* that isn't done in this pass);
|
||||
* 3. returns the run + any open issues.
|
||||
*
|
||||
* This does not replace, call, or block on the Python filter in any way --
|
||||
* it is purely additive. If this route is unreachable, times out, or 500s,
|
||||
* the Python side is required to fail open (never raise into the pipeline).
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, qualityBridgeRunSchema } from "@/src/validation/0pt-schemas";
|
||||
import { qualityService } from "@/src/services/quality";
|
||||
import { ensureBaselineRules } from "@/src/quality/quality-bridge";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(qualityBridgeRunSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
// Tenant-scoped write (auto-provisions baseline rules + stores a run):
|
||||
// the internal service principal must stay inside its server-configured
|
||||
// tenant allowlist, never a tenant named by the caller.
|
||||
const guard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (guard) return guard;
|
||||
|
||||
await ensureBaselineRules(qualityService, {
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
dataset_id: body.dataset_id,
|
||||
});
|
||||
|
||||
const run = await qualityService.runQuality({
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
dataset_id: body.dataset_id,
|
||||
dataset_version: body.dataset_version,
|
||||
rows: body.rows,
|
||||
correlation_id: body.correlation_id,
|
||||
});
|
||||
|
||||
const issues = qualityService.listIssues({
|
||||
tenant_id: body.tenant_id,
|
||||
dataset_id: body.dataset_id,
|
||||
status: "open",
|
||||
});
|
||||
|
||||
return NextResponse.json({ run, issues }, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* app/api/0pt/quality/issues/route.ts
|
||||
* ======================================
|
||||
* quality.list_issues (GET) -- issues opened by finished quality runs
|
||||
* (human-review handoff, Master-DoD §10).
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { qualityService } from "@/src/services/quality";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import type { DataQualityIssue } from "@/src/quality/quality-types";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const issues = qualityService.listIssues({
|
||||
tenant_id: tenantId,
|
||||
dataset_id: searchParams.get("dataset_id") ?? undefined,
|
||||
status: (searchParams.get("status") as DataQualityIssue["status"]) ?? undefined,
|
||||
});
|
||||
return NextResponse.json(issues);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* app/api/0pt/quality/rules/[ruleId]/route.ts
|
||||
* ===============================================
|
||||
* quality.get_rule (GET) + quality.update_rule (PUT, versioned -- bumps
|
||||
* `version`, records the superseded row). Cross-tenant reads are NOT_FOUND
|
||||
* (no existence oracle), matching QualityService.getRule's own contract.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { qualityService } from "@/src/services/quality";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import { z } from "zod";
|
||||
|
||||
const updateQualityRuleSchema = z.object({
|
||||
tenant_id: z.string().min(1),
|
||||
name: z.string().min(1).optional(),
|
||||
expectation: z.object({ expectation_type: z.string().min(1), kwargs: z.record(z.string(), z.unknown()) }).optional(),
|
||||
severity: z.enum(["info", "warning", "error", "critical"]).optional(),
|
||||
status: z.enum(["active", "disabled", "superseded"]).optional(),
|
||||
});
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ ruleId: string }> }) {
|
||||
try {
|
||||
const { ruleId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const versions = searchParams.get("versions") === "true";
|
||||
if (versions) {
|
||||
return NextResponse.json(qualityService.getRuleVersions(ruleId, tenantId));
|
||||
}
|
||||
return NextResponse.json(qualityService.getRule(ruleId, tenantId));
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest, { params }: { params: Promise<{ ruleId: string }> }) {
|
||||
try {
|
||||
const { ruleId } = await params;
|
||||
const raw = await request.json();
|
||||
const parsed = updateQualityRuleSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: "validation_error", issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), message: i.message })) },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
const { tenant_id, ...patch } = parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const rule = await qualityService.updateRule(ruleId, tenant_id, patch);
|
||||
return NextResponse.json(rule);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* app/api/0pt/quality/rules/route.ts
|
||||
* ====================================
|
||||
* quality.create_rule (POST) + quality.list_rules (GET) -- the CRUD surface
|
||||
* over QualityService's versioned rule registry (src/quality/quality-service.ts,
|
||||
* Master-DoD §10). Uses the shared singleton from src/services/quality.ts,
|
||||
* not a fresh `new QualityService()` per route module -- see that file's
|
||||
* doc comment (and BEFORE_STATE.md §1, which found and fixed the same
|
||||
* per-module-instance defect for the Source Registry).
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, createQualityRuleSchema } from "@/src/validation/0pt-schemas";
|
||||
import { qualityService } from "@/src/services/quality";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import type { DataQualityRule } from "@/src/quality/quality-types";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(createQualityRuleSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, __parsed.data.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const rule = await qualityService.createRule(__parsed.data);
|
||||
return NextResponse.json(rule, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const rules = qualityService.listRules({
|
||||
tenant_id: tenantId,
|
||||
dataset_id: searchParams.get("dataset_id") ?? undefined,
|
||||
status: (searchParams.get("status") as DataQualityRule["status"]) ?? undefined,
|
||||
});
|
||||
return NextResponse.json(rules);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* app/api/0pt/quality/runs/[runId]/route.ts
|
||||
* =============================================
|
||||
* quality.get_run (GET). Cross-tenant reads are NOT_FOUND.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { qualityService } from "@/src/services/quality";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ runId: string }> }) {
|
||||
try {
|
||||
const { runId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
return NextResponse.json(qualityService.getRun(runId, tenantId));
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* app/api/0pt/quality/runs/route.ts
|
||||
* ====================================
|
||||
* quality.run (POST) + quality.list_runs (GET). POST executes all active
|
||||
* rules for a dataset against caller-supplied rows -- runs synchronously
|
||||
* when every active rule's expectation is locally executable, otherwise
|
||||
* delegates to the GE backend via N0D (QualityService.runQuality never
|
||||
* fabricates a result for a check it couldn't run).
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, createQualityRunSchema } from "@/src/validation/0pt-schemas";
|
||||
import { qualityService } from "@/src/services/quality";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(createQualityRunSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, __parsed.data.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const run = await qualityService.runQuality(__parsed.data);
|
||||
return NextResponse.json(run, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const runs = qualityService.listRuns({
|
||||
tenant_id: tenantId,
|
||||
dataset_id: searchParams.get("dataset_id") ?? undefined,
|
||||
});
|
||||
return NextResponse.json(runs);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json({
|
||||
status: "ok",
|
||||
product: "0pt",
|
||||
version: "1.0.0",
|
||||
endpoints: [
|
||||
"/api/0pt/sources",
|
||||
"/api/0pt/datasets",
|
||||
"/api/0pt/data-contracts",
|
||||
"/api/0pt/quality/checks",
|
||||
"/api/0pt/quality/reports",
|
||||
"/api/0pt/features/views",
|
||||
"/api/0pt/documents/capture",
|
||||
"/api/0pt/documents/{documentId}/extraction",
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
import { getSearchService } from "@/src/services/search";
|
||||
|
||||
function primitiveFilters(value: unknown): Record<string, string | number | boolean> | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.search", "filters must be an object");
|
||||
}
|
||||
const result: Record<string, string | number | boolean> = {};
|
||||
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
|
||||
if (typeof item !== "string" && typeof item !== "number" && typeof item !== "boolean") {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.search", `filter ${key} must be string, number or boolean`);
|
||||
}
|
||||
result[key] = item;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ indexName: string }> },
|
||||
) {
|
||||
try {
|
||||
const { indexName } = await params;
|
||||
const raw = await request.json();
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.search", "JSON object body is required");
|
||||
}
|
||||
const body = raw as Record<string, unknown>;
|
||||
const tenantId = typeof body.tenant_id === "string" ? body.tenant_id.trim() : "";
|
||||
const purpose = typeof body.purpose === "string" ? body.purpose.trim() : "";
|
||||
if (!tenantId) throw new SiaxError("INVALID_REQUEST", "0pt.search", "tenant_id is required");
|
||||
if (!purpose) throw new SiaxError("INVALID_REQUEST", "0pt.search", "purpose is required");
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
|
||||
// Public/authenticated traffic is deliberately fixed to internal rights.
|
||||
// A client-supplied higher rights_tag would be privilege escalation by
|
||||
// request body; broader tags require a future CL0UD-derived entitlement.
|
||||
if (body.rights_tag !== undefined && body.rights_tag !== "internal") {
|
||||
throw new SiaxError(
|
||||
"AUTHORIZATION_DENIED",
|
||||
"0pt.search",
|
||||
"rights_tag cannot be elevated by the caller",
|
||||
);
|
||||
}
|
||||
|
||||
const result = await getSearchService().query(indexName, {
|
||||
tenant_id: tenantId,
|
||||
purpose,
|
||||
rights_tag: "internal",
|
||||
...(typeof body.text === "string" ? { text: body.text } : {}),
|
||||
...(body.from === undefined ? {} : { from: Number(body.from) }),
|
||||
...(body.size === undefined ? {} : { size: Number(body.size) }),
|
||||
...(body.filters === undefined ? {} : { filters: primitiveFilters(body.filters) }),
|
||||
});
|
||||
return NextResponse.json(result);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { verifyInternalServiceToken } from "@/src/auth/internal-token";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
import { getSearchService } from "@/src/services/search";
|
||||
import type { SearchFieldType } from "@/src/search/search-types";
|
||||
|
||||
const FIELD_TYPES = new Set<SearchFieldType>(["keyword", "text", "long", "double", "date", "boolean"]);
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
if (!verifyInternalServiceToken(request.headers)) {
|
||||
return NextResponse.json({ error: "UNAUTHENTICATED", message: "valid X-Internal-Token is required" }, { status: 401 });
|
||||
}
|
||||
try {
|
||||
const raw = await request.json();
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.search", "JSON object body is required");
|
||||
}
|
||||
const body = raw as Record<string, unknown>;
|
||||
const indexName = typeof body.index_name === "string" ? body.index_name.trim() : "";
|
||||
const version = Number(body.version);
|
||||
if (!body.fields || typeof body.fields !== "object" || Array.isArray(body.fields)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.search", "fields must be an object");
|
||||
}
|
||||
const fields: Record<string, SearchFieldType> = {};
|
||||
for (const [name, rawType] of Object.entries(body.fields as Record<string, unknown>)) {
|
||||
if (!name.trim() || typeof rawType !== "string" || !FIELD_TYPES.has(rawType as SearchFieldType)) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.search", `invalid field definition for ${name || "<empty>"}`);
|
||||
}
|
||||
fields[name.trim()] = rawType as SearchFieldType;
|
||||
}
|
||||
if (!Array.isArray(body.default_search_fields) || !body.default_search_fields.every((v) => typeof v === "string")) {
|
||||
throw new SiaxError("INVALID_REQUEST", "0pt.search", "default_search_fields must be a string array");
|
||||
}
|
||||
|
||||
const definition = await getSearchService().registerIndexDefinitionDurable(
|
||||
{
|
||||
index_name: indexName,
|
||||
version,
|
||||
fields,
|
||||
default_search_fields: body.default_search_fields.map((v) => String(v).trim()),
|
||||
},
|
||||
request.headers.get("x-0pt-verified-sub") ?? "svc_0pt",
|
||||
);
|
||||
return NextResponse.json(definition, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
return NextResponse.json(await getSearchService().listIndexDefinitionsDurable());
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* app/api/0pt/sources/[sourceId]/activate/route.ts
|
||||
* ==================================================
|
||||
* P060 activation gate over HTTP. POST activates a source ONLY when it is
|
||||
* classified (owner + unexpired authorization + rights + provenance);
|
||||
* otherwise it returns 403 AUTHORIZATION_DENIED naming every missing fact.
|
||||
* GET returns the classification without changing anything, so an operator
|
||||
* can see what is missing before trying.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { activateSourceSchema, parseBody } from "@/src/validation/0pt-schemas";
|
||||
import { sourceRegistryService } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const tenantId = new URL(request.url).searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
return NextResponse.json(await sourceRegistryService.classifySource(sourceId, tenantId));
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const parsed = parseBody(activateSourceSchema, await request.json());
|
||||
if (!parsed.ok) return NextResponse.json(parsed.body, { status: parsed.status });
|
||||
const guard = assertTenantMatchesVerified(request, parsed.data.tenant_id);
|
||||
if (guard) return guard;
|
||||
const source = await sourceRegistryService.activateSource(
|
||||
sourceId,
|
||||
parsed.data.tenant_id,
|
||||
parsed.data.actor_id,
|
||||
);
|
||||
return NextResponse.json(source);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* app/api/0pt/sources/[sourceId]/authorization/route.ts
|
||||
* ======================================================
|
||||
* P060 "authorization": the recorded decision that 0pt may connect to this
|
||||
* source at all — separate from rights (what the DATA may be used for). PUT
|
||||
* is an upsert; a service identity as `granted_by` is rejected (400), because
|
||||
* a source may not authorize itself.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, setSourceAuthorizationSchema } from "@/src/validation/0pt-schemas";
|
||||
import { sourceRegistryService } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const tenantId = new URL(request.url).searchParams.get("tenant_id");
|
||||
if (!tenantId) return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
const auth = await sourceRegistryService.getAuthorization(sourceId, tenantId);
|
||||
if (!auth) {
|
||||
return NextResponse.json({ error: `source ${sourceId} has no authorization record` }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json(auth);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const parsed = parseBody(setSourceAuthorizationSchema, await request.json());
|
||||
if (!parsed.ok) return NextResponse.json(parsed.body, { status: parsed.status });
|
||||
const guard = assertTenantMatchesVerified(request, parsed.data.tenant_id);
|
||||
if (guard) return guard;
|
||||
return NextResponse.json(
|
||||
await sourceRegistryService.setAuthorization({ ...parsed.data, source_id: sourceId }),
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* app/api/0pt/sources/[sourceId]/freshness/route.ts
|
||||
* =====================================================
|
||||
* Freshness view derived from provenance's freshness_sla_hours + the last
|
||||
* successful observation (recorded via POST .../health with status "up",
|
||||
* or SourceRegistryService.recordSuccess directly). Read-only — there is no
|
||||
* separate write path here by design; freshness is a derived signal, not
|
||||
* its own record.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { sourceRegistryService } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const freshness = await sourceRegistryService.getFreshness(sourceId, tenantId);
|
||||
return NextResponse.json(freshness);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* app/api/0pt/sources/[sourceId]/health/route.ts
|
||||
* ==================================================
|
||||
* source.health — record a health observation (POST) and read the
|
||||
* aggregate view (GET): status, last check, consecutive failures. Bounded
|
||||
* history (latest 100 observations) — this is an operational signal, not
|
||||
* an audit log; AUD0 owns history.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, recordSourceHealthCheckSchema } from "@/src/validation/0pt-schemas";
|
||||
import { sourceRegistryService } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const health = await sourceRegistryService.getHealth(sourceId, tenantId);
|
||||
return NextResponse.json(health);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(recordSourceHealthCheckSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const health = await sourceRegistryService.recordHealthCheck({
|
||||
source_id: sourceId,
|
||||
tenant_id: body.tenant_id,
|
||||
status: body.status,
|
||||
checked_at: body.checked_at ?? new Date().toISOString(),
|
||||
latency_ms: body.latency_ms,
|
||||
detail: body.detail,
|
||||
});
|
||||
return NextResponse.json(health, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* app/api/0pt/sources/[sourceId]/provenance/route.ts
|
||||
* ======================================================
|
||||
* Per-SOURCE provenance/method metadata (Master-DoD §10) — HOW a source is
|
||||
* obtained (official_api | bulk_download | authorized_web | licensed_feed |
|
||||
* manual_upload), not per-field bridge_provenance. See BEFORE_STATE.md §3
|
||||
* for that distinction: this route does not, and cannot, close the
|
||||
* bridge_provenance gap — it only surfaces what SourceRegistryService
|
||||
* already models at the source level.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, setSourceProvenanceSchema } from "@/src/validation/0pt-schemas";
|
||||
import { sourceRegistryService } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const provenance = await sourceRegistryService.getProvenance(sourceId, tenantId);
|
||||
if (!provenance) {
|
||||
return NextResponse.json({ error: `source ${sourceId} has no provenance record` }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json(provenance);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(setSourceProvenanceSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const provenance = await sourceRegistryService.setProvenance({
|
||||
...body,
|
||||
source_id: sourceId,
|
||||
updated_at: new Date().toISOString(),
|
||||
});
|
||||
return NextResponse.json(provenance);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* app/api/0pt/sources/[sourceId]/query/route.ts
|
||||
* ================================================
|
||||
* 0pt.query_source — bounded synchronous query execution for a registered
|
||||
* Source. Additive: does not modify sibling ../route.ts or ../../route.ts.
|
||||
*
|
||||
* UPDATED (Source Registry Postgres-persistence pass): now imports the
|
||||
* shared `sourceService` singleton from src/services/source-registry.ts
|
||||
* instead of constructing its own SourceService, closing the "not even a
|
||||
* shared process-wide singleton" gap BEFORE_STATE.md §1 flagged (a source
|
||||
* registered via POST /api/0pt/sources used to be invisible here). With
|
||||
* DATABASE_URL configured this is doubly fixed — state lives in Postgres
|
||||
* (sql/002_source_registry.sql), genuinely shared across processes, not
|
||||
* just within one. Details: docs/P0_QUERY_SOURCE_FLOW.md.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, sourceQuerySchema } from "@/src/validation/0pt-schemas";
|
||||
import { sourceService } from "@/src/services/source-registry";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import {
|
||||
SourceQueryService,
|
||||
SourceQueryTimeoutError,
|
||||
SourceQueryUnsupportedError,
|
||||
} from "@/src/services/source-query-service";
|
||||
|
||||
const queryService = new SourceQueryService({ sourceService });
|
||||
|
||||
export async function POST(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(sourceQuerySchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
|
||||
if (typeof body.query !== "string" || body.query.trim().length === 0) {
|
||||
return NextResponse.json({ error: "query (string) is required" }, { status: 400 });
|
||||
}
|
||||
if (typeof body.tenant_id !== "string" || typeof body.project_id !== "string") {
|
||||
return NextResponse.json({ error: "tenant_id and project_id are required" }, { status: 400 });
|
||||
}
|
||||
if (!body.connection_config || typeof body.connection_config !== "object") {
|
||||
return NextResponse.json({ error: "connection_config is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
|
||||
const result = await queryService.querySource({
|
||||
source_id: sourceId,
|
||||
query: body.query,
|
||||
params: body.params,
|
||||
tenant_id: body.tenant_id,
|
||||
project_id: body.project_id,
|
||||
actor_id: body.actor_id,
|
||||
correlation_id: body.correlation_id,
|
||||
max_rows: body.max_rows,
|
||||
timeout_ms: body.timeout_ms,
|
||||
connection_config: body.connection_config,
|
||||
});
|
||||
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (error instanceof SourceQueryTimeoutError) {
|
||||
return NextResponse.json({ error: message }, { status: 504 });
|
||||
}
|
||||
if (error instanceof SourceQueryUnsupportedError) {
|
||||
return NextResponse.json({ error: message }, { status: 422 });
|
||||
}
|
||||
const status = /not found/i.test(message) ? 404 : 400;
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* app/api/0pt/sources/[sourceId]/rights/route.ts
|
||||
* ==================================================
|
||||
* Rights / license / purpose metadata (Master-DoD §10). PUT is an upsert
|
||||
* (SourceRegistryService.setRights), matching the fail-closed purpose gate:
|
||||
* no rights record at all denies every purpose until one is set here.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, setSourceRightsSchema } from "@/src/validation/0pt-schemas";
|
||||
import { sourceRegistryService } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const rights = await sourceRegistryService.getRights(sourceId, tenantId);
|
||||
if (!rights) {
|
||||
return NextResponse.json({ error: `source ${sourceId} has no rights record` }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json(rights);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(setSourceRightsSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const rights = await sourceRegistryService.setRights({ ...body, source_id: sourceId });
|
||||
return NextResponse.json(rights);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* app/api/0pt/sources/[sourceId]/route.ts
|
||||
* ==========================================
|
||||
* source.describe — full SourceDescriptor (base + rights + provenance +
|
||||
* health + freshness + rate policy). Cross-tenant probes get 404 NOT_FOUND
|
||||
* (no existence oracle, §50) via SourceRegistryService.describeSource's
|
||||
* assertSourceTenant gate.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { sourceRegistryService } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const descriptor = await sourceRegistryService.describeSource(sourceId, tenantId);
|
||||
return NextResponse.json(descriptor);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* app/api/0pt/sources/[sourceId]/schedule/route.ts
|
||||
* =================================================
|
||||
* P060 "schedule": ingestion mode + cadence, recorded on the source. 0pt does
|
||||
* NOT run cron itself — ACT0 owns scheduling; this row is the declaration a
|
||||
* scheduler reads, and saying otherwise would be a claim this repo cannot back.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, setSourceScheduleSchema } from "@/src/validation/0pt-schemas";
|
||||
import { sourceRegistryService } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const tenantId = new URL(request.url).searchParams.get("tenant_id");
|
||||
if (!tenantId) return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
const guard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (guard) return guard;
|
||||
const schedule = await sourceRegistryService.getSchedule(sourceId, tenantId);
|
||||
if (!schedule) {
|
||||
return NextResponse.json({ error: `source ${sourceId} has no schedule record` }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json(schedule);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest, { params }: { params: Promise<{ sourceId: string }> }) {
|
||||
try {
|
||||
const { sourceId } = await params;
|
||||
const parsed = parseBody(setSourceScheduleSchema, await request.json());
|
||||
if (!parsed.ok) return NextResponse.json(parsed.body, { status: parsed.status });
|
||||
const guard = assertTenantMatchesVerified(request, parsed.data.tenant_id);
|
||||
if (guard) return guard;
|
||||
return NextResponse.json(
|
||||
await sourceRegistryService.setSchedule({
|
||||
...parsed.data,
|
||||
source_id: sourceId,
|
||||
updated_at: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { sourceRatePolicyService as service } from "@/src/services/source-registry";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
// P014: this lookup used to accept only `sourceRatePolicyId`, with NO tenant
|
||||
// check anywhere in the request path — any authenticated caller could read
|
||||
// another tenant's rate-limit/crawl-budget/compliance-notes record by
|
||||
// guessing or enumerating IDs. Now requires `?tenant_id=` (matching every
|
||||
// sibling route under app/api/0pt/sources/*) and both checks it against the
|
||||
// verified token (assertTenantMatchesVerified) and threads it into the
|
||||
// service so a foreign policy_id 404s instead of leaking (no existence
|
||||
// oracle) — see getSourceRatePolicy's doc comment.
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ sourceRatePolicyId: string }> },
|
||||
) {
|
||||
try {
|
||||
const { sourceRatePolicyId } = await params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const policy = await service.getSourceRatePolicy(sourceRatePolicyId, tenantId);
|
||||
return NextResponse.json(policy);
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return NextResponse.json({ error: message }, { status: 404 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, createSourceRatePolicySchema } from "@/src/validation/0pt-schemas";
|
||||
import { sourceRatePolicyService as service } from "@/src/services/source-registry";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(createSourceRatePolicySchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const policy = await service.createSourceRatePolicy(body);
|
||||
return NextResponse.json(policy, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
return NextResponse.json({ error: message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id") ?? undefined;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const policies = await service.listSourceRatePolicies({
|
||||
tenant_id: tenantId,
|
||||
project_id: searchParams.get("project_id") ?? undefined,
|
||||
source_id: searchParams.get("source_id") ?? undefined,
|
||||
});
|
||||
return NextResponse.json(policies);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* app/api/0pt/sources/route.ts
|
||||
* ==============================
|
||||
* source.register (POST) + source.query (GET) — the P0 Source Registry
|
||||
* route surface BEFORE_STATE.md §1 found entirely missing
|
||||
* (`grep -rl "SourceRegistryService" app/` returned nothing). Backed by
|
||||
* SourceRegistryService, which now persists to Postgres when DATABASE_URL
|
||||
* is configured (src/repositories/*, sql/002_source_registry.sql).
|
||||
*
|
||||
* Uses the shared singleton from src/services/source-registry.ts, not a
|
||||
* fresh `new SourceRegistryService()` per route module — see that file's
|
||||
* doc comment.
|
||||
*/
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { parseBody, registerSourceSchema } from "@/src/validation/0pt-schemas";
|
||||
import { sourceRegistryService } from "@/src/services/source-registry";
|
||||
import { siaxErrorResponse } from "@/src/http/siax-error-response";
|
||||
import { assertTenantMatchesVerified } from "@/src/http/tenant-guard";
|
||||
import type { SourceStatus, SourceType } from "@/src/types/source";
|
||||
import type { SourceRights } from "@/src/types/source-registry";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const __raw = await request.json();
|
||||
const __parsed = parseBody(registerSourceSchema, __raw);
|
||||
if (!__parsed.ok) {
|
||||
return NextResponse.json(__parsed.body, { status: __parsed.status });
|
||||
}
|
||||
const body = __parsed.data;
|
||||
const tenantGuard = assertTenantMatchesVerified(request, body.tenant_id);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const descriptor = await sourceRegistryService.registerSource(body);
|
||||
return NextResponse.json(descriptor, { status: 201 });
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const tenantId = searchParams.get("tenant_id");
|
||||
if (!tenantId) {
|
||||
return NextResponse.json({ error: "tenant_id is required" }, { status: 400 });
|
||||
}
|
||||
const tenantGuard = assertTenantMatchesVerified(request, tenantId);
|
||||
if (tenantGuard) return tenantGuard;
|
||||
const sources = await sourceRegistryService.querySources({
|
||||
tenant_id: tenantId,
|
||||
project_id: searchParams.get("project_id") ?? undefined,
|
||||
source_type: (searchParams.get("source_type") as SourceType) ?? undefined,
|
||||
status: (searchParams.get("status") as SourceStatus) ?? undefined,
|
||||
purpose: searchParams.get("purpose") ?? undefined,
|
||||
redistribution: (searchParams.get("redistribution") as SourceRights["redistribution"]) ?? undefined,
|
||||
});
|
||||
return NextResponse.json(sources);
|
||||
} catch (error: unknown) {
|
||||
return siaxErrorResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { listOrders } from "@/lib/orders-store";
|
||||
import { requireRouteAuth } from "@/src/auth/require-route-auth";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
|
||||
// GET /api/admin/metrics — order queue + financial aggregates for the admin
|
||||
// dashboard. Outside middleware.ts's matcher (/api/0pt/:path* only) and
|
||||
// previously unauthenticated entirely, so auth is enforced here directly via
|
||||
// the same fail-closed Zitadel verifier — see src/auth/require-route-auth.ts.
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
let orders;
|
||||
try {
|
||||
orders = await listOrders();
|
||||
} catch (err: unknown) {
|
||||
// 0pt#53: durable-store failure -> documented DEPENDENCY_UNAVAILABLE/503.
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
const byStatus: Record<string, number> = {};
|
||||
let depositPaidOre = 0;
|
||||
let pipelineOre = 0;
|
||||
for (const o of orders) {
|
||||
byStatus[o.status] = (byStatus[o.status] ?? 0) + 1;
|
||||
if (o.status !== "draft") depositPaidOre += o.deposit_ore ?? 0;
|
||||
pipelineOre += o.total_ore ?? 0;
|
||||
}
|
||||
return NextResponse.json({
|
||||
total: orders.length,
|
||||
by_status: byStatus,
|
||||
in_production: byStatus["in_production"] ?? 0,
|
||||
review: byStatus["review"] ?? 0,
|
||||
delivered: byStatus["delivered"] ?? 0,
|
||||
deposit_paid_ore: depositPaidOre,
|
||||
pipeline_ore: pipelineOre,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
import { requireRouteAuth } from "@/src/auth/require-route-auth";
|
||||
import { createAud0Client } from "@/src/clients/aud0-client";
|
||||
import {
|
||||
addNote,
|
||||
findNote,
|
||||
listNotes,
|
||||
NoteNotFoundError,
|
||||
NoteVersionConflictError,
|
||||
updateNote,
|
||||
} from "@/lib/order-notes-store";
|
||||
import { getOrder } from "@/lib/orders-store";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
|
||||
// GET/POST/PATCH /api/admin/order-notes — persisted collaboration state på
|
||||
// admin-orders (kernel: @siax/collaboration). Ligger utanför middleware.ts:s
|
||||
// matcher (/api/0pt/*), så auth läggs på direkt via requireRouteAuth, precis
|
||||
// som /api/admin/metrics — fail-closed Zitadel-verifiering, 401 utan token.
|
||||
//
|
||||
// Tenant-guard: tenant_id hämtas SERVER-SIDE från ordern (aldrig från
|
||||
// klienten) och jämförs mot den verifierade kontextens tenant — mismatch är
|
||||
// 403. Conflict semantics: PATCH med stale `version` -> 409 + aktuell version
|
||||
// (optimistisk samtidighet; last-write-wins först EFTER en medveten reload).
|
||||
|
||||
const AUDIT_CAPABILITY = "admin.order_notes";
|
||||
|
||||
async function audit(
|
||||
tenantId: string | null,
|
||||
actorId: string,
|
||||
resourceId: string,
|
||||
eventType: string,
|
||||
payload: unknown,
|
||||
): Promise<void> {
|
||||
// Best effort: AUD0 är evidence, inte en skriv-buffert — ett audit-fel får
|
||||
// aldrig rulla tillbaka en lyckad note-skrivning.
|
||||
try {
|
||||
await createAud0Client().ingestEvent({
|
||||
event_id: `aud_${crypto.randomUUID()}`,
|
||||
event_type: eventType,
|
||||
tenant_id: tenantId ?? "anonymous",
|
||||
project_id: "0pt",
|
||||
actor_id: actorId,
|
||||
app_id: "0pt",
|
||||
capability_id: AUDIT_CAPABILITY,
|
||||
resource_type: "order_note",
|
||||
resource_id: resourceId,
|
||||
risk_level: "L1",
|
||||
payload,
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
} catch {
|
||||
// swallow — see comment above
|
||||
}
|
||||
}
|
||||
|
||||
function tenantGuard(ctxTenant: string, orderTenant: string | null | undefined): NextResponse | null {
|
||||
if (!orderTenant) return null; // legacy anonymous draft — admin-ytan får annotera
|
||||
if (ctxTenant !== orderTenant) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "OPT_ACCESS_DENIED",
|
||||
message: "order belongs to a different tenant than the authenticated token",
|
||||
details: { order_tenant: orderTenant },
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
const orderId = req.nextUrl.searchParams.get("order_id");
|
||||
if (!orderId) {
|
||||
return NextResponse.json({ error: "order_id query parameter is required" }, { status: 400 });
|
||||
}
|
||||
const order = await getOrder(orderId);
|
||||
if (!order) {
|
||||
return NextResponse.json({ error: "order_not_found", order_id: orderId }, { status: 404 });
|
||||
}
|
||||
const denied = tenantGuard(auth.ctx.tenantId, order.tenant_id);
|
||||
if (denied) return denied;
|
||||
const notes = await listNotes(orderId);
|
||||
return NextResponse.json({ order_id: orderId, notes });
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
let body: { order_id?: string; body?: string };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
if (!body.order_id || !body.body || !String(body.body).trim()) {
|
||||
return NextResponse.json(
|
||||
{ error: "order_id and non-empty body are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
const order = await getOrder(body.order_id);
|
||||
if (!order) {
|
||||
return NextResponse.json({ error: "order_not_found", order_id: body.order_id }, { status: 404 });
|
||||
}
|
||||
const denied = tenantGuard(auth.ctx.tenantId, order.tenant_id);
|
||||
if (denied) return denied;
|
||||
try {
|
||||
const note = await addNote({
|
||||
order_id: body.order_id,
|
||||
tenant_id: order.tenant_id ?? null,
|
||||
author_id: auth.ctx.actorId,
|
||||
body: String(body.body),
|
||||
});
|
||||
await audit(note.tenant_id, auth.ctx.actorId, note.note_id, "order_note.created", {
|
||||
order_id: note.order_id,
|
||||
clock: note.clock,
|
||||
});
|
||||
return NextResponse.json(note, { status: 201 });
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(req: NextRequest) {
|
||||
const auth = await requireRouteAuth(req);
|
||||
if (auth.response) return auth.response;
|
||||
let body: { note_id?: string; body?: string; version?: number };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
if (!body.note_id || !body.body || !Number.isInteger(body.version)) {
|
||||
return NextResponse.json(
|
||||
{ error: "note_id, body and integer version are required" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
// Server-authoritative tenant check: slå upp noten (och dess order) INNAN
|
||||
// någon skrivning — klienten får aldrig säga vilken tenant en note tillhör.
|
||||
const existing = await findNote(body.note_id);
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: "note_not_found" }, { status: 404 });
|
||||
}
|
||||
const order = await getOrder(existing.order_id);
|
||||
const denied = tenantGuard(auth.ctx.tenantId, order?.tenant_id ?? existing.tenant_id);
|
||||
if (denied) return denied;
|
||||
try {
|
||||
const note = await updateNote({
|
||||
note_id: body.note_id,
|
||||
author_id: auth.ctx.actorId,
|
||||
body: String(body.body),
|
||||
expected_version: body.version as number,
|
||||
});
|
||||
await audit(note.tenant_id, auth.ctx.actorId, note.note_id, "order_note.updated", {
|
||||
order_id: note.order_id,
|
||||
version: note.version,
|
||||
clock: note.clock,
|
||||
});
|
||||
return NextResponse.json(note);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NoteVersionConflictError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "version_conflict",
|
||||
message: err.message,
|
||||
expected_version: err.expectedVersion,
|
||||
current_version: err.currentVersion,
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
if (err instanceof NoteNotFoundError) {
|
||||
return NextResponse.json({ error: "note_not_found" }, { status: 404 });
|
||||
}
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { engineFetch } from "@/lib/engine";
|
||||
|
||||
// POST /api/ai/parse (docs/04) — natural-language need -> prefilled order config.
|
||||
// Uses the engine's LLM when available; otherwise a transparent keyword heuristic.
|
||||
const MARKETS: [RegExp, string][] = [
|
||||
[/sverige|svensk|\bse\b/i, "SE"], [/norge|norsk|\bno\b/i, "NO"], [/danmark|dansk|\bdk\b/i, "DK"],
|
||||
[/finland|finsk|\bfi\b/i, "FI"], [/tyskland|\bde\b/i, "DE"], [/storbritannien|\buk\b|\bgb\b/i, "GB"],
|
||||
];
|
||||
const SERVICE: [RegExp, string][] = [
|
||||
[/skrap|scrap/i, "scraping"], [/mappa|matcha|match|koppla/i, "mapping"],
|
||||
[/normaliser|städ|dedup|tvätta/i, "normalization"], [/konsolider|crm|erp|hubspot|salesforce|dynamics|pipedrive|fivecrm/i, "consolidation"],
|
||||
[/dokument|ocr|pdf|scann/i, "documents"], [/berik|enrich/i, "enrichment"],
|
||||
[/\bicp\b|leads?|målgrupp|beslutsfattare/i, "icp"], [/\bml\b|modell|scoring|prognos|kluster/i, "ml"],
|
||||
[/\bbi\b|dashboard|analys|marknadsanalys/i, "bi"], [/flöde|feed|övervak|freshness/i, "feeds"],
|
||||
];
|
||||
const FIELDS: [RegExp, string][] = [
|
||||
[/e-?post|email|mejl|kontakt|telefon/i, "contact"], [/omsättning|finans|bokslut|resultat|nyckeltal/i, "financials"],
|
||||
[/lei|cross-?border/i, "lei"], [/huvudman|ubo|ägar/i, "ubo"], [/intent|köpsignal|signal/i, "intent"],
|
||||
];
|
||||
const DEST: [RegExp, string][] = [
|
||||
[/hubspot/i, "HubSpot"], [/salesforce/i, "Salesforce"], [/dynamics/i, "Microsoft Dynamics"],
|
||||
[/pipedrive/i, "Pipedrive"], [/fivecrm/i, "FiveCRM"], [/sheets/i, "Google Sheets"],
|
||||
];
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
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 }) });
|
||||
if (eng && eng.ok) return NextResponse.json(await eng.json());
|
||||
|
||||
const pick = (table: [RegExp, string][]) => table.filter(([re]) => re.test(text)).map(([, v]) => v);
|
||||
const markets = [...new Set(pick(MARKETS))];
|
||||
const service = pick(SERVICE)[0] ?? "data";
|
||||
const fields = [...new Set(pick(FIELDS))];
|
||||
const destination = pick(DEST)[0] ?? null;
|
||||
const volMatch = text.replace(/\s/g, "").match(/(\d{3,})/);
|
||||
const volume = volMatch ? Math.min(1_000_000, parseInt(volMatch[1], 10)) : 5000;
|
||||
|
||||
return NextResponse.json({
|
||||
config: {
|
||||
service_type: service,
|
||||
markets: markets.length ? markets : ["SE"],
|
||||
type: "Bolag",
|
||||
fieldIds: fields.length ? fields : ["lei"],
|
||||
enrichmentIds: [],
|
||||
volume,
|
||||
frequency: service === "feeds" || service === "enrichment" ? "Veckovis" : "Engångs",
|
||||
confidence: 92,
|
||||
destination,
|
||||
description: text,
|
||||
},
|
||||
rationale: `Tolkat som ${service}${markets.length ? ` · ${markets.join(", ")}` : ""}${destination ? ` · ${destination}` : ""}. Justera fritt.`,
|
||||
heuristic: true,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
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;
|
||||
}
|
||||
|
||||
// POST /api/auth/login — guarded dev login (scaffold). Requires AUTH_SECRET +
|
||||
// a matching DEV_LOGIN_KEY. Never available in production; real login is GET.
|
||||
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 },
|
||||
);
|
||||
}
|
||||
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);
|
||||
if (!keysMatch) {
|
||||
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 });
|
||||
}
|
||||
const token = await signSession({ email, exp: Date.now() + 7 * 24 * 60 * 60 * 1000 });
|
||||
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,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { SESSION_COOKIE } from "@/lib/auth";
|
||||
|
||||
// POST /api/auth/logout — clear the session cookie.
|
||||
export async function POST() {
|
||||
const res = NextResponse.json({ ok: true });
|
||||
res.cookies.set(SESSION_COOKIE, "", { path: "/", maxAge: 0 });
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
// GET /api/catalog (docs/04) — ready-made datasets. Static seed until DB is provisioned.
|
||||
const CATALOG = [
|
||||
{ id: "nordic-companies", title: "Nordic company data", markets: ["SE", "NO", "DK", "FI"], entity_type: "company", count: 4_900_000, updated: "daily", price_ore: 89500, confidence: 0.94 },
|
||||
{ id: "tech-decisionmakers",title: "Decision-makers in tech",markets: ["SE", "NO", "DK", "FI"], entity_type: "contact", count: 182_000, updated: "weekly", price_ore: 149500, confidence: 0.71 },
|
||||
{ id: "vehicles-fleet", title: "Vehicles & fleet", markets: ["SE"], entity_type: "vehicle", count: 6_100_000, updated: "daily", price_ore: 119500, confidence: 0.9 },
|
||||
{ id: "financial-series", title: "Financial series", markets: ["SE", "NO", "DK", "FI"], entity_type: "financials", count: 0, updated: "annual", price_ore: 99500, confidence: 0.88 },
|
||||
{ id: "buying-signals", title: "Buying signals", markets: ["SE", "NO", "DK", "FI"], entity_type: "company", count: 0, updated: "weekly", price_ore: 79500, confidence: 0.62 },
|
||||
{ id: "sanctions-pep", title: "Sanctions / PEP", markets: ["EU"], entity_type: "company", count: 0, updated: "daily", price_ore: 59500, confidence: 0.95 },
|
||||
];
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json(CATALOG);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
// POST /api/connections/db-grant (docs/04, docs/08) — accept a customer-created
|
||||
// read-only, time-boxed DB role. Connection string is stored ENCRYPTED (AES-GCM
|
||||
// via GRANT_ENC_KEY), never in plaintext, and deleted after the job. Env-guarded.
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
if (!process.env.GRANT_ENC_KEY) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: "grants_not_configured",
|
||||
message: "DB-åtkomst aktiveras när GRANT_ENC_KEY är satt. Skapa en read-only, tidsbegränsad roll åt oss — vi efterfrågar aldrig admin.",
|
||||
},
|
||||
},
|
||||
{ status: 501 },
|
||||
);
|
||||
}
|
||||
// With GRANT_ENC_KEY: validate read-only, AES-GCM encrypt conn_string, store, audit.
|
||||
return NextResponse.json({ grant_id: crypto.randomUUID(), status: "pending", order_id: body?.order_id ?? null }, { status: 201 });
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { computeEstimate, type EntityType, type Frequency } from "@/lib/data";
|
||||
import { engineFetch } from "@/lib/engine";
|
||||
|
||||
// POST /api/estimates (docs/04) — price/time/confidence for a configured job.
|
||||
// Single source of truth for the estimate math; the configurator calls this.
|
||||
export async function POST(req: NextRequest) {
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
body = await req.json();
|
||||
} 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) });
|
||||
if (eng && eng.ok) return NextResponse.json(await eng.json());
|
||||
|
||||
const markets = Array.isArray(body.markets) ? (body.markets as string[]) : [];
|
||||
const entity_type = (body.entity_type as EntityType) || "Bolag";
|
||||
const fields = Array.isArray(body.fields) ? (body.fields as string[]) : [];
|
||||
const enrichment = Array.isArray(body.enrichment) ? (body.enrichment as string[]) : [];
|
||||
const volume = Number(body.volume) || 1000;
|
||||
const frequency = (body.frequency as Frequency) || "Engångs";
|
||||
const confidence_target = Number(body.confidence_target) || 92;
|
||||
|
||||
const est = computeEstimate({
|
||||
markets,
|
||||
type: entity_type,
|
||||
fieldIds: fields,
|
||||
enrichmentIds: enrichment,
|
||||
volume,
|
||||
frequency,
|
||||
confidence: confidence_target,
|
||||
});
|
||||
|
||||
// amounts in öre (docs/03 convention)
|
||||
return NextResponse.json({
|
||||
total_ore: est.price * 100,
|
||||
deposit_ore: est.deposit * 100,
|
||||
balance_ore: est.remainder * 100,
|
||||
est_days: est.timelineDays,
|
||||
est_confidence: est.estConfidence / 100,
|
||||
recurring: est.recurring,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { checkAllDependencies, hasDegradedDependency } from "@/lib/health-checks";
|
||||
|
||||
// GET /api/health — liveness (docs/04, BACKLOG P0-3).
|
||||
//
|
||||
// Fixed finding: this used to hardcode `ok: true` and only ever check
|
||||
// *presence* of DATABASE_URL/REDIS_URL, never whether anything was actually
|
||||
// reachable -- "an uptime monitor watching HTTP 200 would show green for a
|
||||
// dying instance" (docs/architecture/ARCHITECTURE.md). Each dependency below
|
||||
// now reports a real state: "ok" (live round trip succeeded), "error"
|
||||
// (configured but unreachable -- see `detail`), "not_configured", or
|
||||
// "not_integrated" (env var present but no client code reads it -- honest
|
||||
// about `queue`, which has no wired Redis client in this repo).
|
||||
//
|
||||
// This route stays a LIVENESS check: it always answers 200 as long as the
|
||||
// process itself can run the handler (that's what "liveness" means -- an
|
||||
// external dependency outage is not a reason to restart this instance). The
|
||||
// body's `ok` field is the honest signal instead: false whenever a
|
||||
// dependency that IS configured is failing. For a readiness gate that DOES
|
||||
// fail closed on missing/broken dependencies, see GET /api/ready.
|
||||
export async function GET() {
|
||||
const deps = await checkAllDependencies();
|
||||
const degraded = hasDegradedDependency(deps);
|
||||
|
||||
return NextResponse.json({
|
||||
ok: !degraded,
|
||||
service: "0pt-web",
|
||||
db: deps.db.status,
|
||||
queue: deps.queue.status,
|
||||
engine: deps.engine.status,
|
||||
stripe: deps.stripe.status,
|
||||
...(degraded
|
||||
? {
|
||||
detail: Object.fromEntries(
|
||||
Object.entries(deps)
|
||||
.filter(([, v]) => v.status === "error")
|
||||
.map(([k, v]) => [k, v.detail]),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
ts: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getOwnedOrder, setOwnedStatusIfCurrent } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
|
||||
// 0pt#53: durable-store failures arrive as SiaxError(DEPENDENCY_UNAVAILABLE, 503);
|
||||
// map them instead of letting App Router render an opaque 500.
|
||||
async function readOwnedOrder(id: string, tenantId: string) {
|
||||
try {
|
||||
return await getOwnedOrder(id, tenantId);
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/orders/{id}
|
||||
export async function GET(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
const { id } = await ctx.params;
|
||||
const order = await readOwnedOrder(id, auth.owner.tenantId);
|
||||
if (order instanceof NextResponse) return order;
|
||||
if (!order) return NextResponse.json({ error: { code: "not_found", message: "Order saknas" } }, { status: 404 });
|
||||
return NextResponse.json(order);
|
||||
}
|
||||
|
||||
// PATCH /api/orders/{id} — status transition (deposit → in_production → review → accepted ...).
|
||||
// Escrow rule (docs/01): balance never charged before 'accepted'. Stripe wiring follows.
|
||||
export async function PATCH(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
const { id } = await ctx.params;
|
||||
let body: { status?: string };
|
||||
try {
|
||||
body = await req.json();
|
||||
} 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 });
|
||||
}
|
||||
// Paid states are owned exclusively by the signed, matching Stripe webhook.
|
||||
if (body.status === "in_production" || body.status === "delivered") {
|
||||
return NextResponse.json({ error: { code: "payment_event_required" } }, { status: 403 });
|
||||
}
|
||||
const allowed = ["quoted", "deposit_pending", "review", "revision", "accepted"];
|
||||
if (!body.status || !allowed.includes(body.status)) {
|
||||
return NextResponse.json({ error: { code: "bad_status", message: "Ogiltig status" } }, { status: 400 });
|
||||
}
|
||||
const order = await readOwnedOrder(id, auth.owner.tenantId);
|
||||
if (order instanceof NextResponse) return order;
|
||||
if (!order) return NextResponse.json({ error: { code: "not_found", message: "Order saknas" } }, { status: 404 });
|
||||
const previous: Record<string, string[]> = {
|
||||
quoted: ["draft"],
|
||||
deposit_pending: ["draft", "quoted"],
|
||||
review: ["in_production"],
|
||||
revision: ["review"],
|
||||
accepted: ["review", "revision"],
|
||||
};
|
||||
if (!previous[body.status]?.includes(order.status)) {
|
||||
return NextResponse.json({ error: { code: "invalid_transition" } }, { status: 409 });
|
||||
}
|
||||
let updated;
|
||||
try {
|
||||
updated = await setOwnedStatusIfCurrent(id, auth.owner.tenantId, order.status, body.status);
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
if (!updated) return NextResponse.json({ error: { code: "stale_transition" } }, { status: 409 });
|
||||
return NextResponse.json(updated);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { listOwnedOrders } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
|
||||
/**
|
||||
* GET /api/orders/export (våg 3.4, DoD §56) — CSV-export of the authenticated
|
||||
* owner's orders. Same fail-closed auth as GET/POST /api/orders (this path is
|
||||
* outside middleware.ts's /api/0pt matcher, so the Zitadel verifier runs here).
|
||||
*
|
||||
* RFC 4180: CRLF line endings, fields containing comma, quote or newline are
|
||||
* quoted with doubled quotes, header row always present.
|
||||
*
|
||||
* Locale note: deposit_ore / total_ore are exported as RAW ÖRE — öre is the
|
||||
* canonical unit in the order contract; formatting (SEK, thousand separators)
|
||||
* happens in the UI layer, never in the export.
|
||||
*
|
||||
* Cap note (DoD §56): NO row truncation/limiting — an export must be complete.
|
||||
*/
|
||||
|
||||
function csvEscape(value: string): string {
|
||||
if (/[",\r\n]/.test(value)) return `"${value.replace(/"/g, '""')}"`;
|
||||
return value;
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
try {
|
||||
const orders = await listOwnedOrders(auth.owner.tenantId);
|
||||
const header = ["order_id", "flow", "status", "deposit_ore", "total_ore"];
|
||||
const rows = orders.map((o) =>
|
||||
[o.order_id, o.flow, o.status, String(o.deposit_ore), String(o.total_ore)].map(csvEscape).join(","),
|
||||
);
|
||||
const csv = [header.join(","), ...rows].join("\r\n") + "\r\n";
|
||||
const date = new Date().toISOString().slice(0, 10);
|
||||
return new NextResponse(csv, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="orders-${date}.csv"`,
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createOrder, type OrderConfig, type OrderOwner } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
|
||||
import { createAud0Client } from "@/src/clients/aud0-client";
|
||||
import { validateRows, defineMapping, type RowError } from "@siax/contracts/import-export";
|
||||
import { serviceById, type Flow } from "@/lib/services";
|
||||
import { IMPORT_DISPATCH_POLICY, evaluateImportDispatch } from "@/lib/import-dispatch-policy";
|
||||
import { ENTITY_TYPES, FREQUENCIES, type EntityType, type Frequency } from "@/lib/data";
|
||||
|
||||
// C8: CSV-import of orders — the symmetric counterpart of GET /api/orders/export
|
||||
// (våg 3.4). The server is the ONLY authority: the raw CSV is parsed here
|
||||
// (RFC 4180, no eval), re-validated here via the frozen @siax/contracts kernel
|
||||
// (validateRows) plus host field rules, and executed through the EXISTING order
|
||||
// creation logic (createOrder) so imported rows are real tenant-owned orders.
|
||||
// Client-side wizard parsing is presentation entropy, never trusted.
|
||||
//
|
||||
// Fail-closed properties:
|
||||
// - No principal (requireOrderOwner) → 401, no parse, no writes.
|
||||
// - Unknown header column → 400 (never silently dropped).
|
||||
// - More than MAX_IMPORT_ROWS data rows → 413 (cap, never truncate silently).
|
||||
// - execute() re-validates and imports only rows that pass; failing rows are
|
||||
// reported per row (row/field/code) and never created. Each order insert is
|
||||
// individually atomic via createOrder (per-row transactional semantics);
|
||||
// a failing row can never corrupt a passing one.
|
||||
// - Audit: every successful execute emits an AUD0 event via 0pt's sole producer
|
||||
// boundary (durable outbox when DATABASE_URL is configured). Emission failure
|
||||
// is logged, never blocks the import (the outbox pattern owns delivery).
|
||||
|
||||
// DES1GN ADR D3 (§31): taken härstammar från ImportDispatchPolicy — ett objekt,
|
||||
// en sanning. Inline-taket är oförändrat (500); rader > policy.maxRows (5000)
|
||||
// är N0D-dispatch-signalen (descriptor-gate: svarar 413 + hint tills N0D-workern
|
||||
// är verifierad — aldrig tyst trunkering, aldrig tyst dispatch).
|
||||
export const MAX_IMPORT_ROWS = IMPORT_DISPATCH_POLICY.maxInlineRows;
|
||||
const MAX_CSV_CHARS = IMPORT_DISPATCH_POLICY.maxBytes;
|
||||
const IMPORT_COLUMNS = ["flow", "service_type", "type", "volume", "frequency", "markets"] as const;
|
||||
const FLOWS: readonly Flow[] = ["catalog", "custom", "subscription"];
|
||||
const MAX_VOLUME = 1_000_000;
|
||||
|
||||
interface ImportRowError extends RowError {
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface ParsedCsv {
|
||||
rows: Record<string, string>[];
|
||||
headerError?: string;
|
||||
}
|
||||
|
||||
/** Minimal RFC 4180 parser: quoted fields, doubled quotes, CRLF or LF. No eval. */
|
||||
export function parseCsv(text: string): ParsedCsv {
|
||||
const rows: string[][] = [];
|
||||
let field = "";
|
||||
let row: string[] = [];
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (inQuotes) {
|
||||
if (ch === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i++;
|
||||
} else {
|
||||
inQuotes = false;
|
||||
}
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
} else if (ch === '"') {
|
||||
inQuotes = true;
|
||||
} else if (ch === ",") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
} else if (ch === "\n") {
|
||||
row.push(field);
|
||||
field = "";
|
||||
rows.push(row);
|
||||
row = [];
|
||||
} else if (ch === "\r") {
|
||||
// consumed by the following \n (or ignored for bare CR)
|
||||
} else {
|
||||
field += ch;
|
||||
}
|
||||
}
|
||||
if (field.length > 0 || row.length > 0) {
|
||||
row.push(field);
|
||||
rows.push(row);
|
||||
}
|
||||
const nonEmpty = rows.filter((r) => r.length > 1 || (r[0] ?? "").trim() !== "");
|
||||
if (nonEmpty.length === 0) return { rows: [] };
|
||||
const header = nonEmpty[0].map((h) => h.trim().toLowerCase());
|
||||
const unknown = header.filter((h) => h !== "" && !(IMPORT_COLUMNS as readonly string[]).includes(h));
|
||||
if (unknown.length > 0) {
|
||||
return { rows: [], headerError: `Okänd kolumn: ${unknown.join(", ")} (tillåtna: ${IMPORT_COLUMNS.join(", ")})` };
|
||||
}
|
||||
return {
|
||||
rows: nonEmpty.slice(1).map((cells) => {
|
||||
const obj: Record<string, string> = {};
|
||||
header.forEach((h, idx) => {
|
||||
if (h) obj[h] = (cells[idx] ?? "").trim();
|
||||
});
|
||||
return obj;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Host field rules on top of the kernel's required/type checks. */
|
||||
function hostValidate(rows: Record<string, string>[]): ImportRowError[] {
|
||||
const errors: ImportRowError[] = [];
|
||||
rows.forEach((r, idx) => {
|
||||
const rowNo = idx + 1;
|
||||
const flow = (r.flow ?? "").trim() as Flow;
|
||||
if (flow && !FLOWS.includes(flow)) {
|
||||
errors.push({ row: rowNo, field: "flow", code: "bad_type", message: `Ogiltigt flow "${r.flow}" (tillåtna: ${FLOWS.join(", ")})` });
|
||||
}
|
||||
const st = (r.service_type ?? "").trim();
|
||||
if (st && !serviceById(st)) {
|
||||
errors.push({ row: rowNo, field: "service_type", code: "bad_type", message: `Okänd service_type "${st}"` });
|
||||
}
|
||||
const type = (r.type ?? "").trim();
|
||||
if (type && !ENTITY_TYPES.some((t) => t.id === type)) {
|
||||
errors.push({ row: rowNo, field: "type", code: "bad_type", message: `Ogiltig typ "${type}" (tillåtna: ${ENTITY_TYPES.map((t) => t.id).join(", ")})` });
|
||||
}
|
||||
const volume = (r.volume ?? "").trim();
|
||||
if (volume === "") {
|
||||
// optional — order logic applies flow defaults
|
||||
} else if (!/^\d+$/.test(volume) || Number(volume) < 1 || Number(volume) > MAX_VOLUME) {
|
||||
errors.push({ row: rowNo, field: "volume", code: "bad_type", message: `volume måste vara ett positivt heltal ≤ ${MAX_VOLUME}` });
|
||||
}
|
||||
const freq = (r.frequency ?? "").trim();
|
||||
if (freq && !FREQUENCIES.includes(freq as Frequency)) {
|
||||
errors.push({ row: rowNo, field: "frequency", code: "bad_type", message: `Ogiltig frequency "${freq}" (tillåtna: ${FREQUENCIES.join(", ")})` });
|
||||
}
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
|
||||
function buildConfig(r: Record<string, string>): OrderConfig {
|
||||
const config: OrderConfig = {};
|
||||
if ((r.service_type ?? "").trim()) config.service_type = r.service_type.trim();
|
||||
if ((r.type ?? "").trim()) config.type = r.type.trim() as EntityType;
|
||||
if ((r.volume ?? "").trim()) config.volume = Number(r.volume.trim());
|
||||
if ((r.frequency ?? "").trim()) config.frequency = r.frequency.trim() as Frequency;
|
||||
if ((r.markets ?? "").trim()) {
|
||||
config.markets = r.markets.split(";").map((m) => m.trim()).filter(Boolean);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
export interface ImportReport {
|
||||
totalRows: number;
|
||||
validRows: number;
|
||||
errorCount: number;
|
||||
errors: ImportRowError[];
|
||||
}
|
||||
|
||||
/** Server-authoritative validation: kernel required/type checks + host rules. */
|
||||
export function validateImport(csv: string): { report: ImportReport; rows: Record<string, string>[]; headerError?: string } {
|
||||
const { rows, headerError } = parseCsv(csv);
|
||||
if (headerError) return { report: { totalRows: 0, validRows: 0, errorCount: 1, errors: [{ row: 0, field: "header", code: "format", message: headerError }] }, rows: [], headerError };
|
||||
const mapping = defineMapping({ columns: IMPORT_COLUMNS.map((c) => ({ source: c, target: c, required: c === "flow" })) });
|
||||
const kernel = validateRows(rows, mapping);
|
||||
const host = hostValidate(rows);
|
||||
const kernelErrors: ImportRowError[] = kernel.errors.map((e) => ({ ...e, message: e.message ?? `Valideringsfel (${e.code})` }));
|
||||
const errors = [...kernelErrors, ...host];
|
||||
return {
|
||||
report: {
|
||||
totalRows: rows.length,
|
||||
validRows: rows.length - new Set(errors.map((e) => e.row)).size,
|
||||
errorCount: errors.length,
|
||||
errors,
|
||||
},
|
||||
rows,
|
||||
};
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
const owner: OrderOwner = auth.owner;
|
||||
|
||||
let body: { mode?: string; csv?: string };
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: { code: "bad_json", message: "Invalid JSON" } }, { status: 400 });
|
||||
}
|
||||
const mode = body.mode;
|
||||
const csv = body.csv;
|
||||
if (!mode || !["validate", "dry_run", "execute"].includes(mode)) {
|
||||
return NextResponse.json({ error: { code: "bad_mode", message: "mode måste vara validate | dry_run | execute" } }, { status: 400 });
|
||||
}
|
||||
if (typeof csv !== "string" || csv.trim() === "") {
|
||||
return NextResponse.json({ error: { code: "bad_csv", message: "csv saknas eller är tom" } }, { status: 400 });
|
||||
}
|
||||
const csvBytes = Buffer.byteLength(csv, "utf8");
|
||||
if (evaluateImportDispatch({ format: "csv", bytes: csvBytes, rows: 0 }).verdict === "byte_cap_exceeded") {
|
||||
return NextResponse.json({ error: { code: "csv_too_large", message: `CSV större än ${MAX_CSV_CHARS} bytes` } }, { status: 413 });
|
||||
}
|
||||
try {
|
||||
const { report, rows, headerError } = validateImport(csv);
|
||||
if (headerError) {
|
||||
return NextResponse.json({ error: { code: "bad_header", message: headerError }, report }, { status: 400 });
|
||||
}
|
||||
const dispatchVerdict = evaluateImportDispatch({ format: "csv", bytes: csvBytes, rows: rows.length });
|
||||
if (dispatchVerdict.verdict === "dispatch_n0d") {
|
||||
// DES1GN D3-signalen: den här volymen ÄR ett N0D-jobb (0pt.import_execute_job).
|
||||
// Descriptor-gaten är stängd (N0D-worker UNVERIFIED) -> fail-closed 413 med hint.
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: "n0d_dispatch_required",
|
||||
message: `Import med ${rows.length} rader ska köras som N0D-jobb (0pt.import_execute_job); dispatch är ännu inte aktiverad`,
|
||||
hint: { capability_id: "0pt.import_execute", job_type: "0pt.import_execute_job", status: "UNVERIFIED" },
|
||||
},
|
||||
},
|
||||
{ status: 413 },
|
||||
);
|
||||
}
|
||||
if (dispatchVerdict.verdict === "row_cap_exceeded") {
|
||||
return NextResponse.json({ error: { code: "row_cap_exceeded", message: `Max ${MAX_IMPORT_ROWS} rader per import` } }, { status: 413 });
|
||||
}
|
||||
|
||||
if (mode === "validate" || mode === "dry_run") {
|
||||
// No writes — dry_run is exactly validate plus an explicit rehearsal count.
|
||||
return NextResponse.json({ mode, ...report, would_import: report.validRows });
|
||||
}
|
||||
|
||||
// mode === "execute": server re-validates and imports ONLY passing rows.
|
||||
const failedRows = new Set(report.errors.map((e) => e.row));
|
||||
const orderIds: string[] = [];
|
||||
let imported = 0;
|
||||
for (let idx = 0; idx < rows.length; idx++) {
|
||||
if (failedRows.has(idx + 1)) continue;
|
||||
const r = rows[idx];
|
||||
try {
|
||||
const { order } = await createOrder((r.flow ?? "").trim(), buildConfig(r), undefined, owner);
|
||||
orderIds.push(order.order_id);
|
||||
imported++;
|
||||
} catch (err: unknown) {
|
||||
report.errors.push({ row: idx + 1, field: "row", code: "format", message: `Skapning misslyckades: ${err instanceof Error ? err.message : "okänt fel"}` });
|
||||
}
|
||||
}
|
||||
|
||||
// AUD0 audit — 0pt's sole producer boundary; durable outbox under DATABASE_URL.
|
||||
try {
|
||||
const aud0 = createAud0Client();
|
||||
await aud0.ingestEvent({
|
||||
event_id: (globalThis.crypto?.randomUUID?.() ?? `evt-${Date.now()}`),
|
||||
event_type: "0pt.orders.import",
|
||||
tenant_id: owner.tenantId,
|
||||
project_id: "0pt-orders",
|
||||
actor_id: owner.subject,
|
||||
app_id: "0pt",
|
||||
capability_id: "orders.import",
|
||||
resource_type: "order",
|
||||
resource_id: orderIds[0] ?? "none",
|
||||
risk_level: "L2",
|
||||
payload: { imported, total_rows: report.totalRows, error_count: report.errors.length, order_ids: orderIds },
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
} catch (auditErr: unknown) {
|
||||
console.error("[0pt-orders-import] AUD0 emission failed (import not rolled back):", auditErr);
|
||||
}
|
||||
|
||||
return NextResponse.json({ mode, imported, totalRows: report.totalRows, validRows: report.validRows, errorCount: report.errors.length, errors: report.errors.slice(0, 100), order_ids: orderIds });
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createOrder, listOwnedOrders, IdempotencyKeyConflictError, type OrderConfig } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { resolveAdvanceAction, buildOrderInboxItem } from "@/lib/order-flow";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../siax-error-mapping";
|
||||
|
||||
// POST /api/orders (docs/04) — create a draft order from a configurator config.
|
||||
// A payable order is created only for a verified Zitadel tenant/buyer.
|
||||
// Anonymous prospects may obtain estimates but cannot mint payment orders.
|
||||
//
|
||||
// P014: honors an optional `Idempotency-Key` header (the convention this
|
||||
// skill's own docs already name -- "Idempotency-Key on order/payment POSTs")
|
||||
// so a retried submission (double-click, dropped response, proxy replay)
|
||||
// returns the ORIGINAL order (200) instead of creating a duplicate (was:
|
||||
// no idempotency mechanism at all -- every retry created a new row, P014
|
||||
// recon "Duplicate delivery idempotent: NOT MET"). Omitting the header keeps
|
||||
// the pre-P014 behavior exactly: every call creates a fresh order.
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
let body: { flow?: string; config?: OrderConfig };
|
||||
try {
|
||||
body = await req.json();
|
||||
} 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 idempotencyKey = req.headers.get("idempotency-key") ?? undefined;
|
||||
try {
|
||||
const { order, replayed } = await createOrder(flow, config, idempotencyKey, auth.owner);
|
||||
return NextResponse.json(
|
||||
{ order_id: order.order_id, status: order.status, deposit_ore: order.deposit_ore, total_ore: order.total_ore },
|
||||
{ status: replayed ? 200 : 201 },
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof IdempotencyKeyConflictError) {
|
||||
return NextResponse.json({ error: { code: "idempotency_key_conflict", message: err.message } }, { status: 409 });
|
||||
}
|
||||
// 0pt#53: getSqlForDurableStore throws SiaxError(DEPENDENCY_UNAVAILABLE, 503) when
|
||||
// production has no DATABASE_URL — surface it as documented, not opaque 500.
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/orders — list all orders (queue + financial aggregates). This is
|
||||
// outside middleware.ts's matcher (/api/0pt/:path* only), so auth is enforced
|
||||
// here directly via the same fail-closed Zitadel verifier — see
|
||||
// src/auth/require-route-auth.ts for why the request is re-verified rather
|
||||
// than trusting a forwarded header.
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
try {
|
||||
const orders = await listOwnedOrders(auth.owner.tenantId);
|
||||
// ADR-0001: servern resolvér advance-aktionen per order — klienten
|
||||
// renderar bara (ActionGate). Policy ägs här, inte i UI-lagret.
|
||||
const withActions = orders.map((o) => ({ ...o, advance_action: resolveAdvanceAction(o.status), inbox_item: buildOrderInboxItem(o) }));
|
||||
return NextResponse.json(withActions);
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getOwnedOrder } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../../siax-error-mapping";
|
||||
|
||||
// POST /api/payments/[order_id]/deposit
|
||||
// Returns { url } for Stripe Checkout. Returns 501 when STRIPE_SECRET_KEY is absent.
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ order_id: string }> },
|
||||
) {
|
||||
const auth = await requireOrderOwner(request);
|
||||
if (auth.response) return auth.response;
|
||||
const { order_id } = await params;
|
||||
|
||||
const secretKey = process.env.STRIPE_SECRET_KEY;
|
||||
if (!secretKey) {
|
||||
return NextResponse.json({ error: "payment_not_configured" }, { status: 501 });
|
||||
}
|
||||
|
||||
// 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 order;
|
||||
try {
|
||||
order = await getOwnedOrder(order_id, auth.owner.tenantId);
|
||||
} catch (err: unknown) {
|
||||
// 0pt#53: durable-store failure -> documented DEPENDENCY_UNAVAILABLE/503.
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
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",
|
||||
"line_items[0][price_data][currency]": "sek",
|
||||
"line_items[0][price_data][product_data][name]": "0pt data deposit",
|
||||
"line_items[0][price_data][unit_amount]": String(depositOre),
|
||||
"line_items[0][quantity]": "1",
|
||||
mode: "payment",
|
||||
"metadata[order_id]": order_id,
|
||||
"metadata[kind]": "deposit",
|
||||
success_url: `${origin}/order/${order_id}?deposit=success`,
|
||||
cancel_url: `${origin}/bestall/forskott?order=${order_id}`,
|
||||
});
|
||||
|
||||
const stripeRes = await fetch("https://api.stripe.com/v1/checkout/sessions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${secretKey}`,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body,
|
||||
});
|
||||
|
||||
if (!stripeRes.ok) {
|
||||
const err = (await stripeRes.json()) as { error?: { message?: string } };
|
||||
return NextResponse.json({ error: err.error?.message ?? "stripe_error" }, { status: 502 });
|
||||
}
|
||||
|
||||
const session = (await stripeRes.json()) as { url: string };
|
||||
return NextResponse.json({ url: session.url });
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getStripe } from "@/lib/stripe";
|
||||
import { getOwnedOrder } from "@/lib/orders-store";
|
||||
import { requireOrderOwner } from "@/src/auth/require-order-owner";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../../../siax-error-mapping";
|
||||
|
||||
// POST /api/payments/{order_id}/release (docs/04) — charge the held 50% balance.
|
||||
// Called on ACCEPT only; escrow balance is never charged before approval.
|
||||
export async function POST(req: NextRequest, ctx: { params: Promise<{ order_id: string }> }) {
|
||||
const auth = await requireOrderOwner(req);
|
||||
if (auth.response) return auth.response;
|
||||
const { order_id } = await ctx.params;
|
||||
let order;
|
||||
try {
|
||||
order = await getOwnedOrder(order_id, auth.owner.tenantId);
|
||||
} catch (err: unknown) {
|
||||
// 0pt#53: durable-store failure -> documented DEPENDENCY_UNAVAILABLE/503.
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
if (!order) return NextResponse.json({ error: { code: "not_found", message: "Order saknas" } }, { status: 404 });
|
||||
if (order.status !== "accepted") {
|
||||
return NextResponse.json({ error: { code: "not_accepted", message: "Balans frigörs först vid godkänd leverans" } }, { status: 409 });
|
||||
}
|
||||
|
||||
const stripe = getStripe();
|
||||
if (!stripe) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: "stripe_not_configured", message: "Stripe ej konfigurerad" } },
|
||||
{ status: 501 },
|
||||
);
|
||||
}
|
||||
|
||||
const origin = req.nextUrl.origin;
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
mode: "payment",
|
||||
line_items: [{
|
||||
quantity: 1,
|
||||
price_data: {
|
||||
currency: "sek",
|
||||
unit_amount: order.balance_ore,
|
||||
product_data: { name: `0pt order ${order_id} — slutbetalning 50 %` },
|
||||
},
|
||||
}],
|
||||
success_url: `${origin}/order/${order_id}/validera`,
|
||||
cancel_url: `${origin}/order/${order_id}/validera`,
|
||||
metadata: { order_id, kind: "balance" },
|
||||
});
|
||||
// Creating a Checkout Session is not payment. Only a verified paid webhook
|
||||
// may advance the order to delivered.
|
||||
return NextResponse.json({ checkout_url: session.url });
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { checkAllDependencies, isReady } from "@/lib/health-checks";
|
||||
|
||||
// GET /api/ready — readiness (BACKLOG P0-3, CD-04/OBS-04: "no /ready route
|
||||
// existed at all").
|
||||
//
|
||||
// Unlike GET /api/health (liveness -- always 200 while the process can
|
||||
// respond), this fails closed: 503 whenever a load-bearing dependency isn't
|
||||
// both configured AND actually reachable. Point a load balancer / Coolify
|
||||
// readiness probe at this route, not /api/health, to stop routing traffic to
|
||||
// an instance whose database is down without restarting it.
|
||||
//
|
||||
// Load-bearing by absence: only the database (see
|
||||
// `lib/health-checks.ts#isReady`) -- engine/stripe/queue are optional
|
||||
// integrations 0pt is designed to run without. Load-bearing by FAILURE: all
|
||||
// of them. A dependency somebody configured and that then fails a live round
|
||||
// trip makes this instance not-ready, whichever one it is.
|
||||
export async function GET() {
|
||||
const deps = await checkAllDependencies();
|
||||
const ready = isReady(deps);
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
ready,
|
||||
service: "0pt-web",
|
||||
db: deps.db.status,
|
||||
queue: deps.queue.status,
|
||||
engine: deps.engine.status,
|
||||
stripe: deps.stripe.status,
|
||||
ts: new Date().toISOString(),
|
||||
},
|
||||
{ status: ready ? 200 : 503 },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { engineFetch, hasEngine } from "@/lib/engine";
|
||||
|
||||
// An unavailable or malformed screening source is never evidence of no match.
|
||||
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 });
|
||||
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",
|
||||
});
|
||||
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(); }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* app/api/siax-error-mapping.ts — shared error mapper for the LEGACY routes
|
||||
* outside the /api/0pt matcher (`app/api/orders*`, `/subscriptions`,
|
||||
* `/payments/*`, `/webhooks/stripe`, `/admin/metrics`).
|
||||
*
|
||||
* 0pt#53: `getSqlForDurableStore` (lib/db.ts) throws
|
||||
* `SiaxError("DEPENDENCY_UNAVAILABLE")` (httpStatus 503, retryable) when a
|
||||
* money-bearing store would otherwise fall back to an in-memory Map in a
|
||||
* production runtime. The /api/0pt/* surface already maps that error via
|
||||
* src/http/siax-error-response.ts; these legacy routes did not, so the
|
||||
* documented 503 DEPENDENCY_UNAVAILABLE leaked as Next's opaque 500.
|
||||
*
|
||||
* The helpers preserve each route's OWN typed error contract
|
||||
* (IdempotencyKeyConflictError -> 409, etc.) and only ADD the SiaxError
|
||||
* branch — a plain rethrow is deliberately avoided because App Router turns
|
||||
* any uncaught thrown SiaxError into a generic 500 with no error body.
|
||||
*/
|
||||
import { NextResponse } from "next/server";
|
||||
import { SiaxError } from "@/src/platform/errors";
|
||||
|
||||
export function isSiaxError(error: unknown): error is SiaxError {
|
||||
return error instanceof SiaxError;
|
||||
}
|
||||
|
||||
/** Map a caught error to a NextResponse: SiaxError -> its pinned status/body. */
|
||||
export function siaxErrorResponseForLegacy(error: SiaxError): NextResponse {
|
||||
return NextResponse.json(error.toJSON(), { status: error.httpStatus });
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
// GET /api/sources (docs/04) — the transparency moat. Legal sourcing only (CLAUDE.md §1).
|
||||
// access: api | bulk | authorized_web | licensed. VERIFY current terms before relying.
|
||||
const SOURCES = [
|
||||
{ source_id: "gleif", name: "GLEIF (LEI)", market: "global", access: "api", licence: "open (CC0) — verify", cadence: "daily", confidence: 0.98 },
|
||||
{ source_id: "brreg", name: "Brønnøysundregistrene", market: "NO", access: "api", licence: "NLOD open — verify", cadence: "daily", confidence: 0.97 },
|
||||
{ source_id: "companies_house", name: "Companies House", market: "GB", access: "api", licence: "free (key) — verify", cadence: "daily", confidence: 0.97 },
|
||||
{ source_id: "cvr", name: "CVR / Virk", market: "DK", access: "api", licence: "terms apply — verify", cadence: "daily", confidence: 0.95 },
|
||||
{ source_id: "prh", name: "PRH avoindata", market: "FI", access: "api", licence: "CC-BY — verify", cadence: "daily", confidence: 0.93 },
|
||||
{ source_id: "bolagsverket", name: "Bolagsverket", market: "SE", access: "licensed", licence: "restricted bulk — partner route", cadence: "daily", confidence: 0.92 },
|
||||
{ source_id: "rdw", name: "RDW (vehicles)", market: "NL", access: "api", licence: "open — verify", cadence: "daily", confidence: 0.9 },
|
||||
{ source_id: "traficom", name: "Traficom (vehicles)", market: "FI", access: "bulk", licence: "CC-BY — verify", cadence: "quarterly", confidence: 0.88 },
|
||||
{ source_id: "opensanctions", name: "OpenSanctions", market: "global", access: "bulk", licence: "open — verify commercial terms", cadence: "daily", confidence: 0.95 },
|
||||
];
|
||||
|
||||
export async function GET() {
|
||||
return NextResponse.json(SOURCES);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createSubscription, listSubscriptions } from "@/lib/subscriptions-store";
|
||||
import { isSiaxError, siaxErrorResponseForLegacy } from "../siax-error-mapping";
|
||||
|
||||
// GET /api/subscriptions — feeds list. POST — convert an order to a recurring feed.
|
||||
export async function GET() {
|
||||
try {
|
||||
return NextResponse.json(await listSubscriptions());
|
||||
} catch (err: unknown) {
|
||||
// 0pt#53: durable-store failure -> documented DEPENDENCY_UNAVAILABLE/503.
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
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 });
|
||||
}
|
||||
try {
|
||||
const sub = await createSubscription(body.order_id, body.cadence ?? "weekly", body.webhook_url ?? null);
|
||||
return NextResponse.json(sub, { status: 201 });
|
||||
} catch (err: unknown) {
|
||||
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
// GET /api/uploads — list uploaded files. Returns 501 until storage is configured.
|
||||
export async function GET() {
|
||||
const haveR2 = process.env.R2_ACCESS_KEY_ID && process.env.R2_BUCKET && process.env.R2_ENDPOINT;
|
||||
if (!haveR2) {
|
||||
return NextResponse.json([], { status: 501 });
|
||||
}
|
||||
return NextResponse.json([]);
|
||||
}
|
||||
|
||||
// POST /api/uploads (docs/04) — issue a presigned R2 PUT URL. Env-guarded:
|
||||
// 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(
|
||||
{ error: { code: "storage_not_configured", message: "Filuppladdning aktiveras när R2/Blob är kopplat" } },
|
||||
{ status: 501 },
|
||||
);
|
||||
}
|
||||
// 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 },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { engineFetch, hasEngine } from "@/lib/engine";
|
||||
|
||||
// A missing record is distinct from an unavailable or malformed source.
|
||||
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 });
|
||||
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",
|
||||
});
|
||||
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(); }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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' } },
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
// 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');
|
||||
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 });
|
||||
}
|
||||
if (!sig) {
|
||||
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 });
|
||||
}
|
||||
if (
|
||||
event.type === 'checkout.session.completed' ||
|
||||
event.type === 'checkout.session.async_payment_succeeded'
|
||||
) {
|
||||
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 (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 —
|
||||
// the non-2xx keeps Stripe's delivery retry path open).
|
||||
let order;
|
||||
try {
|
||||
order = await getOrder(oid);
|
||||
} catch (err: unknown) {
|
||||
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.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 });
|
||||
}
|
||||
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 });
|
||||
}
|
||||
let delivered = false;
|
||||
try {
|
||||
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 });
|
||||
throw err;
|
||||
}
|
||||
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 });
|
||||
}
|
||||
let advanced = true;
|
||||
try {
|
||||
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 });
|
||||
throw err;
|
||||
}
|
||||
if (!advanced) {
|
||||
return NextResponse.json({ error: 'order_update_failed' }, { status: 503 });
|
||||
}
|
||||
}
|
||||
}
|
||||
return NextResponse.json({ received: true });
|
||||
}
|
||||
Reference in New Issue
Block a user