Files
plugins/packages/fingerprint/tests/server.test.ts
T
yetone e7dfe88218 fingerprint 0.2.1: the page shows in magpie's Linux and Windows windows
nb5p (Discord #feedback, 10-31): the 模型指纹 page stays blank in the
desktop app while `magpie web` (Chromium) shows it.

Cause, Linux: magpie frames a plugin page in <iframe sandbox="allow-scripts">,
so the service document has an opaque origin. WebKitGTK (2.52.6, magpie's
Linux window) then matches nothing to CSP 'self', and the service's policy
was 'self' alone for scripts, styles and images: the bundle was never
requested. Chromium and macOS WebKit match 'self' there, so web mode and the
Mac app worked. The service now names its own validated listener
(http://127.0.0.1:<port> or localhost:<port>) and, when proxied, the
validated launcher origin, in every fetch directive. Nothing else is
allowed: script-src keeps its nonce and no 'unsafe-inline', and
object-src/base-uri/form-action are 'none'.

Two Windows faults on the same path:
- boot.js took the window's http://wails.localhost for a remote web page
  and showed "upgrade magpie" instead of going to the local service.
  Every *.localhost, localhost, ::1 and 127.x now count as this computer
  (the service still checks Host and Origin and its bearer token).
- server.ts kept assets inside ui/ with startsWith(resolve(uiDir) + "/"),
  which never holds for backslash paths, so every asset was a 404 on
  Windows, in web mode too. It now uses path.relative, and still refuses
  .., encoded .. and a backslash escape.

integration.md says the same about the CSP. dist rebuilt with Bun 1.4.2 on
mote (the old source rebuilt to the committed dist byte for byte, so the
dist diff is only this change).

Run:
- mote (macOS 27): bun run build, typecheck, bun test: 33 pass.
- win-run (Windows 11): bun test: 33 pass.
- Linux, the real app: a dev magpie (-tags dev,gtk3) in WSL magpie-desktop
  under a sandbox HOME, with this plugin installed. Old plugin: the frame
  reached the service and no script ran, blank. New: the service page
  rendered and connected to magpie.
- macOS, a WKWebView with a wails:// scheme over a real dev backend on
  mote, sandboxed frame: renders with the old and the new policy.

Broken by hand:
- the new CSP test is red on the old server.ts (no own origin in
  script-src etc.);
- the boot test for wails.localhost is red on the old boot.js;
- the asset test is red on Windows with the old containment check.

Not tried: the real Windows Wails app (WebView2) end to end, and the
reporter's own machine; their platform isn't stated, and Linux is the one
where this reproduces.
2026-11-01 00:08:40 +08:00

219 lines
9.1 KiB
TypeScript

import { afterAll, beforeAll, expect, test } from 'bun:test';
import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { startServer } from '../src/server';
import { Store } from '../src/store';
import { demoHistory } from '../src/demo';
let dir: string, base: string, token: string, service: Awaited<ReturnType<typeof startServer>>;
const api = (path: string, init: RequestInit = {}) =>
fetch(`${base}/api/${path}`, {
...init,
headers: {
authorization: `Bearer ${token}`,
'content-type': 'application/json',
...init.headers,
},
});
beforeAll(async () => {
dir = await mkdtemp(join(tmpdir(), 'magpie-fingerprint-test-'));
await mkdir(join(dir, 'ui'));
await writeFile(join(dir, 'ui/index.html'), '<!doctype html><head></head><body>Test</body>');
await mkdir(join(dir, 'ui/assets'));
await writeFile(join(dir, 'ui/assets/app.js'), 'export {};');
await writeFile(join(dir, 'outside.txt'), 'not served');
service = await startServer({ port: 0, dataDir: dir, uiDir: join(dir, 'ui'), demo: true });
base = `http://127.0.0.1:${service.port}`;
const html = await (await fetch(base)).text();
token = JSON.parse(html.match(/window\.__FINGERPRINT__=(.*?)<\/script>/)![1]).token;
});
afterAll(async () => {
await service?.close();
await rm(dir, { recursive: true, force: true });
});
test('requires bearer token and rejects cross-site origins and rebinding hosts', async () => {
expect((await fetch(`${base}/api/bootstrap`)).status).toBe(401);
expect((await fetch(base, { headers: { origin: 'https://attacker.example' } })).status).toBe(403);
expect((await fetch(base, { headers: { host: 'attacker.example' } })).status).toBe(403);
expect((await api('bootstrap', { headers: { origin: 'null' } })).status).toBe(200);
expect(
(
await fetch(`${base}/api/jobs`, { method: 'OPTIONS', headers: { origin: 'null' } })
).headers.get('access-control-allow-headers'),
).toContain('Authorization');
});
test('allows the native WebKit sandbox to connect only to the validated listener', async () => {
for (const host of [`127.0.0.1:${service.port}`, `localhost:${service.port}`]) {
const page = await fetch(base, { headers: { host } });
const policy = page.headers.get('content-security-policy')!;
expect(policy.split(';').map((part) => part.trim())).toContain(
`connect-src 'self' http://${host}`,
);
expect(policy).not.toContain('allow-same-origin');
}
const preflight = await fetch(`${base}/api/bootstrap`, {
method: 'OPTIONS',
headers: {
origin: 'null',
'access-control-request-method': 'GET',
'access-control-request-headers': 'authorization',
},
});
expect(preflight.status).toBe(204);
expect(preflight.headers.get('access-control-allow-origin')).toBe('null');
expect((await api('bootstrap', { headers: { origin: 'null' } })).status).toBe(200);
expect(
(await fetch(base, { headers: { host: 'attacker.example' } })).headers.has(
'content-security-policy',
),
).toBe(false);
});
test("names its own origins in every fetch directive, since a sandboxed page matches nothing to 'self' in WebKitGTK", async () => {
const directives = (policy: string) =>
new Map(
policy.split(';').map((part) => {
const [name, ...sources] = part.trim().split(/\s+/);
return [name, sources] as const;
}),
);
const proxy = 'https://magpie.example:9443';
for (const [host, query, want] of [
[`127.0.0.1:${service.port}`, '', [`http://127.0.0.1:${service.port}`]],
[`localhost:${service.port}`, '', [`http://localhost:${service.port}`]],
[
`127.0.0.1:${service.port}`,
`?uiOrigin=${encodeURIComponent(proxy)}`,
[`http://127.0.0.1:${service.port}`, proxy],
],
] as const) {
const page = await fetch(`${base}/${query}`, { headers: { host } });
const policy = directives(page.headers.get('content-security-policy')!);
for (const name of ['default-src', 'script-src', 'style-src', 'img-src', 'connect-src'])
for (const source of want) expect(policy.get(name)).toContain(source);
expect(policy.get('script-src')).not.toContain("'unsafe-inline'");
expect(policy.get('script-src')!.some((s) => s.startsWith("'nonce-"))).toBe(true);
}
});
test('serves the interface assets on every system, and nothing outside them', async () => {
const asset = await fetch(`${base}/assets/app.js`);
expect(asset.status).toBe(200);
expect(asset.headers.get('content-type')).toBe('text/javascript');
expect(await asset.text()).toBe('export {};');
for (const path of ['/assets/missing.js', '/%2e%2e/outside.txt', '/assets/%2e%2e/%2e%2e/outside.txt', '/..%5coutside.txt'])
expect((await fetch(`${base}${path}`)).status).toBe(404);
});
test('demo is explicitly identified; catalog and history never pretend to be measurements', async () => {
const boot = await (await api('bootstrap')).json();
expect(boot.demo).toBe(true);
expect(boot.models.length).toBeGreaterThan(0);
expect(boot.jobs.every((j: any) => j.demo === true)).toBe(true);
});
test('names the Magpie web proxy origin in sandbox CSP without accepting policy injection', async () => {
const proxy = 'https://magpie.example:9443';
const page = await fetch(`${base}/?uiOrigin=${encodeURIComponent(proxy)}`);
expect(page.headers.get('content-security-policy')).toContain(
`connect-src 'self' http://127.0.0.1:${service.port} ${proxy}`,
);
for (const invalid of [
'not-an-origin',
'http://*',
'https://*.example.com',
'https://example.com; script-src *',
'https://example.com/path',
'https://u:p@example.com',
'data:text/html,hello',
'https://example.com/?x=1',
]) {
expect((await fetch(`${base}/?uiOrigin=${encodeURIComponent(invalid)}`)).status).toBe(400);
}
expect((await api('bootstrap', { headers: { origin: proxy } })).status).toBe(403);
});
test('creates one batch, streams snapshots, cancels, exports and deletes it', async () => {
const config = {
targets: [{ model: 'openai/gpt-5.5' }],
api: 'auto',
effort: '',
serviceTier: 'default',
strict: false,
targetParallel: 1,
sampleParallel: 3,
deadlineSeconds: 10,
};
const created = await api('jobs', { method: 'POST', body: JSON.stringify(config) });
expect(created.status).toBe(202);
const job = await created.json();
expect((await api('jobs', { method: 'POST', body: JSON.stringify(config) })).status).toBe(409);
const events = await api(`jobs/${job.id}/events`);
expect(events.headers.get('content-type')).toContain('text/event-stream');
const reader = events.body!.getReader();
expect(new TextDecoder().decode((await reader.read()).value)).toContain('event: snapshot');
await reader.cancel();
expect((await api(`jobs/${job.id}/cancel`, { method: 'POST' })).status).toBe(200);
let finished: any;
for (let i = 0; i < 50; i++) {
finished = await (await api(`jobs/${job.id}`)).json();
if (finished.state === 'cancelled') break;
await Bun.sleep(30);
}
expect(finished.state).toBe('cancelled');
expect(finished.results[0].analysis).toBeNull();
const exported = await (await api(`jobs/${job.id}/export`)).json();
expect(exported.schema).toBe('magpie-fingerprint/v1');
expect(exported.demo).toBe(true);
expect((await api(`jobs/${job.id}`, { method: 'DELETE' })).status).toBe(200);
expect((await api(`jobs/${job.id}`)).status).toBe(404);
});
test('restart marks unfinished persisted tasks as interrupted and preserves original evidence', async () => {
const storeDir = join(dir, 'interrupted');
const a = new Store(storeDir);
await a.load();
const j = demoHistory();
j.id = 'unfinished';
j.state = 'running';
j.results[0].state = 'running';
await a.save(j);
const b = new Store(storeDir);
await b.load();
const recovered = b.jobs.get(j.id)!;
expect(recovered.state).toBe('interrupted');
expect(recovered.results[0].analysis).toBeNull();
expect(recovered.results[0].samples[0].raw_text).toBe(j.results[0].samples[0].raw_text);
});
test('validation fails before starting malformed jobs', async () => {
expect((await api('jobs', { method: 'POST', body: 'null' })).status).toBe(400);
expect(
(
await api('jobs', {
method: 'POST',
body: JSON.stringify({ targets: [{ model: 'unknown/model' }] }),
})
).status,
).toBe(400);
});
test('bounds chunked request bodies without trusting Content-Length', async () => {
const body = new ReadableStream({
start(out) {
out.enqueue(new TextEncoder().encode('x'.repeat(20000)));
out.close();
},
});
const response = await api('jobs', { method: 'POST', body });
expect(response.status).toBe(413);
});
test('a second host cannot repair jobs belonging to the active service', async () => {
const job = demoHistory();
job.id = 'active-owner-job';
job.state = 'running';
const path = join(dir, 'demo-jobs', `${job.id}.json`);
await writeFile(path, JSON.stringify(job));
try {
await expect(
startServer({ port: service.port, dataDir: dir, uiDir: join(dir, 'ui'), demo: true }),
).rejects.toThrow();
expect(JSON.parse(await readFile(path, 'utf8')).state).toBe('running');
} finally {
await rm(path, { force: true });
}
});