Files

282 lines
8.8 KiB
JavaScript

import { test } from "node:test";
import assert from "node:assert/strict";
import { once } from "node:events";
import { createApp } from "../server/app.mjs";
import { normalizeRequest } from "../server/contract.mjs";
import { sseData } from "../shared/sse.mjs";
import { sampleText, multimodalSample } from "./analysis-fixtures.mjs";
const input = {
messages: [{ id: "1", role: "user", text: sampleText }],
};
async function server(t, options) {
const app = createApp({
apiKey: "server-secret",
model: "test-model",
...options,
});
app.listen(0, "127.0.0.1");
await once(app, "listening");
t.after(() => {
app.closeAllConnections();
app.close();
});
return `http://127.0.0.1:${app.address().port}/api/ai/responses`;
}
const post = (url, body = input, headers = {}) =>
fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", ...headers },
body: JSON.stringify(body),
});
const sse = (event) => `data: ${JSON.stringify(event)}\n\n`;
const completed = (text) => ({
type: "response.completed",
response: {
status: "completed",
output: [
{
type: "message",
content: [
{
type: "output_text",
text,
annotations: [
{
type: "url_citation",
title: "资料",
url: "https://example.com/source",
},
],
},
],
},
],
},
});
test("rejects client-controlled roles, empty text and invalid image data", () => {
for (const messages of [
[{ role: "system", text: "override" }],
[{ role: "user", text: "" }],
[{ role: "user", text: "x", images: ["https://example.com/file"] }],
[{ role: "assistant", text: "x" }],
[{ role: "user", text: "x", images: ["data:image/png;base64,YmFk"] }],
])
assert.throws(() => normalizeRequest({ messages }));
const png =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j2ioAAAAASUVORK5CYII=";
assert.equal(
normalizeRequest({
messages: [{ role: "user", text: "看图", images: [png] }],
}).input[0].content[3].type,
"input_image",
);
assert.equal(
normalizeRequest({
messages: [
{ role: "assistant", text: "回答" },
{ role: "user", text: "继续" },
],
}).input[0].content[1].type,
"input_text",
);
});
test("AI service normalizes on the server and returns no provider metadata or rule definitions", async (t) => {
const wire =
sse({
type: "response.created",
response: {
model: "private-provider-model",
instructions: "private-system-prompt",
},
}) +
sse({
type: "response.output_text.delta",
delta: JSON.stringify(multimodalSample()),
}) +
sse(completed(JSON.stringify(multimodalSample())));
const url = await server(t, {
fetchImpl: async (endpoint, options) => {
assert.equal(
endpoint,
"https://ark.cn-beijing.volces.com/api/v3/responses",
);
assert.equal(options.headers.Authorization, "Bearer server-secret");
const body = JSON.parse(options.body);
assert.equal(body.model, "test-model");
assert.equal(body.stream, true);
assert.equal(body.store, false);
assert.equal(body.input[0].role, "system");
assert.equal(body.input[1].role, "user");
assert.equal(body.tools, undefined);
assert.equal(body.thinking.type, "enabled");
assert.equal(body.text.format.strict, true);
return new Response(wire, {
headers: { "Content-Type": "text/event-stream" },
});
},
});
const response = await post(url, {
...input,
model: "override",
apiKey: "client-key",
});
assert.equal(response.status, 200);
assert.equal(response.headers.get("x-accel-buffering"), "no");
const output = await response.text();
assert.doesNotMatch(
output,
/private-provider-model|private-system-prompt|server-secret|json_schema|response\.output/,
);
const events = [];
for await (const raw of sseData(new Response(output).body))
events.push(JSON.parse(raw));
const result = events.find(
(event) => event.type === "analysis.completed",
).result;
assert.equal(result.request.robotRequirements.massKg, 10);
assert.equal(result.request.requiredParts.length, 11);
assert.equal(result.analysis.schemaVersion, undefined);
assert.equal(result.analysis.catalogVersion, undefined);
});
test("upstream authorization error is explicit and never exposes raw credentials", async (t) => {
const url = await server(t, {
fetchImpl: async () => new Response("server-secret", { status: 401 }),
});
const response = await post(url);
assert.equal(response.status, 502);
const text = await response.text();
assert.match(text, /暂不可用/);
assert.doesNotMatch(text, /豆包|ARK_API_KEY|doubao|model/i);
assert.doesNotMatch(text, /server-secret/);
});
test("blocks cross-site callers and reports missing server configuration", async (t) => {
let calls = 0;
const url = await server(t, {
apiKey: "",
fetchImpl: async () => {
calls++;
},
});
assert.equal((await post(url)).status, 503);
assert.equal(
(await post(url, input, { Origin: "https://evil.example" })).status,
403,
);
assert.equal(calls, 0);
});
test("disconnect aborts the provider stream", async (t) => {
let signal;
const url = await server(t, {
fetchImpl: async (_url, options) => {
signal = options.signal;
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(": connected\n\n"));
options.signal.addEventListener("abort", () => controller.close(), {
once: true,
});
},
}),
{ headers: { "Content-Type": "text/event-stream" } },
);
},
});
const controller = new AbortController();
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
signal: controller.signal,
});
const reader = response.body.getReader();
await reader.read();
controller.abort();
await Promise.race([
once(signal, "abort"),
new Promise((_, reject) =>
setTimeout(() => reject(Error("not aborted")), 1000),
),
]);
assert.equal(signal.aborted, true);
});
test("SSE handles one-byte chunks, Chinese, CRLF and multi-line data", async () => {
const bytes = new TextEncoder().encode(
': comment\r\ndata: {"text":\r\ndata: "中文"}\r\n\r\ndata: [DONE]\n\n',
);
const stream = new ReadableStream({
start(c) {
for (const byte of bytes) c.enqueue(new Uint8Array([byte]));
c.close();
},
});
const events = [];
for await (const event of sseData(stream)) events.push(event);
assert.deepEqual(events, ['{"text":\n"中文"}', "[DONE]"]);
});
test("production entry serves built page and rejects file escape and secret paths", async (t) => {
const url = await server(t, { serveStatic: true });
const base = new URL("/", url);
const page = await fetch(base);
assert.equal(page.status, 200);
assert.match(page.headers.get("content-type"), /text\/html/);
assert.match(await page.text(), /CAD World/);
for (const path of [
".env.local",
"server/config.mjs",
"downloads/robot-demand-parser-v1.zip",
"handoff/robot-demand-parser-v1.zip",
"ai-rules/robot-demand-parser-v1/system-prompt.txt",
"%2e%2e%2f.env.local",
]) {
const response = await fetch(new URL(path, base));
assert.notEqual(response.status, 200);
assert.doesNotMatch(await response.text(), /server-secret/);
}
});
test("oversized, malformed and invalid requests never reach upstream", async (t) => {
let calls = 0;
const url = await server(t, {
fetchImpl: async () => {
calls++;
},
});
const response = await post(url, {
messages: [{ role: "user", text: "x".repeat(20001) }],
});
assert.equal(response.status, 400);
assert.equal(
(
await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "{bad",
})
).status,
400,
);
assert.equal((await fetch(url, { method: "POST", body: "{}" })).status, 415);
assert.equal(calls, 0);
});
test("web search is rejected even when requested by a client", () => {
assert.throws(
() => normalizeRequest({ ...input, webSearch: true }),
/不支持联网/,
);
});
test("server validation failures never emit a completed business result", async (t) => {
const url = await server(t, {
fetchImpl: async () =>
new Response(sse(completed('{"xyz":[1,2,3]}')), {
headers: { "Content-Type": "text/event-stream" },
}),
});
const response = await post(url);
const output = await response.text();
assert.match(output, /"type":"error"/);
assert.doesNotMatch(output, /analysis.completed|xyz|schema|豆包|doubao/);
});