Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Note SPBoucher AI8 * File : tests/http/next-contract.test.ts9 * Description : HTTP regression tests of the contract defects found by the10 * native client's live tests during the 3.0 integration11 * (BACKEND-DEFECTS-FROM-CORE): every error carries a stable12 * `code`, DELETE is idempotent, a bare filter rule is13 * honoured, lists are capped by `limit`, no raw PostgreSQL14 * value leaks, a trashed database is trashed in the feed,15 * bare dates are stored at 12:00 UTC, the time machine says16 * "did not exist", a deleted reference is not resurrected,17 * /api/health and /api/meta agree on the version. Against a18 * RUNNING scratch instance (`pnpm test:http`). No model is19 * ever called. Everything created is removed in `after`.20 * Module : tests21 * Repository : https://git.spboucher.ai/note-spboucher-ai22 * Project Website : https://note.spboucher.ai23 * Created : 2026-11-1924 * Last Modified : 2026-11-1925 *26 * Author : Simon-Pierre Boucher27 * Position : Professor of Finance28 * Institution : Université du Québec en Outaouais (UQO)29 * Organization : SP Boucher30 * Website : https://spboucher.ai31 * Git : https://git.spboucher.ai32 *33 * Preferred Contact: contact@spboucher.ai34 * Development : dev@spboucher.ai35 * Support : support@spboucher.ai36 * Security/Admin : admin@spboucher.ai37 *38 * Copyright (c) 202639 * Simon-Pierre Boucher40 * All rights reserved where applicable. This file is governed by the41 * applicable project license, copyright notices and relevant law.42 * Existing third-party rights and notices remain unaffected.43 *44 * License : None specified (no license file in this repository)45 *46 * Do not embed credentials, private keys, access tokens,47 * certificates or confidential personal information.48 *49 * =============================================================================50 * END OF SP BOUCHER SOURCE HEADER51 * =============================================================================52 */5354import "../helpers/testdb";55import { test, before, after } from "node:test";56import assert from "node:assert/strict";57import { randomUUID } from "node:crypto";58import fs from "node:fs";59import http from "node:http";60import { and, eq, inArray, like } from "drizzle-orm";61import { db, schema, sql } from "../../src/db/index";62import { createSession, ownerRow } from "../../src/lib/auth/sessions";6364const BASE = (process.env.APP_URL ?? "").replace(/\/$/, ""); const PFX = "nx-contract ·"; const UA = "SPNotes/3.0.0 (Macintosh; Mac OS X 27.0) nx-contract-tests";65const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;66let cookie = ""; let ws = ""; const pages: string[] = []; const tasks: string[] = []; const refs: string[] = []; const concepts: string[] = []; const insights: string[] = [];67type Res = { status: number; headers: Headers; json: any; text: string };68async function api(method: string, path: string, body?: unknown): Promise<Res> {69 const headers: Record<string, string> = { "user-agent": UA, cookie }; if (method !== "GET") headers.origin = BASE; if (body !== undefined) headers["content-type"] = "application/json";70 const r = await fetch(BASE + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "manual" }); const text = await r.text();71 let json: any = null; try { json = JSON.parse(text); } catch { /* not JSON */ }72 return { status: r.status, headers: r.headers, json, text };73}74const page = async (title: string, extra: Record<string, unknown> = {}) => { const r = await api("POST", "/api/pages", { title: `${PFX} ${title}`, ...extra }); assert.equal(r.status, 201, r.text); pages.push(r.json.id); return r.json; };75/** A database with a number property and three rows (1, 2, 3). */76async function database() {77 const host = await page("db", { type: "database", section: "databases" }); const d = await api("GET", `/api/databases/${host.id}`); assert.equal(d.status, 200, d.text);78 const prop = await api("POST", `/api/databases/${host.id}/properties`, { name: "Score", type: "number" }); assert.equal(prop.status, 201, prop.text);79 for (const n of [1, 2, 3]) { const r = await api("POST", `/api/databases/${host.id}/rows`, { title: `${PFX} row ${n}`, values: { [prop.json.id]: n } }); assert.ok(r.status < 300, r.text); }80 return { host, id: d.json.id as string, prop: prop.json.id as string };81}8283before(async () => {84 const host = new URL(BASE).hostname; assert.ok(host === "localhost" || host === "127.0.0.1", "APP_URL must be loopback");85 assert.ok(await fetch(`${BASE}/api/health`).then((r) => r.ok, () => false), `no server on ${BASE}`);86 const u = await ownerRow(); assert.ok(u, "owner missing: pnpm run bootstrap"); const s = await createSession({ userId: u!.id, credentialId: null, userAgent: UA, ip: "127.0.0.1" });87 cookie = `__Host-note_session=${s.token}; note_session=${s.token}`; const [w] = await db.select().from(schema.workspaces).limit(1); ws = w.id;88});89after(async () => {90 const mine = await db.select({ id: schema.pages.id }).from(schema.pages).where(and(eq(schema.pages.workspaceId, ws), like(schema.pages.title, `${PFX}%`))); const ids = [...new Set([...pages, ...mine.map((m) => m.id)])];91 if (tasks.length) await db.delete(schema.tasks).where(inArray(schema.tasks.id, tasks));92 if (refs.length) await db.delete(schema.researchReferences).where(inArray(schema.researchReferences.id, refs));93 if (concepts.length) await db.delete(schema.concepts).where(inArray(schema.concepts.id, concepts));94 if (insights.length) await db.delete(schema.knowledgeInsights).where(inArray(schema.knowledgeInsights.id, insights));95 if (ids.length) {96 await db.delete(schema.tasks).where(inArray(schema.tasks.pageId, ids)); await db.delete(schema.knowledgeEdges).where(inArray(schema.knowledgeEdges.fromId, ids));97 const dbs = await db.select({ id: schema.databases.id }).from(schema.databases).where(inArray(schema.databases.pageId, ids));98 if (dbs.length) await db.delete(schema.pages).where(inArray(schema.pages.databaseId, dbs.map((d) => d.id)));99 await db.delete(schema.pages).where(inArray(schema.pages.id, ids)); await db.delete(schema.knowledgeEvents).where(inArray(schema.knowledgeEvents.pageId, ids));100 }101 await db.delete(schema.pages).where(and(eq(schema.pages.workspaceId, ws), like(schema.pages.title, `${PFX}%`)));102 await db.delete(schema.sessions).where(eq(schema.sessions.userAgent, UA)); await sql.end();103});104105test("every error answer carries a stable `code` (defect 7)", async () => {106 const R = randomUUID(); const p = await page("codes");107 const cases: [string, string, unknown, number, string][] = [108 ["GET", `/api/events?projectId=${R}`, undefined, 404, "not_found"], ["GET", `/api/pages/${R}/zoom`, undefined, 404, "not_found"], ["GET", `/api/pages/${R}`, undefined, 404, "not_found"],109 ["POST", "/api/query", { source: "database", databaseId: R }, 404, "not_found"], ["GET", `/api/databases/${R}`, undefined, 404, "not_found"], ["POST", `/api/databases/${R}/query`, {}, 404, "not_found"],110 ["PATCH", `/api/databases/${R}`, { name: "x" }, 404, "not_found"], ["DELETE", `/api/databases/${R}/views?id=${R}`, undefined, 404, "not_found"], ["DELETE", `/api/databases/${R}/rows?id=${R}`, undefined, 404, "not_found"],111 ["PATCH", `/api/pages/${p.id}`, { parentId: p.id }, 400, "bad_request"], ["POST", "/api/pages", { title: 5 }, 400, "bad_request"], ["GET", "/api/research/tasks", undefined, 400, "bad_request"],112 ["GET", `/api/research/references/${R}`, undefined, 404, "not_found"], ["GET", `/api/tasks/${R}`, undefined, 404, "not_found"], ["GET", `/api/canvases/${R}`, undefined, 404, "not_found"],113 ];114 for (const [m, path, body, status, code] of cases) { const r = await api(m, path, body); assert.deepEqual([r.status, r.json?.code], [status, code], `${m} ${path} → ${r.text.slice(0, 160)}`); assert.equal(typeof r.json.error, "string"); }115 // invalid JSON body, and without a session116 const bad = await fetch(`${BASE}/api/pages`, { method: "POST", headers: { cookie, origin: BASE, "content-type": "application/json", "user-agent": UA }, body: "{nope" }); assert.equal(bad.status, 400); assert.equal((await bad.json()).code, "bad_request");117 const anon = await fetch(`${BASE}/api/brief`); assert.equal(anon.status, 401); assert.equal((await anon.json()).code, "unauthenticated");118 // extras the documentation promises119 const same = await api("POST", "/api/graph/relations", { fromId: p.id, toId: p.id, relType: "supports" }); assert.deepEqual([same.status, same.json.code, same.json.field], [400, "bad_node", "toId"]);120 const unknownNode = await api("POST", "/api/graph/relations", { fromId: p.id, toId: R, relType: "supports" }); assert.deepEqual([unknownNode.json.code, unknownNode.json.field], ["bad_node", "toId"]);121 const c1 = await api("POST", "/api/concepts", { name: `${PFX} one ${R.slice(0, 6)}` }); const c2 = await api("POST", "/api/concepts", { name: `${PFX} two ${R.slice(0, 6)}` }); concepts.push(c1.json.id, c2.json.id);122 const clash = await api("PATCH", "/api/concepts", { id: c2.json.id, name: c1.json.name }); assert.deepEqual([clash.status, clash.json.code, clash.json.id, clash.json.status], [409, "concept_exists", c1.json.id, c1.json.status]);123 const clash2 = await api("PATCH", `/api/concepts/${c2.json.id}`, { name: c1.json.name.toUpperCase() }); assert.deepEqual([clash2.status, clash2.json.code, clash2.json.status], [409, "concept_exists", c1.json.status]);124});125126test("DELETE is idempotent: the second call and an unknown id answer the same 200 (defect 8)", async () => {127 const R = randomUUID(); const a = await page("del a"); const b = await page("del b");128 const rel = await api("POST", "/api/graph/relations", { fromId: a.id, toId: b.id, relType: "supports" }); assert.equal(rel.status, 201, rel.text);129 for (let i = 0; i < 2; i++) { const d = await api("DELETE", `/api/graph/relations/${rel.json.id}`); assert.deepEqual([d.status, d.json], [200, { ok: true }], `relation, call ${i + 1}`); }130 assert.deepEqual((await api("DELETE", `/api/graph/relations/${R}`)).json, { ok: true });131 assert.equal((await api("GET", `/api/events?pageId=${a.id}&kinds=relation.removed`)).json.events.length, 1, "one event: the second DELETE wrote nothing");132 const con = await api("POST", "/api/concepts", { name: `${PFX} del ${R.slice(0, 6)}` }); concepts.push(con.json.id);133 for (let i = 0; i < 2; i++) { const d = await api("DELETE", `/api/concepts/${con.json.id}`); assert.deepEqual([d.status, d.json], [200, { ok: true }], `concept, call ${i + 1}`); }134 assert.equal((await api("DELETE", `/api/concepts/${R}`)).status, 200);135 const t = await api("POST", "/api/tasks", { title: `${PFX} del` }); tasks.push(t.json.id);136 assert.deepEqual((await api("DELETE", `/api/tasks/${t.json.id}`)).json, { ok: true, deleted: true }); assert.deepEqual((await api("DELETE", `/api/tasks/${t.json.id}`)).json, { ok: true, deleted: false });137 assert.deepEqual([(await api("DELETE", `/api/tasks/${R}`)).status, (await api("DELETE", `/api/research/tasks/${R}`)).status, (await api("DELETE", `/api/research/references/${R}`)).status, (await api("DELETE", `/api/research/experiments/${R}`)).status, (await api("DELETE", `/api/attachments?id=${R}`)).status], [200, 200, 200, 200, 200]);138 // inside an existing database: unknown view / property / row / row template → 200; the database itself unknown → 404 (the container is missing)139 const d = await database();140 for (const sub of ["views", "properties", "rows", "row-templates"]) { const r = await api("DELETE", `/api/databases/${d.id}/${sub}?id=${R}`); assert.equal(r.status, 200, `${sub}: ${r.text}`); assert.equal(r.json.ok, true); }141 assert.equal((await api("DELETE", `/api/databases/${R}/properties?id=${R}`)).status, 404);142 // a derived edge is still refused (it exists and cannot be deleted this way) — covered by the unit suite; a malformed id is still 400143 assert.equal((await api("DELETE", "/api/concepts/not-a-uuid")).status, 400);144});145146test("database query: a bare rule as `filter` is honoured, nonsense is refused, never ignored (defect 3)", async () => {147 const d = await database(); const rule = { property: d.prop, op: "gt", value: 1 };148 const all = await api("POST", `/api/databases/${d.id}/query`, {}); assert.equal(all.json.total, 3);149 const bare = await api("POST", `/api/databases/${d.id}/query`, { filter: rule }); assert.equal(bare.status, 200, bare.text); assert.equal(bare.json.total, 2, "the bare rule filters");150 const grouped = await api("POST", `/api/databases/${d.id}/query`, { filter: { and: [rule] } }); assert.equal(grouped.json.total, 2);151 assert.equal((await api("POST", `/api/databases/${d.id}/query`, { extraFilter: rule })).json.total, 2);152 assert.equal((await api("POST", `/api/databases/${d.id}/query`, { filter: {} })).json.total, 3); assert.equal((await api("POST", `/api/databases/${d.id}/query`, { filter: null })).json.total, 3);153 for (const f of [{ foo: 1 }, "x", [rule], { and: [rule], property: d.prop }, { property: d.prop }, { property: "nope", op: "gt", value: 1 }, { property: d.prop, op: "nope" }]) {154 const r = await api("POST", `/api/databases/${d.id}/query`, { filter: f }); assert.deepEqual([r.status, r.json.code], [400, "bad_filter"], JSON.stringify(f));155 }156 // the same rule for a bulk selection: a bare rule must not turn "the matching rows" into "every row"157 const bulk = await api("POST", `/api/databases/${d.id}/rows/bulk`, { action: "delete", all: { filter: { property: d.prop, op: "gt", value: 2 } } }); assert.equal(bulk.status, 200, bulk.text);158 assert.equal((await api("POST", `/api/databases/${d.id}/query`, {})).json.total, 2, "one row deleted, not three");159 assert.equal((await api("POST", `/api/databases/${d.id}/rows/bulk`, { action: "delete", all: { filter: { foo: 1 } } })).json.code, "bad_filter");160});161162test("change feed: reset answer has one empty list per kind; a trashed database is trashed in the feed and comes back on restore (defects 4, 11)", async () => {163 const head = (await api("GET", "/api/sync?kinds=all&since=0&limit=1")).json.head as number;164 const reset = await api("GET", `/api/sync?kinds=all&since=${head + 10_000_000}`); assert.equal(reset.json.reset, true);165 assert.deepEqual(reset.json.entities, { task: [], database: [], database_property: [], database_view: [], database_row: [], edge: [], reference: [], canvas: [], concept: [] });166 assert.equal("entities" in (await api("GET", `/api/sync?since=${head + 10_000_000}`)).json, false, "2.x reset answer unchanged");167 const d = await database(); const start = (await api("GET", "/api/sync?kinds=database&since=0&limit=1")).json.head as number;168 assert.equal((await api("DELETE", `/api/pages/${d.host.id}`)).status, 200);169 const trashed = (await api("GET", `/api/sync?kinds=database&since=${start}&limit=500`)).json; const row = trashed.entities.database.find((x: any) => x.id === d.id);170 assert.ok(row, "the database row is in the feed after its host page was trashed"); assert.match(row.deletedAt, ISO); assert.ok(row.rev > start);171 assert.equal(trashed.pages.find((x: any) => x.id === d.host.id).deletedAt, row.deletedAt, "same instant as its host page");172 assert.equal((await api("POST", `/api/pages/${d.host.id}?action=restore`)).status, 200);173 const back = (await api("GET", `/api/sync?kinds=database&since=${row.rev}&limit=500`)).json.entities.database.find((x: any) => x.id === d.id); assert.ok(back); assert.equal(back.deletedAt, null); assert.ok(back.rev > row.rev);174});175176test("lists are capped by `limit`; out-of-range values are clamped and the applied value is visible (defect 9)", async () => {177 for (let i = 0; i < 3; i++) { const [r] = await db.insert(schema.knowledgeInsights).values({ workspaceId: ws, kind: "open_question", status: "suggested", title: `${PFX} insight ${i}`, detail: "", data: {}, origin: "system", fingerprint: `nx-contract-${randomUUID()}` }).returning({ id: schema.knowledgeInsights.id }); insights.push(r.id); }178 const two = await api("GET", "/api/graph/insights?limit=2&intelligence=0"); assert.equal(two.status, 200); assert.equal(two.json.insights.length, 2, "limit caps `insights`"); assert.ok(two.json.counts.suggested >= 3, "counts are not capped");179 const zero = await api("GET", "/api/graph/insights?limit=0&intelligence=0"); assert.equal(zero.status, 200); assert.equal(zero.json.insights.length, 1, "limit=0 is clamped to 1");180 assert.ok((await api("GET", "/api/graph/insights?intelligence=0")).json.insights.length >= 3);181 const intel = await api("GET", "/api/graph/insights?limit=1"); for (const k of ["centralPages", "centralConcepts", "clusters", "recurringTopics"]) assert.ok(intel.json.intelligence[k].length <= 1, k);182 assert.equal((await api("GET", "/api/graph/insights?limit=abc")).json.code, "bad_request");183 assert.equal((await api("GET", "/api/health/knowledge?inactiveDays=0")).json.inactiveDays, 1, "clamped to the minimum, and echoed"); assert.equal((await api("GET", "/api/health/knowledge?inactiveDays=9999")).json.inactiveDays, 3650);184});185186test("no raw PostgreSQL value: dates are ISO-8601 UTC, counts are JSON numbers (defect 10); search default mode is the 2.x quick search", async () => {187 await page("values needle");188 for (const path of ["/api/search?q=nx-contract&mode=quick", "/api/search?q=nx-contract", "/api/search?mode=quick&q="]) {189 const r = await api("GET", path); assert.equal(r.status, 200); assert.ok(Array.isArray(r.json) && r.json.length >= 1, path);190 assert.deepEqual(Object.keys(r.json[0]), ["id", "title", "icon", "type", "section", "updatedAt"], "quick-search row (also the answer when `mode` is absent, as in 2.x)"); for (const row of r.json) assert.match(row.updatedAt, ISO, path);191 }192 const usage = (await api("GET", "/api/ai/usage?days=90")).json;193 for (const m of usage.byModel) for (const k of ["calls", "errors", "inputTokens", "outputTokens", "costUsd"]) assert.equal(typeof m[k], "number", `byModel.${k}`);194 for (const d of usage.byDay) { assert.equal(typeof d.calls, "number"); assert.equal(typeof d.costUsd, "number"); } for (const t of usage.byTask) { assert.equal(typeof t.calls, "number"); assert.equal(typeof t.costUsd, "number"); }195 const idx = (await api("GET", "/api/search/index-state")).json;196 for (const k of ["pages", "attachments", "chunks", "embedded", "indexed_sources", "stale"]) assert.equal(typeof idx[k], "number", k); assert.ok(idx.last_indexed === null || ISO.test(idx.last_indexed));197 for (const p of idx.health.pending) assert.match(p.updatedAt, ISO); for (const f of idx.health.failed) assert.match(f.at, ISO);198 const health = await fetch(`${BASE}/api/health`).then((r) => r.json()); assert.match(health.time, ISO);199 const meta = (await api("GET", "/api/meta")).json; assert.equal(health.version, meta.version, "/api/health and /api/meta report the same version"); assert.match(health.version, /^3\./);200});201202test("bare dates are stored at 12:00 UTC by both task routes (defect 12); the time machine says a page did not exist yet (defect 13)", async () => {203 const p = await page("dates");204 const rt = await api("POST", "/api/research/tasks", { pageId: p.id, title: `${PFX} research due`, dueAt: "2026-12-05" }); assert.equal(rt.status, 201, rt.text); tasks.push(rt.json.id);205 const t = await api("POST", "/api/tasks", { title: `${PFX} due`, due: "2026-12-05" }); tasks.push(t.json.id);206 assert.equal(rt.json.dueAt, "2026-12-05T12:00:00.000Z"); assert.equal(t.json.dueAt, rt.json.dueAt, "one rule for a bare date");207 assert.equal((await api("PATCH", `/api/research/tasks/${rt.json.id}`, { dueAt: "2026-12-06" })).json.dueAt, "2026-12-06T12:00:00.000Z");208 assert.equal((await api("PATCH", `/api/research/tasks/${rt.json.id}`, { dueAt: "2026-12-06T08:30:00-05:00" })).json.dueAt, "2026-12-06T13:30:00.000Z", "a datetime with offset is kept");209 const bad = await api("POST", "/api/research/tasks", { pageId: p.id, title: `${PFX} bad`, dueAt: "tomorrow" }); assert.deepEqual([bad.status, bad.json.code], [400, "bad_request"]);210 const tm = await api("GET", `/api/timemachine?at=2020-01-01T00:00:00Z&pageId=${p.id}`); assert.equal(tm.status, 200); const s = tm.json.pages[0];211 assert.deepEqual([s.existed, s.source, s.exact, s.version, s.versionId], [false, "none", false, null, null]); assert.equal("content" in s, false);212 const now = (await api("GET", `/api/timemachine?at=${encodeURIComponent(new Date().toISOString())}&pageId=${p.id}`)).json.pages[0]; assert.deepEqual([now.existed, now.source, now.exact], [true, "current", true]);213});214215test("references: client id replay answers the stored row (200 + x-existing), a deleted one is not resurrected (409), ids= / projectId= (defects 6, 14)", async () => {216 const id = randomUUID(); refs.push(id); const project = await page("refs project", { section: "projects" });217 const first = await api("POST", "/api/research/references", { id, title: `${PFX} ref`, authors: ["Boucher, S.-P."], year: 2026, pageId: project.id }); assert.equal(first.status, 201, first.text); assert.equal(first.headers.get("x-existing"), null);218 const again = await api("POST", "/api/research/references", { id, title: `${PFX} another title` }); assert.equal(again.status, 200); assert.equal(again.headers.get("x-existing"), "1"); assert.equal(again.json.title, `${PFX} ref`, "the stored row, untouched");219 const R = randomUUID(); const list = await api("GET", `/api/research/references?ids=${id},${R}`); assert.equal(list.status, 200); assert.deepEqual(list.json.map((r: any) => r.id), [id]); assert.equal(list.headers.get("x-missing-ids"), R);220 assert.equal(typeof list.json[0].label, "string"); assert.equal(typeof list.json[0].citation, "string");221 assert.ok((await api("GET", `/api/research/references?projectId=${project.id}`)).json.some((r: any) => r.id === id));222 assert.equal((await api("GET", "/api/research/references?ids=abc")).status, 400);223 assert.equal((await api("DELETE", `/api/research/references/${id}`)).status, 200);224 const dead = await api("POST", "/api/research/references", { id, title: `${PFX} ref` }); assert.deepEqual([dead.status, dead.json.code, dead.json.id], [409, "reference_deleted", id]); assert.match(dead.json.deletedAt, ISO);225 assert.equal((await api("GET", `/api/research/references?ids=${id}`)).headers.get("x-missing-ids"), id, "a deleted reference is missing");226 assert.equal((await api("POST", `/api/research/references/${id}?action=restore`)).status, 200); assert.equal((await api("POST", "/api/research/references", { id, title: "x" })).status, 200);227});228229test("capture kinds screenshot / selection / document are accepted (defect 5); the brief never serves a summary nobody asked for", async () => {230 for (const kind of ["screenshot", "selection", "document"]) {231 const r = await api("POST", "/api/capture", { kind, text: `${PFX} captured ${kind}` }); assert.equal(r.status, 201, `${kind}: ${r.text}`); pages.push(r.json.id); assert.equal(r.json.kind, kind); assert.match(r.json.inboxAt, ISO);232 assert.equal((await api("GET", `/api/pages/${r.json.id}`)).json.captureKind, kind);233 }234 assert.equal((await api("POST", "/api/capture", { kind: "hologram", text: "x" })).status, 400);235 const before = await db.select().from(schema.settings).where(eq(schema.settings.key, `brief.summary:${ws}`));236 const brief = (await api("GET", "/api/brief")).json; const s = brief.aiSummary;237 if (!before.length) assert.equal(s, null, "no stored summary → aiSummary is null: GET /api/brief never calls a model");238 else { assert.equal(s.ai, true); assert.equal(typeof s.model, "string"); assert.match(s.at, ISO); assert.doesNotMatch(s.model, /^fake/, "a test fixture must not be left in the scratch workspace"); }239 assert.deepEqual((await db.select().from(schema.settings).where(eq(schema.settings.key, `brief.summary:${ws}`))).length, before.length, "reading the brief stores nothing");240});241242test("every mutating method of every route.ts refuses a signed-in request without (or with a foreign) Origin: 403 csrf", async () => {243 const PUBLIC = new Set(["/api/health", "/api/auth/login/options", "/api/auth/login/verify", "/api/auth/enroll/options", "/api/auth/enroll/verify", "/api/auth/logout"]);244 const found: [string, string][] = []; const unwrapped: string[] = [];245 const walk = (d: string) => { for (const e of fs.readdirSync(d, { withFileTypes: true })) { if (e.isDirectory()) walk(`${d}/${e.name}`); else if (e.name === "route.ts") {246 const route = d.replace("src/app", "").replace(/\[[^\]]+\]/g, "00000000-0000-4000-8000-000000000000"); const src = fs.readFileSync(`${d}/route.ts`, "utf8");247 for (const m of src.matchAll(/^export (?:const|async function) (GET|POST|PUT|PATCH|DELETE)\b(.*)$/gm)) { if (PUBLIC.has(route)) continue; if (!/=\s*handler\(/.test(m[2])) unwrapped.push(`${m[1]} ${route}`); if (m[1] !== "GET") found.push([m[1], route]); }248 } } };249 walk("src/app/api");250 assert.deepEqual(unwrapped, [], "every non-public route method goes through the authenticated `handler` wrapper"); assert.ok(found.length > 100, `walked ${found.length} mutating methods`);251 const raw = (method: string, path: string, headers: Record<string, string>) => new Promise<{ status: number; json: any }>((resolve, reject) => {252 const u = new URL(BASE + path); const data = "{}"; const req = http.request({ host: u.hostname, port: u.port, path: u.pathname, method, headers: { "content-type": "application/json", "content-length": Buffer.byteLength(data), "user-agent": UA, cookie, ...headers } }, (res) => { let t = ""; res.on("data", (c) => (t += c)); res.on("end", () => { let json: any = null; try { json = JSON.parse(t); } catch { /* */ } resolve({ status: res.statusCode ?? 0, json }); }); });253 req.on("error", reject); req.end(data);254 });255 for (const [method, route] of found) {256 const none = await raw(method, route, {}); assert.deepEqual([none.status, none.json?.code], [403, "csrf"], `${method} ${route} without Origin`);257 const foreign = await raw(method, route, { origin: "https://evil.example" }); assert.deepEqual([foreign.status, foreign.json?.code], [403, "csrf"], `${method} ${route} with a foreign Origin`);258 }259});260261test("offline-first capture through POST /api/pages: inboxAt | inbox + captureKind land in the server inbox, idempotent on id, in the feed, journaled", async () => {262 const start = (await api("GET", "/api/sync?since=0&limit=1")).json.head as number; const id = randomUUID(); pages.push(id); const at = "2026-11-19T14:05:06.000Z";263 const first = await api("POST", "/api/pages", { id, title: `${PFX} captured offline`, inboxAt: at, captureKind: "selection", content: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "typed in the tunnel" }] }] } });264 assert.equal(first.status, 201, first.text); assert.deepEqual([first.json.inboxAt, first.json.captureKind], [at, "selection"]);265 const again = await api("POST", "/api/pages", { id, title: "other", inbox: true, captureKind: "link" }); assert.equal(again.status, 200); assert.equal(again.headers.get("x-existing"), "1"); assert.deepEqual([again.json.inboxAt, again.json.captureKind, again.json.title], [at, "selection", `${PFX} captured offline`]);266 assert.ok((await api("GET", "/api/inbox")).text.includes(id), "listed by the inbox");267 const row = (await api("GET", `/api/sync?since=${start}&limit=500`)).json.pages.find((p: any) => p.id === id); assert.deepEqual([row.inboxAt, row.captureKind], [at, "selection"]);268 assert.deepEqual((await api("GET", `/api/events?pageId=${id}`)).json.events.map((e: any) => e.kind).sort(), ["capture.created", "page.created"]);269 const now = await api("POST", "/api/pages", { title: `${PFX} inbox true`, inbox: true }); pages.push(now.json.id); assert.match(now.json.inboxAt, ISO); assert.equal(now.json.captureKind, "note");270 const kindOnly = await api("POST", "/api/pages", { title: `${PFX} kind only`, captureKind: "voice-memo" }); pages.push(kindOnly.json.id); assert.match(kindOnly.json.inboxAt, ISO); assert.equal(kindOnly.json.captureKind, "voice-memo", "open string");271 const plain = await api("POST", "/api/pages", { title: `${PFX} plain` }); pages.push(plain.json.id); assert.deepEqual([plain.json.inboxAt, plain.json.captureKind], [null, null]); assert.deepEqual((await api("GET", `/api/events?pageId=${plain.json.id}`)).json.events.map((e: any) => e.kind), ["page.created"]);272 assert.deepEqual([(await api("POST", "/api/pages", { title: "x", inboxAt: "yesterday" })).json.code, (await api("POST", "/api/pages", { title: "x", captureKind: "k".repeat(33) })).status], ["bad_request", 400]);273});274275test("universal links: the app-site association keeps webcredentials and hands /p/* to the iOS app", async () => {276 const r = await fetch(`${BASE}/.well-known/apple-app-site-association`); assert.equal(r.status, 200); assert.match(r.headers.get("content-type") ?? "", /json/); const j = await r.json();277 assert.deepEqual(j.webcredentials, { apps: ["3YM54G49SN.ai.spboucher.spnotes", "3YM54G49SN.ai.spboucher.spnotes.ios"] });278 assert.deepEqual(j.applinks, { details: [{ appIDs: ["3YM54G49SN.ai.spboucher.spnotes.ios"], components: [{ "/": "/p/*", comment: "a page, optional #blockId" }] }] });279});280