feat(workspace): integrate persisted canvas, element editing and session renewal

This commit is contained in:
2026-11-06 12:50:43 +08:00
parent 45e78f2e43
commit 373582906d
36 changed files with 1028 additions and 193 deletions
+84 -5
View File
@@ -6,12 +6,26 @@ import { fileURLToPath } from "node:url";
import { readdir, readFile } from "node:fs/promises";
const host = "http://127.0.0.1:3005";
const graphs = new Map();
let canvasSnapshot = { version: 1, document: { schema_version: 1, nodes: [], edges: [], viewport: { x: 0, y: 0, zoom: 1 } } };
let mockSessionSeconds = "2592000";
let mockProfile = {
id: "user", username: "test", display_name: "Test User", email: "test@example.com",
avatar_url: "https://lh3.googleusercontent.com/test-avatar=s96-c",
};
const upstream = createServer(async (req, res) => {
res.setHeader("Content-Type", "application/json");
if (req.headers.authorization === "Bearer test-only-session" && !req.url.endsWith("/auth/logout")) res.setHeader("X-Foundry-Session-Expires-In", mockSessionSeconds);
const canonical = req.url.replace("/workspaces/creative-space/", "/workspaces/space/").replace("/materials/my-board", "/materials/foundry-generated-id");
if (canonical === "/projects/endoleap/workspaces/space/materials/foundry-generated-id/canvas") {
if (req.headers.authorization !== "Bearer test-only-session") { res.statusCode = 401; res.end(JSON.stringify({ error: "invalid_session" })); return; }
if (req.method === "GET") { res.setHeader("ETag", '"' + canvasSnapshot.version + '"'); res.end(JSON.stringify(canvasSnapshot)); return; }
let raw = ""; for await (const chunk of req) raw += chunk;
if (req.headers["if-match"] !== '"' + canvasSnapshot.version + '"') { res.statusCode = 412; res.end(JSON.stringify({ error: "version_conflict" })); return; }
const { document } = JSON.parse(raw);
assert.equal(document.schema_version, 1); assert(Array.isArray(document.nodes));
canvasSnapshot = { version: canvasSnapshot.version + 1, document };
res.setHeader("ETag", '"' + canvasSnapshot.version + '"'); res.end(JSON.stringify({ version: canvasSnapshot.version })); return;
}
if (req.url.endsWith("/auth/logout")) {
res.statusCode = 204;
res.end();
@@ -21,11 +35,11 @@ const upstream = createServer(async (req, res) => {
for await (const chunk of req) raw += chunk;
const input = JSON.parse(raw);
assert.deepEqual(input, { kind: "board", title: "未命名图谱", content: { schema_version: 1 } });
const graph = { ...input, id: "foundry-generated-id", workspace_id: "space", version: 1 };
const graph = { ...input, slug: "my-board", id: "foundry-generated-id", workspace_id: "space", version: 1 };
graphs.set(graph.id, graph);
res.statusCode = 201;
res.end(JSON.stringify({ id: graph.id, workspace_id: graph.workspace_id, kind: graph.kind, version: graph.version }));
} else if (req.url === "/projects/endoleap/workspaces/space/materials/foundry-generated-id") {
} else if (canonical === "/projects/endoleap/workspaces/space/materials/foundry-generated-id") {
assert.equal(req.headers.authorization, "Bearer test-only-session");
if (req.method === "PATCH") {
assert.equal(req.headers["if-match"], '"1"');
@@ -43,7 +57,7 @@ const upstream = createServer(async (req, res) => {
res.end(
JSON.stringify({
access_token: "test-only-session",
expires_in: 28800,
expires_in: 2592000,
token_type: "Bearer",
}),
);
@@ -129,8 +143,28 @@ try {
const cookie = res.headers.get("set-cookie");
assert(cookie?.includes("HttpOnly"));
assert(cookie.includes("SameSite=Lax"));
assert(cookie.includes("Max-Age=28800"));
assert(cookie.includes("Max-Age=2592000"));
const session = cookie.split(";")[0];
const signedInHome = await fetch(host + "/", { headers: { Cookie: session }, redirect: "manual" });
assert.equal(signedInHome.status, 307);
assert.equal(signedInHome.headers.get("location"), "/dashboard");
assert.match(signedInHome.headers.get("cache-control") || "", /private|no-store/);
assert(!(await signedInHome.text()).includes("test-only-session"));
const dashboardHome = await fetch(host + "/dashboard", { headers: { Cookie: session } });
assert.equal(dashboardHome.status, 200);
const dashboardHtml = await dashboardHome.text();
assert.match(dashboardHtml, /aria-label="(?:工作空间侧边栏|正在加载侧边栏)"/);
assert(!dashboardHtml.includes('data-testid="rf__wrapper"'));
assert(!dashboardHtml.includes('class="landing"'));
for (const guestHeaders of [{}, { Cookie: "foundry_session=expired-session" }]) {
const guestHome = await fetch(host + "/", { headers: guestHeaders, redirect: "manual" });
assert.equal(guestHome.status, 200);
assert.equal(guestHome.headers.get("location"), null);
const html = await guestHome.text();
assert(html.includes('class="landing"'));
assert(!html.includes('aria-label="工作空间侧边栏"'));
}
assert.equal(
(
await fetch(host + "/api/foundry/profile", {
@@ -140,6 +174,17 @@ try {
200,
);
assert.equal((await fetch(host + "/api/foundry/profile")).status, 401);
mockSessionSeconds = "3600";
const renewed = await fetch(host + "/api/foundry/profile", { headers: { Cookie: session } });
assert.equal(renewed.status, 200); assert.match(renewed.headers.get("set-cookie") || "", /Max-Age=3600/);
assert.match(renewed.headers.get("set-cookie") || "", /HttpOnly/);
mockSessionSeconds = "garbage";
const malformedRenewal = await fetch(host + "/api/foundry/profile", { headers: { Cookie: session } });
assert.equal(malformedRenewal.headers.get("set-cookie"), null);
mockSessionSeconds = "2592000";
const expiredSession = await fetch(host + "/api/foundry/profile", { headers: { Cookie: "foundry_session=expired" } });
assert.equal(expiredSession.status, 401); assert.equal(expiredSession.headers.get("set-cookie"), null);
const profile = await (await fetch(host + "/api/foundry/profile", { headers: { Cookie: session } })).json();
assert.equal(profile.avatar_url, "https://lh3.googleusercontent.com/test-avatar=s96-c");
const updated = await fetch(host + "/api/foundry/profile", {
@@ -176,6 +221,40 @@ try {
assert.equal(renamed.version, 2);
assert.deepEqual(renamed.content, stored.content);
for (const workspace of ["space", "creative-space"]) for (const board of ["foundry-generated-id", "my-board"]) {
const path = `/api/foundry/workspaces/${workspace}/materials/${board}`;
const material = await (await fetch(host + path, { headers: { Cookie: session } })).json();
assert.equal(material.id, "foundry-generated-id"); assert.equal(material.slug, "my-board");
const snapshot = await fetch(host + path + "/canvas", { headers: { Cookie: session } });
assert.equal(snapshot.status, 200); assert.equal(snapshot.headers.get("etag"), '"1"');
assert.equal((await snapshot.json()).version, 1);
}
const canvasPath = "/api/foundry/workspaces/creative-space/materials/my-board/canvas";
const largeDocument = { schema_version: 1, nodes: Array.from({ length: 15 }, (_, index) => ({ id: "text-" + index, type: "material", position: { x: index * 300, y: 100 }, width: 260, height: 200, data: { kind: "text", title: "保存测试", text: "x".repeat(90000), fontSize: 24, rotation: 30, textStyle: { bold: true, color: "#123456" } } })), edges: [], viewport: { x: 20, y: 40, zoom: 0.75 } };
const savedCanvas = await fetch(host + canvasPath, { method: "PATCH", headers: { Cookie: session, Origin: host, "Content-Type": "application/json", "If-Match": '"1"' }, body: JSON.stringify({ document: largeDocument }) });
assert.equal(savedCanvas.status, 200); assert.equal(savedCanvas.headers.get("etag"), '"2"');
assert.equal((await savedCanvas.json()).version, 2);
const restoredCanvas = await (await fetch(host + canvasPath, { headers: { Cookie: session } })).json();
assert.deepEqual(restoredCanvas.document, largeDocument);
const conflict = await fetch(host + canvasPath, { method: "PATCH", headers: { Cookie: session, Origin: host, "Content-Type": "application/json", "If-Match": '"1"' }, body: JSON.stringify({ document: largeDocument }) });
assert.equal(conflict.status, 412); assert.equal((await conflict.json()).error, "version_conflict");
const frameDocument = structuredClone(largeDocument);
frameDocument.nodes.unshift({ id: "frame-1", type: "frame", position: { x: 0, y: 0 }, width: 640, height: 400, data: { kind: "frame", title: "参考分区", text: "", rotation: 0, labelMode: "fixed" } });
frameDocument.nodes[1].data.frameId = "frame-1";
for (const [index, mode] of ["hidden", "fixed", "scaled"].entries()) {
frameDocument.nodes[0].data.labelMode = mode;
const response = await fetch(host + canvasPath, { method: "PATCH", headers: { Cookie: session, Origin: host, "Content-Type": "application/json", "If-Match": '"' + (2 + index) + '"' }, body: JSON.stringify({ document: frameDocument }) });
assert.equal(response.status, 200);
const restored = await (await fetch(host + canvasPath, { headers: { Cookie: session } })).json();
assert.equal(restored.document.nodes[0].data.labelMode, mode);
assert.equal(restored.document.nodes[1].data.frameId, "frame-1");
}
assert.equal((await fetch(host + canvasPath)).status, 401);
assert.equal((await fetch(host + "/api/foundry/workspaces/space/search/my-board/canvas")).status, 404);
const oversizedCanvas = await fetch(host + canvasPath, { method: "PATCH", headers: { Cookie: session, "Content-Type": "application/json" }, body: JSON.stringify({ document: "x".repeat(5 * 1024 * 1024) }) });
assert.equal(oversizedCanvas.status, 413);
for (const origin of ["https://example.com", "null"])
assert.equal(
(
@@ -224,7 +303,7 @@ try {
assert.equal(await logout.text(), "");
assert.match(logout.headers.get("set-cookie"), /Max-Age=0/);
console.log(
"PASS: 88 original brand assets, favicon metadata, avatar and profile updates, App Router pages and metadata, body validation, method and query filtering, OAuth redirects, logout, session cookie, token removal, authenticated proxy, invalid session, cross-origin rejection, path allowlist, OAuth validation",
"PASS: Canvas GET/PATCH and independent versions, ETag/If-Match, 1+ MiB snapshot restore, conflict and 5 MiB limit, four ID/slug combinations, authenticated home redirect, anonymous and expired-session landing, canvas-free dashboard, 88 original brand assets, favicon metadata, avatar and profile updates, App Router pages and metadata, body validation, method and query filtering, OAuth redirects, logout, session cookie, token removal, authenticated proxy, invalid session, cross-origin rejection, path allowlist, OAuth validation",
);
} finally {
const exited = once(app, "exit");
+93
View File
@@ -0,0 +1,93 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { canvasReducer, decodeCanvas, emptyCanvas, makeCanvasNode } from "../src/lib/canvas.ts";
import { assignFrameMembership } from "../src/lib/canvas-frames.ts";
function seeded() {
const frame = makeCanvasNode("frame", { x: 100, y: 100 });
const member = makeCanvasNode("text", { x: 160, y: 160 });
const outsider = makeCanvasNode("icon", { x: 900, y: 120 });
return { frame, member, outsider, document: { ...emptyCanvas(), nodes: [frame, member, outsider] } };
}
function state(document) { return { past: [], present: document, future: [] }; }
test("only dropped content joins a frame; pre-existing overlapping content stays outside", () => {
const { frame, member, outsider, document } = seeded();
assert.equal(document.nodes[1].data.frameId, undefined);
const nodes = assignFrameMembership(document.nodes, [member.id]);
assert.equal(nodes[1].data.frameId, frame.id);
assert.equal(nodes[2].data.frameId, undefined);
const untouched = assignFrameMembership(document.nodes, [frame.id]);
assert.equal(untouched[1].data.frameId, undefined);
outsider.position = { x: 200, y: 200 };
assert.equal(assignFrameMembership([frame, member, outsider], [member.id])[2].data.frameId, undefined);
});
test("frames carry existing members without collecting newly overlapped content and undo restores positions", () => {
const { frame, member, outsider, document } = seeded();
member.data.frameId = frame.id;
let history = canvasReducer(state(document), { type: "checkpoint" });
history = canvasReducer(history, { type: "nodes", changes: [{ type: "position", id: frame.id, position: { x: 700, y: 100 } }] });
assert.deepEqual(history.present.nodes[1].position, { x: 760, y: 160 });
assert.equal(history.present.nodes[2].data.frameId, undefined);
assert.deepEqual(history.present.nodes[2].position, outsider.position);
history = canvasReducer(history, { type: "undo" });
assert.deepEqual(history.present.nodes[1].position, member.position);
assert.equal(history.present.nodes[1].data.frameId, frame.id);
});
test("dragging out detaches content and dragging between frames reassigns membership", () => {
const { frame, member } = seeded();
member.data.frameId = frame.id;
member.position = { x: 900, y: 900 };
assert.equal(assignFrameMembership([frame, member], [member.id])[1].data.frameId, undefined);
const second = makeCanvasNode("frame", { x: 800, y: 800 });
assert.equal(assignFrameMembership([frame, second, member], [member.id])[2].data.frameId, second.id);
});
test("multi-selection does not move frame members twice", () => {
const { frame, member, document } = seeded();
member.data.frameId = frame.id;
const result = canvasReducer(state(document), { type: "nodes", changes: [
{ type: "position", id: frame.id, position: { x: 200, y: 200 } },
{ type: "position", id: member.id, position: { x: 260, y: 260 } },
] });
assert.deepEqual(result.present.nodes[1].position, { x: 260, y: 260 });
});
test("deleting a frame keeps its content and undo restores membership", () => {
const { frame, member, document } = seeded();
member.data.frameId = frame.id;
const removed = canvasReducer(state(document), { type: "nodes", changes: [{ type: "remove", id: frame.id }] });
assert.equal(removed.present.nodes.length, 2);
assert.equal(removed.present.nodes[0].data.frameId, undefined);
assert.deepEqual(removed.present.nodes[0].position, member.position);
assert.equal(canvasReducer(removed, { type: "undo" }).present.nodes[1].data.frameId, frame.id);
});
test("all label modes, frame names and memberships survive save/restore and settings undo", () => {
const { frame, member, document } = seeded();
member.data.frameId = frame.id;
for (const labelMode of ["hidden", "fixed", "scaled"]) {
const result = canvasReducer(state(document), { type: "frame", id: frame.id, title: "灵感分区", labelMode });
const restored = decodeCanvas(JSON.stringify(result.present));
assert.equal(restored.nodes[0].type, "frame");
assert.equal(restored.nodes[0].data.title, "灵感分区");
assert.equal(restored.nodes[0].data.labelMode, labelMode);
assert.equal(restored.nodes[1].data.frameId, frame.id);
assert.equal(restored.nodes[0].zIndex, -1);
assert.equal(canvasReducer(result, { type: "undo" }).present.nodes[0].data.title, frame.data.title);
}
});
test("invalid frame references, label modes, frame nesting and rotation are rejected", () => {
for (const mutate of [
({ member }) => { member.data.frameId = "missing"; },
({ frame, member }) => { frame.data.frameId = member.id; },
({ frame }) => { frame.data.labelMode = "unexpected"; },
({ frame }) => { frame.data.rotation = 20; },
]) {
const input = seeded(); mutate(input);
assert.throws(() => decodeCanvas(JSON.stringify(input.document)));
}
});
+37 -1
View File
@@ -1,7 +1,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { CanvasElement, CardElement, TextCardElement, ImageCardElement, ScriptCardElement, PlainTextElement, elementCapabilities } from "../src/lib/canvas-elements.ts";
import { nodeCenter, nodeSize, resizeFromPointer, rotateVector, rotationFromPointer } from "../src/lib/canvas-geometry.ts";
import { nodeConnector, connectorBezier, nodeCenter, nodeSize, resizeFromPointer, rotateVector, rotationFromPointer } from "../src/lib/canvas-geometry.ts";
import { branchCanvasNode, canvasReducer, decodeCanvas, emptyCanvas } from "../src/lib/canvas.ts";
function close(actual, expected) { assert(Math.abs(actual - expected) < 0.00001, `${actual} != ${expected}`); }
@@ -93,3 +93,39 @@ test("old text-card drafts remain cards and invalid transform values are rejecte
assert.throws(() => decodeCanvas(JSON.stringify({ ...document, nodes: [{ ...old, ...patch }] })));
}
});
test("connection endpoints stay on the exact border centers after resize and rotation", () => {
const node = new TextCardElement({ x: 20, y: 30 }).toNode();
const expected = {
0: { top: [150, 30], right: [280, 130], bottom: [150, 230], left: [20, 130] },
90: { top: [250, 130], right: [150, 260], bottom: [50, 130], left: [150, 0] },
180: { top: [150, 230], right: [20, 130], bottom: [150, 30], left: [280, 130] },
};
for (const [rotation, sides] of Object.entries(expected)) {
node.data.rotation = Number(rotation);
for (const [side, point] of Object.entries(sides)) {
const anchor = nodeConnector(node, side);
close(anchor.point.x, point[0]); close(anchor.point.y, point[1]);
close(Math.hypot(anchor.normal.x, anchor.normal.y), 1);
}
}
node.data.rotation = 0;
const resized = transformed(node, resizeFromPointer(node, "bottom-right", { x: 100, y: 50 }));
assert.deepEqual(nodeConnector(resized, "right").point, { x: 380, y: 155 });
assert.deepEqual(nodeConnector(resized, "bottom").point, { x: 200, y: 280 });
});
test("Bezier paths include both exact card anchors, independent of selected handle sizes", () => {
const source = new TextCardElement({ x: 20, y: 30 }).toNode();
const target = new TextCardElement({ x: 500, y: 180 }).toNode();
for (const angle of [0, 37, 90, 180, 270]) {
source.data.rotation = angle;
target.data.rotation = (angle + 45) % 360;
const from = nodeConnector(source, "right"), to = nodeConnector(target, "left");
const path = connectorBezier(from, to);
assert(path.startsWith(`M ${from.point.x},${from.point.y} C `));
assert(path.endsWith(` ${to.point.x},${to.point.y}`));
source.selected = true; target.selected = true;
assert.equal(connectorBezier(nodeConnector(source, "right"), nodeConnector(target, "left")), path);
}
});
+38
View File
@@ -0,0 +1,38 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { canvasReducer, decodeCanvas, emptyCanvas, makeCanvasNode } from "../src/lib/canvas.ts";
import { CanvasElement, CardElement, PlainImageElement } from "../src/lib/canvas-elements.ts";
import { resizeFromPointer } from "../src/lib/canvas-geometry.ts";
import { iconCatalog, iconsById, searchIcons } from "../src/components/canvas/icon-catalog.ts";
test("plain images inherit transforms without card connections and preserve source/name on restore", () => {
const image = new PlainImageElement({ x: 0, y: 0 }, "", "data:image/png;base64,YQ==");
assert(image instanceof CanvasElement); assert.equal(image instanceof CardElement, false);
const node = image.toNode();
assert.equal(node.type, "plainImage"); assert.equal(PlainImageElement.capabilities.connectable, false);
const resized = resizeFromPointer(node, "bottom-right", { x: 320, y: 240 });
assert.equal(resized.width, 640); assert.equal(resized.height, 480);
const renamed = canvasReducer({ past: [], present: { ...emptyCanvas(), nodes: [node] }, future: [] }, { type: "rename-node", id: node.id, title: "参考照片" });
const restored = decodeCanvas(JSON.stringify(renamed.present));
assert.equal(restored.nodes[0].data.title, "参考照片"); assert.equal(restored.nodes[0].data.src, node.data.src);
assert.equal(canvasReducer(renamed, { type: "undo" }).present.nodes[0].data.title, "图片");
});
test("plain image sources are required and pure images cannot acquire card connections", () => {
const image = makeCanvasNode("plain-image", { x: 0, y: 0 }, "data:image/png;base64,YQ==");
const card = makeCanvasNode("text", { x: 300, y: 0 });
const document = { ...emptyCanvas(), nodes: [image, card], edges: [{ id: "edge", source: card.id, target: image.id }] };
assert.throws(() => decodeCanvas(JSON.stringify(document)));
image.data.src = "javascript:bad"; document.edges = [];
assert.throws(() => decodeCanvas(JSON.stringify(document)));
});
test("the complete Lucide catalog has unique backend-compatible identifiers and searchable names", () => {
assert(iconCatalog.length > 2000);
assert.equal(iconsById.size, iconCatalog.length);
for (const icon of iconCatalog) assert.match(icon.name, /^[A-Z][A-Za-z0-9]{0,63}$/);
assert(searchIcons("箭头").length > 45);
assert(searchIcons("arrow left").some((icon) => icon.name === "ArrowLeft"));
assert.equal(iconsById.get("Star").slug, "star");
assert.equal(iconsById.get("WandSparkles").slug, "wand-sparkles");
});
+85
View File
@@ -0,0 +1,85 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { CanvasSync, canvasPath, canvasPayload, readLocalRecovery } from "../src/lib/canvas-sync.ts";
import { emptyCanvas, makeCanvasNode } from "../src/lib/canvas.ts";
import { loadBoardCanvas } from "../src/lib/canvas-loader.ts";
function document(text = "") { const doc = emptyCanvas(); const node = makeCanvasNode("text", { x: 0, y: 0 }); node.id = "text"; node.data.text = text; doc.nodes.push(node); return doc; }
function deferred() { let resolve, reject; const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); return { promise, resolve, reject }; }
const tick = () => new Promise((resolve) => setImmediate(resolve));
test("serialized autosaves use successive versions and coalesce queued documents", async () => {
const calls = [], first = deferred();
const writer = new CanvasSync(async (path, options) => {
calls.push({ path, ...options });
if (calls.length === 1) return first.promise;
return { version: 3 };
}, canvasPath("space", "board"), { version: 1, document: emptyCanvas() }, () => {});
const a = writer.enqueue(document("A")); await tick();
writer.enqueue(document("B")); writer.enqueue(document("C"));
assert.equal(calls.length, 1);
first.resolve({ version: 2 }); await a;
assert.equal(calls.length, 2);
assert.equal(calls[0].headers["If-Match"], '"1"'); assert.equal(calls[1].headers["If-Match"], '"2"');
assert.equal(JSON.parse(calls[1].body).document.nodes[0].data.text, "C"); assert.equal(writer.version, 3);
});
test("version conflicts stop automatic writes and preserve the latest pending content", async () => {
const calls = [];
const writer = new CanvasSync(async (_path, options) => { calls.push(options); throw new Error("version_conflict"); }, "canvas", { version: 7, document: emptyCanvas() }, () => {});
await writer.enqueue(document("A")); await writer.enqueue(document("B"));
assert.equal(calls.length, 1); assert.equal(writer.error, "version_conflict"); assert.equal(writer.version, 7);
});
test("explicit retry sends the newest document after a failed write", async () => {
const calls = [];
const writer = new CanvasSync(async (_path, options) => { calls.push(options); if (calls.length === 1) throw new Error("upstream_unavailable"); return { version: 2 }; }, "canvas", { version: 1, document: emptyCanvas() }, () => {});
await writer.enqueue(document("A")); await writer.enqueue(document("B")); await writer.retry();
assert.equal(calls.length, 2); assert.equal(JSON.parse(calls[1].body).document.nodes[0].data.text, "B"); assert.equal(writer.error, "");
});
test("selection and measured dimensions do not trigger redundant writes or leak UI fields", async () => {
const initial = document("keep"); let calls = 0;
const writer = new CanvasSync(async () => { calls++; return { version: 2 }; }, "canvas", { version: 1, document: initial }, () => {});
const changed = structuredClone(initial); changed.nodes[0].selected = true; changed.nodes[0].measured = { width: 260, height: 200 };
await writer.enqueue(changed); assert.equal(calls, 0);
const payload = canvasPayload(changed);
for (const key of ["selected", "style", "measured", "dragging", "zIndex"]) assert.equal(payload.nodes[0][key], undefined);
const first = writer.enqueue(changed); const second = writer.enqueue(document("new")); await Promise.all([first, second]);
assert.equal(calls, 1);
});
test("all ID/slug combinations load the same canonical board and snapshot", async () => {
for (const workspace of ["space-id", "creative-space"]) for (const board of ["board-id", "my-board"]) {
const calls = [];
const result = await loadBoardCanvas(async (path) => { calls.push(path); return path.endsWith("/canvas") ? { version: 4, document: document("saved") } : { id: "board-id", slug: "my-board", workspace_id: "space-id", kind: "board", title: "Saved" }; }, workspace, board);
assert.equal(result.board.id, "board-id"); assert.equal(result.board.workspace_id, "space-id"); assert.equal(result.snapshot.version, 4);
assert(calls.includes(`workspaces/${workspace}/materials/${board}/canvas`));
}
});
test("failed snapshot loads and mismatched boards prevent editing rather than creating an empty replacement", async () => {
await assert.rejects(loadBoardCanvas(async (path) => { if (path.endsWith("/canvas")) throw new Error("upstream_unavailable"); return { id: "board", workspace_id: "space", kind: "board" }; }, "space", "board"), /upstream/);
await assert.rejects(loadBoardCanvas(async (path) => path.endsWith("/canvas") ? { version: 1, document: emptyCanvas() } : { id: "other", workspace_id: "space", kind: "board" }, "space", "board"), /invalid_reference/);
});
test("dirty local recovery and legacy drafts are offered for explicit migration; clean backups never replace server data", () => {
const remote = { version: 3, document: document("server") };
const local = document("local");
const storage = (values) => ({ getItem: (key) => values[key] || null });
assert.equal(readLocalRecovery(storage({ key: JSON.stringify(local) }), "key", remote).nodes[0].data.text, "local");
assert.equal(readLocalRecovery(storage({ "key:recovery": JSON.stringify({ document: local, dirty: true, baseVersion: 2 }) }), "key", remote).nodes[0].data.text, "local");
assert.equal(readLocalRecovery(storage({ "key:recovery": JSON.stringify({ document: local, dirty: false }), key: JSON.stringify(local) }), "key", remote), null);
assert.equal(readLocalRecovery(storage({ "key:recovery": JSON.stringify({ document: remote.document, dirty: true }) }), "key", remote), null);
});
test("canonical fingerprints ignore server JSON key ordering", async () => {
const remote = document("same"), local = document("same");
remote.nodes[0].data.textStyle = { bold: true, color: "#123456" };
local.nodes[0].data.textStyle = { color: "#123456", bold: true };
let calls = 0;
const writer = new CanvasSync(async () => { calls++; return { version: 2 }; }, "canvas", { version: 1, document: remote }, () => {});
await writer.enqueue(local);
assert.equal(calls, 0);
const storage = { getItem: () => JSON.stringify({ document: local, dirty: true }) };
assert.equal(readLocalRecovery(storage, "key", { version: 1, document: remote }), null);
});
+20
View File
@@ -0,0 +1,20 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { sessionCookie, sessionMaxAge, SESSION_IDLE_SECONDS } from "../src/lib/session-cookie.ts";
test("session cookies respect backend remaining lifetime and a 30-day maximum", () => {
assert.equal(SESSION_IDLE_SECONDS, 2592000);
assert.equal(sessionMaxAge(2592000), 2592000);
assert.equal(sessionMaxAge("3600"), 3600);
assert.equal(sessionMaxAge(90 * 86400), 2592000);
assert.equal(sessionMaxAge(0), 0);
assert.equal(sessionMaxAge(-1), 2592000);
for (const invalid of [Infinity, "garbage", "1.5", NaN, {}, null]) assert.equal(sessionMaxAge(invalid), 2592000);
});
test("renewed cookies retain HttpOnly/SameSite and use the backend-capped deadline", () => {
const cookie = sessionCookie("session-token", 42, true);
assert.match(cookie, /Max-Age=42;/); assert.match(cookie, /HttpOnly/); assert.match(cookie, /SameSite=Lax/); assert.match(cookie, /; Secure$/);
assert(!sessionCookie("session-token", 1000, false).includes("Secure"));
assert.match(sessionCookie("session-token", 0, true), /Max-Age=0/);
});