Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Note SPBoucher AI8 * File : tests/http/next-p-offline.test.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/note-spboucher-ai11 * Project Website : https://note.spboucher.ai12 * Created : 2026-11-1913 * Last Modified : 2026-11-1914 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * HTTP-level checks of what the web offline-first layer relies on, against a RUNNING scratch instance (`pnpm test:http`):45 * the integrity route (new in 3.0), and the server guarantees the mutation journal is built on — a create replayed under the same46 * client id answers the stored row, a stale versioned save is refused with the server copy, an upload replayed under the same id is47 * stored once. The session is created directly in the scratch database — no passkey, never against production.48 */49import "../helpers/testdb";50import { test, before, after } from "node:test";51import assert from "node:assert/strict";52import { randomUUID, createHash } from "node:crypto";53import { eq, inArray } from "drizzle-orm";54import { db, schema, sql } from "../../src/db/index";55import { createSession, ownerRow } from "../../src/lib/auth/sessions";56import { stableJson } from "../../src/lib/stable-json";5758const BASE = (process.env.APP_URL ?? "").replace(/\/$/, ""); const PFX = "nx-p-offline ·"; const UA = "note-web-offline-http-test";59let cookie = ""; const pages: string[] = []; const tasks: string[] = []; const atts: string[] = [];60async function api(method: string, path: string, body?: unknown, extra: Record<string, string> = {}, anonymous = false) {61 const headers: Record<string, string> = { "user-agent": UA, ...extra }; if (!anonymous) headers.cookie = cookie; if (method !== "GET") headers.origin = BASE;62 let payload: any; if (body instanceof FormData) payload = body; else if (body !== undefined) { headers["content-type"] = "application/json"; payload = JSON.stringify(body); }63 const r = await fetch(BASE + path, { method, headers, body: payload, redirect: "manual" }); const text = await r.text(); let json: any = null; try { json = JSON.parse(text); } catch { /* not JSON */ }64 return { status: r.status, headers: r.headers, json };65}66const doc = (t: string) => ({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: t }] }] });67before(async () => {68 const host = new URL(BASE).hostname; assert.ok(host === "localhost" || host === "127.0.0.1", "APP_URL must be loopback");69 assert.ok(await fetch(`${BASE}/api/health`).then((r) => r.ok, () => false), `no server on ${BASE}`);70 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" });71 cookie = `__Host-note_session=${s.token}; note_session=${s.token}`;72});73after(async () => {74 if (tasks.length) await db.delete(schema.tasks).where(inArray(schema.tasks.id, tasks)); if (atts.length) await db.delete(schema.attachments).where(inArray(schema.attachments.id, atts));75 if (pages.length) { await db.delete(schema.knowledgeEvents).where(inArray(schema.knowledgeEvents.pageId, pages)); await db.delete(schema.pages).where(inArray(schema.pages.id, pages)); }76 await db.delete(schema.sessions).where(eq(schema.sessions.userAgent, UA)); await sql.end();77});7879test("GET /api/sync/integrity: needs a session; one fingerprint per page, equal to sha256(canonical JSON of the content)", async () => {80 assert.equal((await api("GET", "/api/sync/integrity", undefined, {}, true)).status, 401);81 const start = (await api("GET", "/api/sync?since=0&limit=1&kinds=task")).json.head;82 const id = randomUUID(); pages.push(id); const content = doc("integrity é ✓");83 assert.equal((await api("POST", "/api/pages", { id, title: `${PFX} integrity`, content })).status, 201);84 const stored = (await api("GET", `/api/pages/${id}`)).json;85 const r = await api("GET", "/api/sync/integrity"); assert.equal(r.status, 200); assert.equal(r.json.algorithm, "sha256-stable-json-1"); assert.equal(r.json.count, r.json.pages.length);86 assert.match(r.headers.get("cache-control") ?? "", /no-store/);87 const mine = r.json.pages.find((p: any) => p.id === id); assert.ok(mine); assert.equal(mine.version, stored.version); assert.deepEqual(Object.keys(mine).sort(), ["hash", "id", "version"]);88 assert.equal(mine.hash, createHash("sha256").update(stableJson(stored.content)).digest("hex"));89 // the hash follows the content, and the feed delivers the same content the hash was computed from90 const up = await api("PATCH", `/api/pages/${id}`, { content: doc("changed"), baseVersion: stored.version }); assert.equal(up.status, 200);91 const again = (await api("GET", "/api/sync/integrity")).json.pages.find((p: any) => p.id === id); assert.notEqual(again.hash, mine.hash); assert.equal(again.version, up.json.version);92 const feed = (await api("GET", `/api/sync?since=${start}&limit=500&kinds=task`)).json; const row = feed.pages.find((p: any) => p.id === id);93 assert.ok(row, "the page is in the feed read from the cursor taken before it was created"); assert.equal(createHash("sha256").update(stableJson(row.content)).digest("hex"), again.hash);94});95test("journal guarantees: a replayed create answers the stored row; a stale versioned save is refused with the server copy", async () => {96 const id = randomUUID(); pages.push(id); const key = `k-${id}`;97 const a = await api("POST", "/api/pages", { id, title: `${PFX} created offline`, section: "notes" }, { "idempotency-key": key }); assert.equal(a.status, 201); assert.equal(a.json.id, id);98 const b = await api("POST", "/api/pages", { id, title: `${PFX} created offline`, section: "notes" }, { "idempotency-key": key }); assert.ok([200, 201].includes(b.status)); assert.equal(b.json.id, id); assert.equal(b.json.version, a.json.version);99 const c = await api("POST", "/api/pages", { id, title: `${PFX} other title` }); assert.equal(c.status, 200, "same id, other key: still the stored page"); assert.equal(c.headers.get("x-existing"), "1"); assert.equal(c.json.title, `${PFX} created offline`);100 const rows = await db.select({ id: schema.pages.id }).from(schema.pages).where(eq(schema.pages.id, id)); assert.equal(rows.length, 1);101 const ok = await api("PATCH", `/api/pages/${id}`, { content: doc("first"), baseVersion: a.json.version }); assert.equal(ok.status, 200);102 const stale = await api("PATCH", `/api/pages/${id}`, { content: doc("second, from an old base"), baseVersion: a.json.version }); assert.equal(stale.status, 409); assert.equal(stale.json.code, "conflict");103 assert.equal(stale.json.server.version, ok.json.version); assert.deepEqual(stale.json.server.content.content[0].content[0].text, "first");104 // unversioned metadata (pin / archive / move) does not need a base and does not disturb the text version check105 assert.equal((await api("PATCH", `/api/pages/${id}`, { pinned: true })).status, 200);106 assert.equal((await api("PUT", `/api/pages/${id}/tags`, { tags: ["offline", "journal"] })).status, 200);107 assert.equal((await api("DELETE", `/api/pages/${id}`)).status, 200); assert.equal((await api("POST", `/api/pages/${id}?action=restore`)).status, 200);108});109test("journal guarantees: tasks and uploads replayed under their client id are stored once", async () => {110 const pid = randomUUID(); pages.push(pid); await api("POST", "/api/pages", { id: pid, title: `${PFX} with task` });111 const tid = randomUUID(); tasks.push(tid);112 const t1 = await api("POST", "/api/tasks", { id: tid, title: `${PFX} task`, pageId: pid }); assert.equal(t1.status, 201);113 const t2 = await api("POST", "/api/tasks", { id: tid, title: `${PFX} task`, pageId: pid }); assert.equal(t2.status, 200); assert.equal(t2.headers.get("x-existing"), "1");114 assert.equal((await api("PATCH", `/api/tasks/${tid}`, { status: "done" })).json.status, "done"); assert.equal((await api("PATCH", `/api/tasks/${tid}`, { status: "done" })).status, 200, "completing twice is harmless");115 assert.equal((await db.select().from(schema.tasks).where(eq(schema.tasks.id, tid))).length, 1);116 const aid = randomUUID(); atts.push(aid); const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "base64");117 const form = () => { const f = new FormData(); f.append("id", aid); f.append("file", new File([png], "queued.png", { type: "image/png" })); f.append("pageId", pid); return f; };118 const u1 = await api("POST", "/api/attachments", form()); assert.ok([200, 201].includes(u1.status)); assert.equal(u1.json.id, aid);119 const u2 = await api("POST", "/api/attachments", form()); assert.equal(u2.status, 200); assert.equal(u2.headers.get("x-existing"), "1"); assert.equal(u2.json.id, aid);120 assert.equal((await db.select().from(schema.attachments).where(eq(schema.attachments.id, aid))).length, 1);121 const feed = (await api("GET", "/api/sync?since=0&limit=500&kinds=task")).json; assert.ok(Array.isArray(feed.entities.task)); assert.ok("cursor" in feed && "more" in feed);122});123