Rename existing Endoleap proxy and configuration in place [skip ci]
This commit is contained in:
+32
-32
@@ -132,7 +132,7 @@ const app = spawn(
|
||||
],
|
||||
{
|
||||
cwd: fileURLToPath(new URL("../", import.meta.url)),
|
||||
env: { ...process.env, FOUNDRY_API_ORIGIN: "http://127.0.0.1:" + port },
|
||||
env: { ...process.env, BEDROCK_API_ORIGIN: "http://127.0.0.1:" + port },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
@@ -188,7 +188,7 @@ try {
|
||||
}
|
||||
assert.equal((await fetch(host + "/missing-page")).status, 404);
|
||||
// 登录代理必须去掉响应体 token,改设 HttpOnly/SameSite cookie,并报告上游计时。
|
||||
const res = await fetch(host + "/api/foundry/auth/login", {
|
||||
const res = await fetch(host + "/api/bedrock/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Origin: host },
|
||||
body: "{}",
|
||||
@@ -207,7 +207,7 @@ try {
|
||||
// 2500ms 的 Promise.race 只限制 fetch 返回响应头,后面的 reader.read 不在该 deadline 内,不能据此声称首块也受同一计时约束。
|
||||
let streamTimer;
|
||||
try {
|
||||
const streamed = await Promise.race([fetch(host + "/api/foundry/workspaces/space/materials/stream-board/canvas", { headers: { Cookie: session } }), new Promise((_, reject) => { streamTimer = setTimeout(() => reject(new Error("Snapshot proxy buffered the body")), 2500); })]);
|
||||
const streamed = await Promise.race([fetch(host + "/api/bedrock/workspaces/space/materials/stream-board/canvas", { headers: { Cookie: session } }), new Promise((_, reject) => { streamTimer = setTimeout(() => reject(new Error("Snapshot proxy buffered the body")), 2500); })]);
|
||||
assert.equal(streamed.headers.get("etag"), '\"1\"'); assert.equal(streamed.headers.get("x-canvas-schema-version"), "2");
|
||||
assert.match(streamed.headers.get("server-timing"), /upstream;dur=.*proxy_headers;dur=/);
|
||||
assert.ok(streamed.headers.get("set-cookie")?.includes("HttpOnly"));
|
||||
@@ -217,27 +217,27 @@ try {
|
||||
assert.equal(JSON.parse(raw).document.schema_version, 2);
|
||||
} finally { clearTimeout(streamTimer); releaseStream(); }
|
||||
// 子命令循环只检查头透传;随后检查资源 variant、目录分页与 AI 查询参数白名单。
|
||||
const v2Base = host + "/api/foundry/workspaces/space/materials/foundry-generated-id/canvas";
|
||||
const v2Base = host + "/api/bedrock/workspaces/space/materials/foundry-generated-id/canvas";
|
||||
const idem = "11111111-1111-4111-8111-111111111111";
|
||||
for (const path of ["connections", "subgraphs", "subgraphs/migrate", "subgraphs/frame-1/members", "subgraphs/frame-1/dissolve", "transactions/tx-1/undo", "ai/runs", "ai/runs/run-1/cancel", "ai/runs/run-1/apply"]) {
|
||||
const response = await fetch(v2Base + "/" + path, { method: "POST", headers: { Cookie: session, Origin: host, "Content-Type": "application/json", "Idempotency-Key": idem, "If-Match": '\"7\"' }, body: "{}" });
|
||||
assert.equal(response.status, 200, path); const echo = await response.json(); assert.equal(echo.key, idem); assert.equal(echo.version, '\"7\"'); assert.equal(echo.accept, "application/vnd.foundry.canvas+json;version=2");
|
||||
}
|
||||
const preview = await fetch(host + "/api/foundry/workspaces/space/assets/image?variant=preview", { headers: { Cookie: session } });assert.equal(preview.status,200);assert.equal(preview.headers.get("x-asset-variant"),"preview");await preview.arrayBuffer();
|
||||
const directoryResponse = await (await fetch(host + "/api/foundry/workspaces/space/materials?kind=board&sort=modified&include_subgraphs=true&limit=100&offset=100", { headers: { Cookie: session } })).json();
|
||||
const preview = await fetch(host + "/api/bedrock/workspaces/space/assets/image?variant=preview", { headers: { Cookie: session } });assert.equal(preview.status,200);assert.equal(preview.headers.get("x-asset-variant"),"preview");await preview.arrayBuffer();
|
||||
const directoryResponse = await (await fetch(host + "/api/bedrock/workspaces/space/materials?kind=board&sort=modified&include_subgraphs=true&limit=100&offset=100", { headers: { Cookie: session } })).json();
|
||||
const directoryQuery = new URL(directoryResponse.url, "http://mock").searchParams;
|
||||
assert.equal(directoryQuery.get("include_subgraphs"), "true"); assert.equal(directoryQuery.get("offset"), "100");
|
||||
const events = await (await fetch(v2Base + "/ai/runs/run-1?after_seq=12&limit=100&status=active&include_descendants=true&cursor=cursor&secret=drop", { headers: { Cookie: session } })).json();
|
||||
const query = new URL(events.url, "http://mock").searchParams; assert.equal(query.get("after_seq"), "12"); assert.equal(query.get("include_descendants"), "true"); assert.equal(query.get("cursor"), "cursor"); assert.equal(query.get("secret"), null);
|
||||
// 验证慢 body 完整读取和 trace 标识,再检查资源认证、MIME 拒绝、nosniff 与 multipart 转发。
|
||||
const slowSnapshot = await fetch(host + "/api/foundry/workspaces/space/materials/slow-body-board/canvas", { headers: { Cookie: session } });
|
||||
const slowSnapshot = await fetch(host + "/api/bedrock/workspaces/space/materials/slow-body-board/canvas", { headers: { Cookie: session } });
|
||||
assert.ok(slowSnapshot.headers.get("x-canvas-trace-id")); assert.equal((await slowSnapshot.json()).version, 210, "A valid body can finish after the old 15-second total deadline");
|
||||
const asset = await fetch(host + "/api/foundry/workspaces/space/assets/image-1", { headers: { Cookie: session } });
|
||||
const asset = await fetch(host + "/api/bedrock/workspaces/space/assets/image-1", { headers: { Cookie: session } });
|
||||
assert.equal(asset.status, 200); assert.equal(asset.headers.get("content-type"), "image/png"); assert.equal(asset.headers.get("x-content-type-options"), "nosniff"); assert.ok(asset.headers.get("set-cookie")?.includes("HttpOnly")); assert.equal((await asset.arrayBuffer()).byteLength, 8);
|
||||
assert.equal((await fetch(host + "/api/foundry/workspaces/space/assets/image-1")).status, 401);
|
||||
assert.equal((await fetch(host + "/api/foundry/workspaces/space/assets/bad", { headers: { Cookie: session } })).status, 502);
|
||||
assert.equal((await fetch(host + "/api/bedrock/workspaces/space/assets/image-1")).status, 401);
|
||||
assert.equal((await fetch(host + "/api/bedrock/workspaces/space/assets/bad", { headers: { Cookie: session } })).status, 502);
|
||||
const form = new FormData(); form.set("image", new Blob([new Uint8Array([137,80,78,71])], { type: "image/png" }), "test.png");
|
||||
const upload = await (await fetch(host + "/api/foundry/workspaces/space/assets", { method: "POST", headers: { Cookie: session, Origin: host, "Idempotency-Key": idem }, body: form })).json();
|
||||
const upload = await (await fetch(host + "/api/bedrock/workspaces/space/assets", { method: "POST", headers: { Cookie: session, Origin: host, "Idempotency-Key": idem }, body: form })).json();
|
||||
// 这里只核对 multipart Content-Type、image 字段标记及幂等键;未解析 multipart,也未逐字节比较上传文件内容。
|
||||
assert.match(upload.type, /^multipart\/form-data; boundary=/); assert.equal(upload.key, idem); assert.ok(upload.multipart);
|
||||
// 有效会话首页重定向且不缓存私有结果;dashboard 初始 HTML 不应包含画布或 landing。
|
||||
@@ -264,29 +264,29 @@ try {
|
||||
|
||||
assert.equal(
|
||||
(
|
||||
await fetch(host + "/api/foundry/profile", {
|
||||
await fetch(host + "/api/bedrock/profile", {
|
||||
headers: { Cookie: session },
|
||||
})
|
||||
).status,
|
||||
200,
|
||||
);
|
||||
assert.equal((await fetch(host + "/api/foundry/profile")).status, 401);
|
||||
assert.equal((await fetch(host + "/api/bedrock/profile")).status, 401);
|
||||
// 续期只接受有效剩余秒数;非法上游值和无效会话不应产生新的 Set-Cookie。
|
||||
mockSessionSeconds = "3600";
|
||||
const renewed = await fetch(host + "/api/foundry/profile", { headers: { Cookie: session } });
|
||||
const renewed = await fetch(host + "/api/bedrock/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 } });
|
||||
const malformedRenewal = await fetch(host + "/api/bedrock/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" } });
|
||||
const expiredSession = await fetch(host + "/api/bedrock/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();
|
||||
const profile = await (await fetch(host + "/api/bedrock/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", {
|
||||
const updated = await fetch(host + "/api/bedrock/profile", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json", Cookie: session, Origin: host },
|
||||
body: JSON.stringify({ username: "test", display_name: "Updated name" }),
|
||||
@@ -297,7 +297,7 @@ try {
|
||||
assert.equal(updatedProfile.avatar_url, profile.avatar_url);
|
||||
|
||||
// 经真实代理创建、读取和重命名内存图谱,检查服务分配身份、内容保留和元信息版本递增。
|
||||
const create = await fetch(host + "/api/foundry/workspaces/space/materials", {
|
||||
const create = await fetch(host + "/api/bedrock/workspaces/space/materials", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Cookie: session, Origin: host },
|
||||
body: JSON.stringify({ kind: "board", title: "未命名图谱", content: { schema_version: 1 } }),
|
||||
@@ -305,18 +305,18 @@ try {
|
||||
assert.equal(create.status, 201);
|
||||
const graph = await create.json();
|
||||
assert.deepEqual(graph, { id: "foundry-generated-id", workspace_id: "space", kind: "board", version: 1 });
|
||||
const opened = await fetch(host + `/api/foundry/workspaces/${graph.workspace_id}/materials/${graph.id}`, { headers: { Cookie: session } });
|
||||
const opened = await fetch(host + `/api/bedrock/workspaces/${graph.workspace_id}/materials/${graph.id}`, { headers: { Cookie: session } });
|
||||
assert.equal(opened.status, 200);
|
||||
const stored = await opened.json();
|
||||
assert.equal(stored.title, "未命名图谱");
|
||||
assert.equal(stored.workspace_id, "space");
|
||||
assert.equal(stored.content.schema_version, 1);
|
||||
const rename = await fetch(host + `/api/foundry/workspaces/${graph.workspace_id}/materials/${graph.id}`, {
|
||||
const rename = await fetch(host + `/api/bedrock/workspaces/${graph.workspace_id}/materials/${graph.id}`, {
|
||||
method: "PATCH", headers: { "Content-Type": "application/json", Cookie: session, Origin: host, "If-Match": '"1"' },
|
||||
body: JSON.stringify({ title: "改名后的图谱", description: "", content: stored.content }),
|
||||
});
|
||||
assert.equal(rename.status, 204);
|
||||
const renamed = await (await fetch(host + `/api/foundry/workspaces/${graph.workspace_id}/materials/${graph.id}`, { headers: { Cookie: session } })).json();
|
||||
const renamed = await (await fetch(host + `/api/bedrock/workspaces/${graph.workspace_id}/materials/${graph.id}`, { headers: { Cookie: session } })).json();
|
||||
assert.equal(renamed.title, "改名后的图谱");
|
||||
assert.equal(renamed.version, 2);
|
||||
assert.deepEqual(renamed.content, stored.content);
|
||||
@@ -324,14 +324,14 @@ try {
|
||||
// workspace/board 各自使用 ID 或 slug 的四种组合都应定位同一图谱和独立画布版本。
|
||||
// 替身通过 canonical 字符串替换提供该映射;此处验证代理接受四种路径,不验证真实 Foundry 的 slug 解析实现。
|
||||
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 path = `/api/bedrock/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 canvasPath = "/api/bedrock/workspaces/creative-space/materials/my-board/canvas";
|
||||
// 生成超过 1 MiB 的完整快照经代理保存/恢复,再用旧版本重发检查 412;不是增量或大文件性能测试。
|
||||
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 }) });
|
||||
@@ -354,7 +354,7 @@ try {
|
||||
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);
|
||||
assert.equal((await fetch(host + "/api/bedrock/workspaces/space/search/my-board/canvas")).status, 404);
|
||||
// 超过画布 body 上限的请求必须返回 413,不能转成成功保存。
|
||||
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);
|
||||
@@ -364,7 +364,7 @@ try {
|
||||
for (const origin of ["https://example.com", "null"])
|
||||
assert.equal(
|
||||
(
|
||||
await fetch(host + "/api/foundry/auth/login", {
|
||||
await fetch(host + "/api/bedrock/auth/login", {
|
||||
method: "POST",
|
||||
headers: { Origin: origin, "Content-Type": "application/json" },
|
||||
body: "{}",
|
||||
@@ -372,27 +372,27 @@ try {
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
assert.equal((await fetch(host + "/api/foundry/unlisted")).status, 404);
|
||||
assert.equal((await fetch(host + "/api/bedrock/unlisted")).status, 404);
|
||||
assert.equal(
|
||||
(await fetch(host + "/api/oauth/slack?challenge=bad")).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(res.headers.get("cache-control"), "no-store");
|
||||
const secure = await fetch(host + "/api/foundry/auth/login", {
|
||||
const secure = await fetch(host + "/api/bedrock/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "X-Forwarded-Proto": "https" },
|
||||
body: "{}",
|
||||
});
|
||||
assert.match(secure.headers.get("set-cookie"), /; Secure/);
|
||||
for (const [body, status] of [["{", 400], [JSON.stringify({ text: "x".repeat(1024 * 1024) }), 413]]) {
|
||||
const invalid = await fetch(host + "/api/foundry/auth/login", {
|
||||
const invalid = await fetch(host + "/api/bedrock/auth/login", {
|
||||
method: "POST", headers: { "Content-Type": "application/json" }, body,
|
||||
});
|
||||
assert.equal(invalid.status, status);
|
||||
}
|
||||
assert.equal((await fetch(host + "/api/foundry/profile", { method: "PUT" })).status, 405);
|
||||
assert.equal((await fetch(host + "/api/bedrock/profile", { method: "PUT" })).status, 405);
|
||||
// 查询保留 kind/limit 而删除未许可 secret;此处使用替身回显观察最终上游路径。
|
||||
const materials = await fetch(host + "/api/foundry/workspaces/space/materials?kind=board&limit=100&secret=drop", {
|
||||
const materials = await fetch(host + "/api/bedrock/workspaces/space/materials?kind=board&limit=100&secret=drop", {
|
||||
method: "PATCH", headers: { "Content-Type": "application/json" }, body: "{}",
|
||||
});
|
||||
assert.deepEqual(await materials.json(), {
|
||||
@@ -405,7 +405,7 @@ try {
|
||||
assert.equal(redirect.headers.get("location"), `http://127.0.0.1:${port}/projects/endoleap/auth/${provider}?challenge=${"a".repeat(43)}`);
|
||||
}
|
||||
// 登出保持 204 空体并清除 cookie;下方 PASS 长文是摘要,实际覆盖以逐项断言为准。
|
||||
const logout = await fetch(host + "/api/foundry/auth/logout", {
|
||||
const logout = await fetch(host + "/api/bedrock/auth/logout", {
|
||||
method: "POST", headers: { "Content-Type": "application/json", Cookie: session }, body: "{}",
|
||||
});
|
||||
assert.equal(logout.status, 204);
|
||||
|
||||
@@ -35,6 +35,6 @@ test('uncertain upload retries the exact bytes with the same idempotency key',as
|
||||
// 受管原始 URL 转同源认证代理,preview 仅加显示变体参数;普通外部图片地址保持原样。
|
||||
// 这里仅比对字符串,不请求代理,也不验证登录鉴权或预览图片内容。
|
||||
test('preview URLs are renderer-only and do not replace original managed references',()=>{
|
||||
assert.equal(managedImageSource(asset.url),`/api/foundry/workspaces/w/assets/${id}`);assert.equal(managedImageSource(asset.url,true),`/api/foundry/workspaces/w/assets/${id}?variant=preview`);
|
||||
assert.equal(managedImageSource(asset.url),`/api/bedrock/workspaces/w/assets/${id}`);assert.equal(managedImageSource(asset.url,true),`/api/bedrock/workspaces/w/assets/${id}?variant=preview`);
|
||||
assert.equal(managedImageSource('https://example.com/photo.png',true),'https://example.com/photo.png');
|
||||
});
|
||||
|
||||
@@ -55,7 +55,7 @@ globalThis.ResizeObserver = window.ResizeObserver = class {
|
||||
let apiMock = null;
|
||||
const requests = [];
|
||||
globalThis.fetch = async (url, options) => {
|
||||
if (apiMock && String(url).startsWith("/api/foundry/")) return apiMock(url, options);
|
||||
if (apiMock && String(url).startsWith("/api/bedrock/")) return apiMock(url, options);
|
||||
requests.push(String(url));
|
||||
assert.ok(String(url).startsWith("/canvas-icons/"), `Unexpected network request ${url}`);
|
||||
if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");
|
||||
|
||||
@@ -168,7 +168,7 @@ export async function canvasV2Scenario({root,act,h,GraphCanvas,window,makeCanvas
|
||||
assert.ok(document.querySelector('[aria-label="AI 模型"]').textContent.includes('测试图片模型'),'Sticky AI mode selects models for the newly selected image');
|
||||
assert.ok(!document.querySelector('[aria-label="AI 模型"]').textContent.includes('测试文本模型'));
|
||||
await event(document.querySelector('[aria-label="执行 AI"]'),'click');
|
||||
await waitUntil(()=>document.querySelector('.react-flow__node[data-id="image-target"] img')?.getAttribute('src')==='/api/foundry/workspaces/w/assets/generated-image?variant=preview','managed AI image result');
|
||||
await waitUntil(()=>document.querySelector('.react-flow__node[data-id="image-target"] img')?.getAttribute('src')==='/api/bedrock/workspaces/w/assets/generated-image?variant=preview','managed AI image result');
|
||||
const generated=records.get(parent).document.nodes.find(node=>node.id==='image-target');assert.equal(generated.width,image.width);assert.equal(generated.height,image.height);assert.equal(generated.data.title,'图片目标');
|
||||
await waitUntil(()=>document.querySelector('[aria-label="执行 AI"]'),'image run terminal UI');
|
||||
await event(document.querySelector('[aria-label="执行 AI"]'),'click');
|
||||
|
||||
@@ -70,7 +70,7 @@ test('eight-direction resize is free by default in resize mode and Shift locks t
|
||||
});
|
||||
// 受管资产显示转认证同源代理,普通外部 URL 保留;这里只检查地址转换,不验证实际认证请求。
|
||||
test('managed assets render through the authenticated same-origin proxy',()=>{
|
||||
assert.equal(managedImageSource('https://api.foundry.entroia.com/projects/endoleap/workspaces/w/assets/a'),'/api/foundry/workspaces/w/assets/a');assert.equal(managedImageSource('https://example.com/a.png'),'https://example.com/a.png');
|
||||
assert.equal(managedImageSource('https://api.foundry.entroia.com/projects/endoleap/workspaces/w/assets/a'),'/api/bedrock/workspaces/w/assets/a');assert.equal(managedImageSource('https://example.com/a.png'),'https://example.com/a.png');
|
||||
});
|
||||
|
||||
// 连线持久 owner 是最低共同祖先,事务参与者恰为两条 owner 路径的并集;祖先本身不需要重复登记。
|
||||
|
||||
@@ -41,7 +41,7 @@ test('asset adapter preserves byte identity and headers and validates the scoped
|
||||
test('a headless host supplies display URLs without changing canonical asset identity or authority',async()=>{
|
||||
const options={workspaceId:id(4),transport:async()=>{throw Error('display routing must not make a request');}};
|
||||
const browser=createFoundryAssets(options),host=createFoundryAssets({...options,displayURL:asset=>`https://host.example/preview/${encodeURIComponent(asset)}`});
|
||||
assert.equal(browser.displayURL(id(1)),`/api/foundry/workspaces/${id(4)}/assets/${id(1)}?variant=preview`);
|
||||
assert.equal(browser.displayURL(id(1)),`/api/bedrock/workspaces/${id(4)}/assets/${id(1)}?variant=preview`);
|
||||
assert.equal(host.displayURL(id(1)),`https://host.example/preview/${id(1)}`);
|
||||
assert.equal(host.sourceURL(id(1)),browser.sourceURL(id(1)));assert.equal(host.authority.scope,browser.authority.scope);
|
||||
});
|
||||
|
||||
@@ -36,7 +36,7 @@ const reservation=createServer();await new Promise(resolve=>reservation.listen(0
|
||||
let next,logs='',launchError;
|
||||
try{
|
||||
// 复制实际 route 及它依赖的响应/会话模块;临时页面仅满足 Next 项目结构,不替换被测 route。
|
||||
for(const filename of ['package.json','tsconfig.json','src/app/api/foundry/[...path]/route.ts','src/app/api/bedrock/[...path]/route.ts','src/lib/canvas-response.ts','src/lib/session-cookie.ts']){
|
||||
for(const filename of ['package.json','tsconfig.json','src/app/api/bedrock/[...path]/route.ts','src/lib/canvas-response.ts','src/lib/session-cookie.ts']){
|
||||
const target=join(directory,filename);await mkdir(resolve(target,'..'),{recursive:true});await copyFile(join(source,filename),target);
|
||||
}
|
||||
// 复用当前依赖树而不重新安装,临时项目的源码和编译目录与主项目分开。
|
||||
@@ -44,62 +44,59 @@ try{
|
||||
await writeFile(join(directory,'src/app/layout.tsx'),'export default function Layout({children}:{children:React.ReactNode}){return <html><body>{children}</body></html>}');
|
||||
await writeFile(join(directory,'src/app/page.tsx'),'export default function Page(){return <main>Proxy verification fixture</main>}');
|
||||
// 显式运行 webpack 开发服务器并指向本地上游,detached 便于 finally 按进程组清理。
|
||||
next=spawn(process.execPath,[join(source,'node_modules/next/dist/bin/next'),'dev','--webpack','--hostname','127.0.0.1','--port',String(port)],{cwd:directory,detached:true,env:{...process.env,NEXT_TELEMETRY_DISABLED:'1',FOUNDRY_API_ORIGIN:`http://127.0.0.1:${upstream.address().port}`,NEXT_PUBLIC_FOUNDRY_PROJECT:'legacy-fixture',NEXT_PUBLIC_BEDROCK_PROJECT:'fixture'},stdio:['ignore','pipe','pipe']});
|
||||
next=spawn(process.execPath,[join(source,'node_modules/next/dist/bin/next'),'dev','--webpack','--hostname','127.0.0.1','--port',String(port)],{cwd:directory,detached:true,env:{...process.env,NEXT_TELEMETRY_DISABLED:'1',BEDROCK_API_ORIGIN:`http://127.0.0.1:${upstream.address().port}`,NEXT_PUBLIC_BEDROCK_PROJECT:'fixture'},stdio:['ignore','pipe','pipe']});
|
||||
// 只保留最后 12000 字符日志;启动失败和退出必须被 readiness 循环识别。
|
||||
next.stdout.on('data',chunk=>{logs=(logs+chunk).slice(-12000)});next.stderr.on('data',chunk=>{logs=(logs+chunk).slice(-12000)});next.on('error',error=>{launchError=error});
|
||||
// 最多 90 次探测,单次请求超时 1.5 秒、失败间隔 250 毫秒;只有实际代理返回 200 才开始断言。
|
||||
let ready=false;
|
||||
for(let attempt=0;attempt<90;attempt++){
|
||||
if(launchError)throw launchError;if(next.exitCode!==null)throw new Error('Next exited during startup:\n'+logs);
|
||||
try{const response=await fetch(`http://127.0.0.1:${port}/api/foundry/profile`,{signal:AbortSignal.timeout(1500)});await response.text();if(response.status===200){ready=true;break}}catch{}
|
||||
try{const response=await fetch(`http://127.0.0.1:${port}/api/bedrock/profile`,{signal:AbortSignal.timeout(1500)});await response.text();if(response.status===200){ready=true;break}}catch{}
|
||||
await pause(250);
|
||||
}
|
||||
if(!ready)throw new Error('Next did not become ready:\n'+logs);
|
||||
const bedrockProfile=await fetch(`http://127.0.0.1:${port}/api/bedrock/profile`,{signal:AbortSignal.timeout(15000)});
|
||||
assert.equal(bedrockProfile.status,200);
|
||||
assert.deepEqual(await bedrockProfile.json(),{id:'fixture'});
|
||||
assert.deepEqual(received.slice(-2).map(request=>request.path),['/projects/fixture/profile','/projects/fixture/profile']);
|
||||
assert.equal(received.at(-1)?.path,'/projects/fixture/profile');
|
||||
// 规范文档操作路径使用固定 workspace/material,后续从它推导资产及 AI 路由。
|
||||
const path='workspaces/10000000-0000-4000-8000-000000000003/materials/10000000-0000-4000-8000-000000000001/canvas/model/operations';
|
||||
// 1.1 MB 请求超过通用 1 MiB 上限但低于规范文档专用 5 MiB 上限,专门覆盖该路由的体积策略。
|
||||
const body=' {\n "protocol_version":2,"request_id":"'+key+'","fixture":"'+ 'x'.repeat(1100000)+'"\n} ';
|
||||
// 发送超过通用限制但低于文档专用限制的原始 body,核对上游状态码及终态回执字节不变。
|
||||
const response=await fetch(`http://127.0.0.1:${port}/api/foundry/${path}`,{method:'POST',body,headers:{'Content-Type':'application/json','Idempotency-Key':key,'X-Expected-Account':account,Cookie:'foundry_session=fixture-session',Origin:`http://127.0.0.1:${port}`},signal:AbortSignal.timeout(20000)});
|
||||
const response=await fetch(`http://127.0.0.1:${port}/api/bedrock/${path}`,{method:'POST',body,headers:{'Content-Type':'application/json','Idempotency-Key':key,'X-Expected-Account':account,Cookie:'foundry_session=fixture-session',Origin:`http://127.0.0.1:${port}`},signal:AbortSignal.timeout(20000)});
|
||||
assert.equal(response.status,409);assert.equal(await response.text(),responseBytes);
|
||||
// 从上游记录检查 body、幂等键、预期账户,以及 session cookie 转成 Bearer 的实际结果。
|
||||
const request=received.find(item=>item.path.endsWith('/model/operations'));
|
||||
assert.ok(request);assert.equal(request.body.toString(),body);assert.equal(request.headers['idempotency-key'],key);assert.equal(request.headers['x-expected-account'],account);assert.equal(request.headers.authorization,'Bearer fixture-session');
|
||||
// 资产回执和元数据是 JSON 路径;元数据还检查身份传递与 no-store,避免误走图片 body 验证。
|
||||
const receiptPath=`workspaces/10000000-0000-4000-8000-000000000003/assets/operations/${key}`;
|
||||
const assetReceipt=await fetch(`http://127.0.0.1:${port}/api/foundry/${receiptPath}`);assert.equal(assetReceipt.status,200);assert.deepEqual(await assetReceipt.json(),{id:'fixture'});
|
||||
const metadata=await fetch(`http://127.0.0.1:${port}/api/foundry/${receiptPath.replace('/operations/','/metadata/')}`,{headers:{'X-Expected-Account':account,Cookie:'foundry_session=fixture-session'}});assert.equal(metadata.status,200);assert.deepEqual(await metadata.json(),{id:'fixture'});assert.match(metadata.headers.get('cache-control'),/no-store/);const metadataRequest=received.find(item=>item.path.includes('/assets/metadata/'));assert.equal(metadataRequest.headers['x-expected-account'],account);assert.equal(metadataRequest.headers.authorization,'Bearer fixture-session');
|
||||
const assetReceipt=await fetch(`http://127.0.0.1:${port}/api/bedrock/${receiptPath}`);assert.equal(assetReceipt.status,200);assert.deepEqual(await assetReceipt.json(),{id:'fixture'});
|
||||
const metadata=await fetch(`http://127.0.0.1:${port}/api/bedrock/${receiptPath.replace('/operations/','/metadata/')}`,{headers:{'X-Expected-Account':account,Cookie:'foundry_session=fixture-session'}});assert.equal(metadata.status,200);assert.deepEqual(await metadata.json(),{id:'fixture'});assert.match(metadata.headers.get('cache-control'),/no-store/);const metadataRequest=received.find(item=>item.path.includes('/assets/metadata/'));assert.equal(metadataRequest.headers['x-expected-account'],account);assert.equal(metadataRequest.headers.authorization,'Bearer fixture-session');
|
||||
console.log('PASS asset metadata JSON uses the actual authenticated Next proxy without image-body validation or caching');
|
||||
// FormData 自带 boundary;下面核对文件内容片段、Content-Type 和资源/幂等身份头,未逐字节比较整份 multipart 包。
|
||||
const multipart=new FormData();multipart.append('image',new Blob(['immutable file'],{type:'image/png'}),'fixture.png');
|
||||
const assetPath=receiptPath.split('/operations/')[0],resourceId='10000000-0000-4000-8000-000000000006';
|
||||
const uploaded=await fetch(`http://127.0.0.1:${port}/api/foundry/${assetPath}`,{method:'POST',body:multipart,headers:{'X-Resource-Id':resourceId,'Idempotency-Key':key,'X-Expected-Account':account}});await uploaded.text();assert.equal(uploaded.status,200);
|
||||
const uploaded=await fetch(`http://127.0.0.1:${port}/api/bedrock/${assetPath}`,{method:'POST',body:multipart,headers:{'X-Resource-Id':resourceId,'Idempotency-Key':key,'X-Expected-Account':account}});await uploaded.text();assert.equal(uploaded.status,200);
|
||||
const upload=received.find(item=>item.path.endsWith('/assets'));assert.equal(upload.headers['x-resource-id'],resourceId);assert.equal(upload.headers['idempotency-key'],key);assert.match(upload.body.toString(),/immutable file/);assert.match(upload.headers['content-type'],/^multipart\/form-data; boundary=/);
|
||||
console.log('PASS asset receipt JSON and multipart resource identity cross the actual Next proxy');
|
||||
// AI 受理同样保留冻结 JSON 空白、幂等键和 If-Match,并协商 canvas v2;查询回执与事件游标单独检查。
|
||||
const aiPath=path.replace('/model/operations','/ai/runs');
|
||||
const frozenAI=' {\n "protocol_version":2,"request_id":"'+key+'","prompt":"保留请求字节" } ';
|
||||
const aiResponse=await fetch(`http://127.0.0.1:${port}/api/foundry/${aiPath}`,{method:'POST',body:frozenAI,headers:{'Content-Type':'application/json','Idempotency-Key':key,'If-Match':'"7"','X-Expected-Account':account,Cookie:'foundry_session=fixture-session'}});
|
||||
const aiResponse=await fetch(`http://127.0.0.1:${port}/api/bedrock/${aiPath}`,{method:'POST',body:frozenAI,headers:{'Content-Type':'application/json','Idempotency-Key':key,'If-Match':'"7"','X-Expected-Account':account,Cookie:'foundry_session=fixture-session'}});
|
||||
await aiResponse.text();assert.equal(aiResponse.status,200);
|
||||
const ai=received.find(item=>item.path.endsWith('/ai/runs'));
|
||||
assert.equal(ai.body.toString(),frozenAI);assert.equal(ai.headers['if-match'],'"7"');assert.equal(ai.headers['idempotency-key'],key);assert.equal(ai.headers['x-expected-account'],account);assert.equal(ai.headers.authorization,'Bearer fixture-session');assert.equal(ai.headers.accept,'application/vnd.foundry.canvas+json;version=2');
|
||||
const aiReceipt=await fetch(`http://127.0.0.1:${port}/api/foundry/${aiPath.replace('/runs','/operations')}/${key}`);await aiReceipt.text();assert.equal(aiReceipt.status,200);
|
||||
const aiReceipt=await fetch(`http://127.0.0.1:${port}/api/bedrock/${aiPath.replace('/runs','/operations')}/${key}`);await aiReceipt.text();assert.equal(aiReceipt.status,200);
|
||||
assert.ok(received.some(item=>item.path.endsWith('/ai/operations/'+key)));
|
||||
const aiEvents=await fetch(`http://127.0.0.1:${port}/api/foundry/${aiPath}/${key}?after_seq=41&limit=100`);await aiEvents.text();assert.equal(aiEvents.status,200);
|
||||
const aiEvents=await fetch(`http://127.0.0.1:${port}/api/bedrock/${aiPath}/${key}?after_seq=41&limit=100`);await aiEvents.text();assert.equal(aiEvents.status,200);
|
||||
assert.ok(received.some(item=>item.path.endsWith('/ai/runs/'+key+'?limit=100&after_seq=41')));
|
||||
console.log('PASS frozen AI bytes, identity, version header, admission receipt and event cursor cross the actual Next proxy');
|
||||
// 上游尾部仍挂起时读取第一块,随后释放并核对余下字节,验证端到端增量转发。
|
||||
const streamed=await fetch(`http://127.0.0.1:${port}/api/foundry/${path.replace('/operations','')}`,{headers:{Accept:'application/vnd.foundry.canvas-model+ndjson;version=1'}});
|
||||
const streamed=await fetch(`http://127.0.0.1:${port}/api/bedrock/${path.replace('/operations','')}`,{headers:{Accept:'application/vnd.foundry.canvas-model+ndjson;version=1'}});
|
||||
assert.equal(streamed.headers.get('content-type'),'application/vnd.foundry.canvas-model+ndjson;version=1');
|
||||
// 尾部 gate 尚未放开就等待首块,才能区分增量转发和整条缓冲;随后放开并排空剩余 body。
|
||||
const reader=streamed.body.getReader(),first=await reader.read();assert.equal(new TextDecoder().decode(first.value),streamPrefix);streamRelease();let rest='';while(true){const next=await reader.read();if(next.done)break;rest+=new TextDecoder().decode(next.value);}assert.equal(rest,streamTail);reader.releaseLock();
|
||||
console.log('PASS negotiated canonical NDJSON and first chunk cross the actual Next proxy before the gated tail');
|
||||
// 多余路径段应在代理 allowlist 被拒绝,不能发到上游再依赖上游返回错误。
|
||||
const before=received.length,invalid=await fetch(`http://127.0.0.1:${port}/api/foundry/${path}/unexpected/extra`,{signal:AbortSignal.timeout(10000)});await invalid.text();assert.equal(invalid.status,404);assert.equal(received.length,before);
|
||||
const before=received.length,invalid=await fetch(`http://127.0.0.1:${port}/api/bedrock/${path}/unexpected/extra`,{signal:AbortSignal.timeout(10000)});await invalid.text();assert.equal(invalid.status,404);assert.equal(received.length,before);
|
||||
console.log('PASS actual Next proxy preserves frozen request bytes/key/account and raw terminal receipt above 1 MiB');
|
||||
console.log('PASS canonical route allowlist rejects unexpected paths without contacting the upstream');
|
||||
}finally{
|
||||
|
||||
@@ -216,7 +216,7 @@ module.exports=function(source){return nativeTransform.call(this,source).replace
|
||||
await symlink(join(source, 'node_modules'), join(directory, 'node_modules'));
|
||||
// 统一 Next 子进程启动和日志尾部收集;独立进程组供 finally 一并终止,API origin 指向本次上游。
|
||||
const launchNext=args=>{
|
||||
const child=spawn(process.execPath,[join(source,'node_modules/next/dist/bin/next'),...args],{cwd:directory,detached:true,env:{...process.env,NEXT_TELEMETRY_DISABLED:'1',FOUNDRY_API_ORIGIN:`http://127.0.0.1:${upstream.address().port}`,NEXT_PUBLIC_FOUNDRY_PROJECT:'endoleap'},stdio:['ignore','pipe','pipe']});
|
||||
const child=spawn(process.execPath,[join(source,'node_modules/next/dist/bin/next'),...args],{cwd:directory,detached:true,env:{...process.env,NEXT_TELEMETRY_DISABLED:'1',BEDROCK_API_ORIGIN:`http://127.0.0.1:${upstream.address().port}`,NEXT_PUBLIC_BEDROCK_PROJECT:'endoleap'},stdio:['ignore','pipe','pipe']});
|
||||
child.stdout.on('data',chunk=>{logs=(logs+chunk).slice(-16000);});child.stderr.on('data',chunk=>{logs=(logs+chunk).slice(-16000);});return child;
|
||||
};
|
||||
let buildMs;
|
||||
@@ -229,7 +229,7 @@ module.exports=function(source){return nativeTransform.call(this,source).replace
|
||||
next=launchNext([productionMode?'start':'dev',...productionMode?[]:[`--${bundler}`],'--hostname','127.0.0.1','--port',String(port)]);
|
||||
// 有界探测真实代理 profile,并检查 Next 提前退出;后续页面等待还会验证应用是否实际可用。
|
||||
// 循环结束后未另设 ready 断言;120 次都未成功时仍进入浏览器阶段,由后续导航/页面等待暴露未就绪。
|
||||
for (let i = 0; i < 120; i++) { if (next.exitCode !== null) throw new Error(logs); try { const r = await fetch(`http://127.0.0.1:${port}/api/foundry/profile`, { signal: AbortSignal.timeout(1000) }); if (r.ok) break; } catch {} await pause(250); }
|
||||
for (let i = 0; i < 120; i++) { if (next.exitCode !== null) throw new Error(logs); try { const r = await fetch(`http://127.0.0.1:${port}/api/bedrock/profile`, { signal: AbortSignal.timeout(1000) }); if (r.ok) break; } catch {} await pause(250); }
|
||||
// 只保留本次隔离 Chrome 的日志尾部,CHROME_BIN 可覆盖可执行路径,不连接日常 profile。
|
||||
let browserLogs='';
|
||||
chrome = spawn(process.env.CHROME_BIN ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', ['--headless=new', '--no-first-run', '--disable-background-networking', '--disable-component-update', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore','ignore','pipe'] });
|
||||
|
||||
Reference in New Issue
Block a user