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.
This commit is contained in:
yetone
2026-11-01 00:08:40 +08:00
parent 5b1ae40256
commit e7dfe88218
9 changed files with 97 additions and 29 deletions
+8 -8
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+5 -3
View File
@@ -14,9 +14,11 @@ desktop window it is reached at `http://127.0.0.1:<port>`; in `magpie web`,
Magpie supplies `magpie.service`, a tokenized reverse-proxy URL. The service
does not expose the gateway listener. Its authenticated API accepts its local
page and the opaque `Origin: null` used by Magpie's sandbox, and rejects unrelated origins.
The page CSP explicitly allows connections to the validated local listener and,
when proxied, the HTTP(S) origin supplied by the page launcher. Opaque sandbox
frames cannot reliably match `connect-src 'self'`. The launcher origin changes
The page CSP names the validated local listener and, when proxied, the HTTP(S)
origin supplied by the page launcher in every fetch directive (default, script,
style, image and connect). Opaque sandbox frames cannot reliably match `'self'`:
WebKitGTK, magpie's Linux window, matches nothing to it there, so a policy of
`'self'` alone loads no script and the page stays blank. The launcher origin changes
only the document policy; the API bearer token and Host/Origin checks still apply.
## UI integration
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-fingerprint",
"version": "0.2.0",
"version": "0.2.1",
"description": "Check for suspected model substitution with numeric response fingerprints in Magpie, powered by lm-detector.",
"type": "module",
"license": "MIT",
+10 -1
View File
@@ -68,8 +68,17 @@
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(text.invalidPort);
let service = window.magpie?.service;
if (!service) {
// This computer's window: wails://localhost on macOS and Linux,
// http://wails.localhost on Windows (Wails v3, WebView2).
const host = String(location.hostname || '')
.toLowerCase()
.replace(/^\[|\]$/g, '');
const local =
!location.hostname || ['localhost', '127.0.0.1', '::1'].includes(location.hostname);
!host ||
host === 'localhost' ||
host.endsWith('.localhost') ||
host === '::1' ||
/^127\./.test(host);
if (!local) {
status.textContent = text.remote;
return;
+13 -5
View File
@@ -1,6 +1,6 @@
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { readFile, mkdir, rename, unlink, access } from 'node:fs/promises';
import { join, resolve, extname } from 'node:path';
import { join, resolve, relative, isAbsolute, extname } from 'node:path';
import { loadDetector, parseNumbers, type Detector } from '../vendor/lmfpd-sdk/index.js';
import { options, type Options } from './config';
import { Gateway } from './gateway';
@@ -642,9 +642,14 @@ export async function startServer(input: Options = {}) {
)
throw new Error('Invalid UI origin.');
}
const connectSources = [
// This document's own origins, named: in magpie's frame the
// document is sandboxed to an opaque origin, and WebKitGTK
// (magpie's Linux window) then matches nothing to 'self', so
// a policy of 'self' alone loads no script, style or image
// there and the page stays blank.
const ownSources = [
...new Set([`http://${host}`, ...(uiOrigin ? [uiOrigin] : [])]),
];
].join(' ');
let html = await readFile(join(uiDir, 'index.html'), 'utf8').catch(
() =>
'<!doctype html><title>Build required</title><p>Run bun run build to create the Fingerprint interface.</p>',
@@ -669,13 +674,16 @@ export async function startServer(input: Options = {}) {
// Opaque sandbox origins cannot reliably match 'self'. The
// launcher supplies the HTTP(S) origin of Magpie's proxy;
// it affects this document's CSP only, never API admission.
'content-security-policy': `default-src 'self'; connect-src 'self' ${connectSources.join(' ')}; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; object-src 'none'; base-uri 'none'; form-action 'none'`,
'content-security-policy': `default-src 'self' ${ownSources}; connect-src 'self' ${ownSources}; script-src 'self' ${ownSources} 'nonce-${nonce}'; style-src 'self' ${ownSources} 'unsafe-inline'; img-src 'self' ${ownSources} data:; object-src 'none'; base-uri 'none'; form-action 'none'`,
},
});
}
const decoded = decodeURIComponent(url.pathname);
const file = resolve(uiDir, `.${decoded}`);
if (!file.startsWith(`${resolve(uiDir)}/`) || decoded.includes('..'))
// inside uiDir by the system's own separator: on Windows resolve
// gives back slashes, and a check for "/" refused every asset
const inside = relative(resolve(uiDir), file);
if (!inside || inside.startsWith('..') || isAbsolute(inside) || decoded.includes('..'))
return new Response('Not found', { status: 404 });
const asset = Bun.file(file);
if (!(await asset.exists())) return new Response('Not found', { status: 404 });
+1 -1
View File
@@ -13,7 +13,7 @@ import {
import { join, resolve } from 'node:path';
import { options, type Options } from './config';
export const VERSION = '0.2.0';
export const VERSION = '0.2.1';
// The health endpoint is public, so the configuration digest must not be a
// plain hash of a low-entropy gateway key. Keep the salt beside the install's
+15 -3
View File
@@ -3,7 +3,7 @@ import { readFile } from 'node:fs/promises';
import { runInNewContext } from 'node:vm';
const source = await readFile(new URL('../page/boot.js', import.meta.url), 'utf8');
async function boot(lang?: string, remote = false, port = 3488) {
async function boot(lang?: string, remote = false, port = 3488, desktopHost = '') {
const elements = {
status: { textContent: 'Connecting to Fingerprint…' },
title: { textContent: 'Fingerprint' },
@@ -14,7 +14,8 @@ async function boot(lang?: string, remote = false, port = 3488) {
getElementById: (id: keyof typeof elements) => elements[id],
};
let destination: URL | undefined;
const service = remote ? '' : 'http://127.0.0.1:3488/';
// magpie hands no service to its desktop window, only to magpie web
const service = remote || desktopHost ? '' : 'http://127.0.0.1:3488/';
await runInNewContext(source, {
URL,
document,
@@ -29,7 +30,7 @@ async function boot(lang?: string, remote = false, port = 3488) {
},
},
location: {
hostname: remote ? 'magpie.example' : '127.0.0.1',
hostname: desktopHost || (remote ? 'magpie.example' : '127.0.0.1'),
href: 'http://127.0.0.1/boot/index.html',
replace: (url: string) => {
destination = new URL(url);
@@ -67,3 +68,14 @@ test('boot localizes remote-service guidance and invalid-port errors', async ()
expect(invalid.destination).toBeUndefined();
expect(invalid.elements.status.textContent).toContain('Ungültiger Port');
});
test("boot goes to the local service from magpie's desktop window on every system", async () => {
// Wails v3: wails://localhost on macOS and Linux, http://wails.localhost
// on Windows (WebView2), where the page said "upgrade Magpie" instead
for (const host of ['localhost', 'wails.localhost', '[::1]', '127.0.0.1']) {
const result = await boot('zh-CN', false, 3490, host);
expect(result.destination?.origin).toBe('http://127.0.0.1:3490');
expect(result.destination?.searchParams.get('uiOrigin')).toBe('http://127.0.0.1:3490');
expect(result.elements.status.textContent).not.toContain('升级');
}
});
+37
View File
@@ -19,6 +19,9 @@ 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();
@@ -65,6 +68,40 @@ test('allows the native WebKit sandbox to connect only to the validated listener
),
).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);