fix(recovery): restore source removed by production documentation merge

This commit is contained in:
2026-11-10 03:42:10 +01:00
parent 585bdd4b44
commit 3d2fc6f913
957 changed files with 115754 additions and 0 deletions
+52
View File
@@ -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);
}
}
+40
View File
@@ -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 },
);
}
}
+155
View File
@@ -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 },
);
}
+37
View File
@@ -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,
})),
});
}
+27
View File
@@ -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);
}
}
+91
View File
@@ -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 });
}
}
+64
View File
@@ -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);
}
+56
View File
@@ -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,
});
}
+454
View File
@@ -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 },
);
}
}
+241
View File
@@ -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 },
);
}
+44
View File
@@ -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);
}
}
+17
View File
@@ -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);
}
}
+101
View File
@@ -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 });
}
}
+84
View File
@@ -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);
}
+47
View File
@@ -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);
}
}
+70
View File
@@ -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);
}
}
+31
View File
@@ -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);
}
}
+52
View File
@@ -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);
}
}
+25
View File
@@ -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);
}
}
+49
View File
@@ -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);
}
}
+19
View File
@@ -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);
}
}
+58
View File
@@ -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);
}
}
+29
View File
@@ -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);
}
+60
View File
@@ -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);
}
}