diff --git a/src/app/api/tools/traffic-inspector/sessions/[id]/requests/route.ts b/src/app/api/tools/traffic-inspector/sessions/[id]/requests/route.ts new file mode 100644 index 0000000000..95dd5fa0c3 --- /dev/null +++ b/src/app/api/tools/traffic-inspector/sessions/[id]/requests/route.ts @@ -0,0 +1,62 @@ +/** + * POST /api/tools/traffic-inspector/sessions/[id]/requests — persist a live snapshot entry + * + * Accepts a JSON-encoded InterceptedRequest payload and appends it to the + * session request log, atomically incrementing request_count. Returns the + * assigned seq number so the caller can confirm persistence order. + * + * LOCAL_ONLY enforced by routeGuard at the /api/tools/ prefix level. + * + * Part of R5-5 (backend half): the frontend hook (F3 / useSessionRecorder.ts) + * is the corresponding caller that POSTs snapshots here on stop(). + */ + +import { buildErrorBody, sanitizeErrorMessage } from "@omniroute/open-sse/utils/error.ts"; +import { InspectorSessionRequestAppendSchema } from "@/shared/schemas/inspector"; +import { getSession, appendSessionRequest } from "@/lib/db/inspectorSessions"; + +interface Params { + params: Promise<{ id: string }>; +} + +export async function POST(request: Request, { params }: Params): Promise { + const { id } = await params; + + // Verify session exists before attempting to append + const session = getSession(id); + if (!session) { + return new Response(JSON.stringify(buildErrorBody(404, "Session not found")), { + status: 404, + headers: { "content-type": "application/json" }, + }); + } + + let body: unknown; + try { + body = await request.json(); + } catch { + return new Response(JSON.stringify(buildErrorBody(400, "Invalid JSON body")), { + status: 400, + headers: { "content-type": "application/json" }, + }); + } + + const parsed = InspectorSessionRequestAppendSchema.safeParse(body); + if (!parsed.success) { + return new Response( + JSON.stringify(buildErrorBody(400, parsed.error.issues[0]?.message ?? "Validation error")), + { status: 400, headers: { "content-type": "application/json" } } + ); + } + + try { + const seq = appendSessionRequest(id, parsed.data.payload); + return Response.json({ seq }, { status: 201 }); + } catch (err) { + const msg = sanitizeErrorMessage(err); + return new Response( + JSON.stringify(buildErrorBody(500, msg || "Failed to append session request")), + { status: 500, headers: { "content-type": "application/json" } } + ); + } +} diff --git a/src/lib/db/inspectorSessions.ts b/src/lib/db/inspectorSessions.ts index aae84257b5..faaee6081b 100644 --- a/src/lib/db/inspectorSessions.ts +++ b/src/lib/db/inspectorSessions.ts @@ -77,8 +77,9 @@ export function getSession(id: string): InspectorSessionRow | null { return row ? mapSessionRow(row) : null; } -export function appendSessionRequest(sessionId: string, payload: string): void { +export function appendSessionRequest(sessionId: string, payload: string): number { const db = getDbInstance(); + let insertedSeq = 0; const runTransaction = db.transaction(() => { // Get next seq atomically within transaction @@ -97,9 +98,12 @@ export function appendSessionRequest(sessionId: string, payload: string): void { db.prepare( "UPDATE inspector_sessions SET request_count = request_count + 1 WHERE id = ?" ).run(sessionId); + + insertedSeq = nextSeq; }); runTransaction(); + return insertedSeq; } export function getSessionRequests(sessionId: string): Array<{ seq: number; payload: string }> { diff --git a/src/shared/schemas/inspector.ts b/src/shared/schemas/inspector.ts index 6fb3e59f9a..a474d4362b 100644 --- a/src/shared/schemas/inspector.ts +++ b/src/shared/schemas/inspector.ts @@ -32,6 +32,11 @@ export const InspectorAnnotationPutSchema = z.object({ annotation: z.string().max(10_000), }); +// 1 MB cap — matches INSPECTOR_MAX_BODY_KB constant +export const InspectorSessionRequestAppendSchema = z.object({ + payload: z.string().max(1_048_576), +}); + export const InspectorListQuerySchema = z.object({ profile: z.enum(["llm", "custom", "all"]).optional(), host: z.string().optional(), diff --git a/tests/integration/traffic-inspector-session-requests.test.ts b/tests/integration/traffic-inspector-session-requests.test.ts new file mode 100644 index 0000000000..d0b9bcb14e --- /dev/null +++ b/tests/integration/traffic-inspector-session-requests.test.ts @@ -0,0 +1,137 @@ +/** + * Integration tests: POST /api/tools/traffic-inspector/sessions/[id]/requests + * + * Tests snapshot persistence: seq increments, request_count sync, validation, 404. + */ + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-ti-session-requests-")); +process.env.DATA_DIR = TEST_DATA_DIR; + +const { resetDbInstance, getDbInstance } = await import("../../src/lib/db/core.ts"); + +async function resetStorage() { + resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true }); + fs.mkdirSync(TEST_DATA_DIR, { recursive: true }); + getDbInstance(); +} + +const sessionsRoute = await import( + "../../src/app/api/tools/traffic-inspector/sessions/route.ts" +); +const sessionDetailRoute = await import( + "../../src/app/api/tools/traffic-inspector/sessions/[id]/route.ts" +); +const sessionRequestsRoute = await import( + "../../src/app/api/tools/traffic-inspector/sessions/[id]/requests/route.ts" +); + +async function createSession(name?: string): Promise { + const res = await sessionsRoute.POST( + new Request("http://localhost/api/tools/traffic-inspector/sessions", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(name !== undefined ? { name } : {}), + }) + ); + const body = (await res.json()) as { id: string }; + return body.id; +} + +async function postRequest(sessionId: string, payload: string): Promise { + return sessionRequestsRoute.POST( + new Request("http://localhost/", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ payload }), + }), + { params: Promise.resolve({ id: sessionId }) } + ); +} + +test.beforeEach(async () => { + await resetStorage(); +}); + +test.after(() => { + resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true }); +}); + +test("POST /sessions/[id]/requests: seq increments 1, 2, 3", async () => { + const id = await createSession("seq-test"); + + const r1 = await postRequest(id, JSON.stringify({ note: "first" })); + assert.equal(r1.status, 201); + const b1 = (await r1.json()) as { seq: number }; + assert.equal(b1.seq, 1); + + const r2 = await postRequest(id, JSON.stringify({ note: "second" })); + assert.equal(r2.status, 201); + const b2 = (await r2.json()) as { seq: number }; + assert.equal(b2.seq, 2); + + const r3 = await postRequest(id, JSON.stringify({ note: "third" })); + assert.equal(r3.status, 201); + const b3 = (await r3.json()) as { seq: number }; + assert.equal(b3.seq, 3); +}); + +test("POST /sessions/[id]/requests: GET session reflects requestCount === 3", async () => { + const id = await createSession("count-test"); + + await postRequest(id, "payload-1"); + await postRequest(id, "payload-2"); + await postRequest(id, "payload-3"); + + const getRes = await sessionDetailRoute.GET(new Request("http://localhost/"), { + params: Promise.resolve({ id }), + }); + assert.equal(getRes.status, 200); + const body = (await getRes.json()) as { session: { request_count: number } }; + assert.equal(body.session.request_count, 3); +}); + +test("POST /sessions/[id]/requests: invalid body returns 400", async () => { + const id = await createSession("validation-test"); + + // Missing `payload` field + const res = await sessionRequestsRoute.POST( + new Request("http://localhost/", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ not_payload: "oops" }), + }), + { params: Promise.resolve({ id }) } + ); + assert.equal(res.status, 400); +}); + +test("POST /sessions/[id]/requests: payload exceeding 1MB cap returns 400", async () => { + const id = await createSession("size-cap-test"); + + // Exceed 1_048_576 bytes + const oversized = "x".repeat(1_048_577); + const res = await postRequest(id, oversized); + assert.equal(res.status, 400); +}); + +test("POST /sessions/[id]/requests: non-existent session id returns 404", async () => { + const res = await postRequest("00000000-0000-4000-8000-000000000000", "some-payload"); + assert.equal(res.status, 404); +}); + +test("POST /sessions/[id]/requests: error response does not leak stack trace", async () => { + // POST to non-existent session — exercises the 404 path error body + const res = await postRequest("00000000-0000-4000-8000-000000000099", "data"); + assert.equal(res.status, 404); + const body = await res.json() as { error?: { message?: string } }; + const msg = body?.error?.message ?? ""; + assert.ok(!msg.includes("at /"), "should not contain stack trace"); +});