CI (SIAX Cloud) / integration (push) Skipped
CI (SIAX Cloud) / sonar (push) Skipped
masterplan-lock / check (push) Successful in 7s
Security Scan (SIAX Cloud) / security (push) Successful in 16s
CI (SIAX Cloud) / security (push) Successful in 18s
masterplan-lock / check (pull_request) Successful in 8s
CI (SIAX Cloud) / quality (push) Failing after 33s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 22s
CI (SIAX Cloud) / integration (pull_request) Successful in 31s
CI (SIAX Cloud) / security (pull_request) Successful in 23s
CI (SIAX Cloud) / sonar (pull_request) Skipped
CI (SIAX Cloud) / quality (pull_request) Failing after 21s
Kernel 0.3.0 används som capability, inte som paket-dekor: - lib/order-notes-store.ts: varje note ÄR en CollaborationOperation; nextLamportClock för nya klockor, mergeOperationLog/compareOperations för deterministisk listning; optimistisk version -> 409 vid stale skrivning. - lib/order-notes-client.ts: kernel-CollaborationTransport över host-API; offline = medvetet no-op + varning (ingen tyst förlust), 409 -> ConflictError. - app/api/admin/order-notes: requireRouteAuth (fail-closed 401), server-authoritative tenant-guard (403), AUD0-audit via hostens klient. - app/admin/notes: admin-yta med offline-växel, konflikt-banner + reload. - sql/016_order_notes.sql: persistens (DB-tabell, version + Lamport-klocka). Tester: API (happy/conflict 409/empty/400/401/403/404), klient-adapter (offline no-op utan fetch, 409-mappning, presence), SSR-render. 18 nya test.
184 lines
6.2 KiB
TypeScript
184 lines
6.2 KiB
TypeScript
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;
|
|
}
|
|
}
|