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");