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
+38
View File
@@ -0,0 +1,38 @@
import { NextRequest, NextResponse } from "next/server";
import { listOrders } from "@/lib/orders-store";
import { requireRouteAuth } from "@/src/auth/require-route-auth";
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
// GET /api/admin/metrics — order queue + financial aggregates for the admin
// dashboard. Outside middleware.ts's matcher (/api/0pt/:path* only) and
// previously unauthenticated entirely, so auth is enforced here directly via
// the same fail-closed Zitadel verifier — see src/auth/require-route-auth.ts.
export async function GET(req: NextRequest) {
const auth = await requireRouteAuth(req);
if (auth.response) return auth.response;
let orders;
try {
orders = await listOrders();
} catch (err: unknown) {
// 0pt#53: durable-store failure -> documented DEPENDENCY_UNAVAILABLE/503.
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
throw err;
}
const byStatus: Record<string, number> = {};
let depositPaidOre = 0;
let pipelineOre = 0;
for (const o of orders) {
byStatus[o.status] = (byStatus[o.status] ?? 0) + 1;
if (o.status !== "draft") depositPaidOre += o.deposit_ore ?? 0;
pipelineOre += o.total_ore ?? 0;
}
return NextResponse.json({
total: orders.length,
by_status: byStatus,
in_production: byStatus["in_production"] ?? 0,
review: byStatus["review"] ?? 0,
delivered: byStatus["delivered"] ?? 0,
deposit_paid_ore: depositPaidOre,
pipeline_ore: pipelineOre,
});
}
+183
View File
@@ -0,0 +1,183 @@
import { NextRequest, NextResponse } from "next/server";
import { requireRouteAuth } from "@/src/auth/require-route-auth";
import { createAud0Client } from "@/src/clients/aud0-client";
import {
addNote,
findNote,
listNotes,
NoteNotFoundError,
NoteVersionConflictError,
updateNote,
} from "@/lib/order-notes-store";
import { getOrder } from "@/lib/orders-store";
import { isSiaxError, siaxErrorResponseForLegacy } from "../../siax-error-mapping";
// GET/POST/PATCH /api/admin/order-notes — persisted collaboration state på
// admin-orders (kernel: @siax/collaboration). Ligger utanför middleware.ts:s
// matcher (/api/0pt/*), så auth läggs på direkt via requireRouteAuth, precis
// som /api/admin/metrics — fail-closed Zitadel-verifiering, 401 utan token.
//
// Tenant-guard: tenant_id hämtas SERVER-SIDE från ordern (aldrig från
// klienten) och jämförs mot den verifierade kontextens tenant — mismatch är
// 403. Conflict semantics: PATCH med stale `version` -> 409 + aktuell version
// (optimistisk samtidighet; last-write-wins först EFTER en medveten reload).
const AUDIT_CAPABILITY = "admin.order_notes";
async function audit(
tenantId: string | null,
actorId: string,
resourceId: string,
eventType: string,
payload: unknown,
): Promise<void> {
// Best effort: AUD0 är evidence, inte en skriv-buffert — ett audit-fel får
// aldrig rulla tillbaka en lyckad note-skrivning.
try {
await createAud0Client().ingestEvent({
event_id: `aud_${crypto.randomUUID()}`,
event_type: eventType,
tenant_id: tenantId ?? "anonymous",
project_id: "0pt",
actor_id: actorId,
app_id: "0pt",
capability_id: AUDIT_CAPABILITY,
resource_type: "order_note",
resource_id: resourceId,
risk_level: "L1",
payload,
created_at: new Date().toISOString(),
});
} catch {
// swallow — see comment above
}
}
function tenantGuard(ctxTenant: string, orderTenant: string | null | undefined): NextResponse | null {
if (!orderTenant) return null; // legacy anonymous draft — admin-ytan får annotera
if (ctxTenant !== orderTenant) {
return NextResponse.json(
{
error: "OPT_ACCESS_DENIED",
message: "order belongs to a different tenant than the authenticated token",
details: { order_tenant: orderTenant },
},
{ status: 403 },
);
}
return null;
}
export async function GET(req: NextRequest) {
const auth = await requireRouteAuth(req);
if (auth.response) return auth.response;
const orderId = req.nextUrl.searchParams.get("order_id");
if (!orderId) {
return NextResponse.json({ error: "order_id query parameter is required" }, { status: 400 });
}
const order = await getOrder(orderId);
if (!order) {
return NextResponse.json({ error: "order_not_found", order_id: orderId }, { status: 404 });
}
const denied = tenantGuard(auth.ctx.tenantId, order.tenant_id);
if (denied) return denied;
const notes = await listNotes(orderId);
return NextResponse.json({ order_id: orderId, notes });
}
export async function POST(req: NextRequest) {
const auth = await requireRouteAuth(req);
if (auth.response) return auth.response;
let body: { order_id?: string; body?: string };
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
}
if (!body.order_id || !body.body || !String(body.body).trim()) {
return NextResponse.json(
{ error: "order_id and non-empty body are required" },
{ status: 400 },
);
}
const order = await getOrder(body.order_id);
if (!order) {
return NextResponse.json({ error: "order_not_found", order_id: body.order_id }, { status: 404 });
}
const denied = tenantGuard(auth.ctx.tenantId, order.tenant_id);
if (denied) return denied;
try {
const note = await addNote({
order_id: body.order_id,
tenant_id: order.tenant_id ?? null,
author_id: auth.ctx.actorId,
body: String(body.body),
});
await audit(note.tenant_id, auth.ctx.actorId, note.note_id, "order_note.created", {
order_id: note.order_id,
clock: note.clock,
});
return NextResponse.json(note, { status: 201 });
} catch (err: unknown) {
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
throw err;
}
}
export async function PATCH(req: NextRequest) {
const auth = await requireRouteAuth(req);
if (auth.response) return auth.response;
let body: { note_id?: string; body?: string; version?: number };
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });
}
if (!body.note_id || !body.body || !Number.isInteger(body.version)) {
return NextResponse.json(
{ error: "note_id, body and integer version are required" },
{ status: 400 },
);
}
// Server-authoritative tenant check: slå upp noten (och dess order) INNAN
// någon skrivning — klienten får aldrig säga vilken tenant en note tillhör.
const existing = await findNote(body.note_id);
if (!existing) {
return NextResponse.json({ error: "note_not_found" }, { status: 404 });
}
const order = await getOrder(existing.order_id);
const denied = tenantGuard(auth.ctx.tenantId, order?.tenant_id ?? existing.tenant_id);
if (denied) return denied;
try {
const note = await updateNote({
note_id: body.note_id,
author_id: auth.ctx.actorId,
body: String(body.body),
expected_version: body.version as number,
});
await audit(note.tenant_id, auth.ctx.actorId, note.note_id, "order_note.updated", {
order_id: note.order_id,
version: note.version,
clock: note.clock,
});
return NextResponse.json(note);
} catch (err: unknown) {
if (err instanceof NoteVersionConflictError) {
return NextResponse.json(
{
error: "version_conflict",
message: err.message,
expected_version: err.expectedVersion,
current_version: err.currentVersion,
},
{ status: 409 },
);
}
if (err instanceof NoteNotFoundError) {
return NextResponse.json({ error: "note_not_found" }, { status: 404 });
}
if (isSiaxError(err)) return siaxErrorResponseForLegacy(err);
throw err;
}
}