fingerprint 0.2.2: an account named 北冥 pins its samples, and the job file names the account (#615)
StockRabbit (#615): with the WorkBuddy account 北冥 picked, every sample failed with "Header 'X-Magpie-Account' has invalid value", since fetch refuses a header value that isn't ASCII. The saved job also didn't say which account it ran on. - gateway.ts: accountHeader() sends printable ASCII as it is and any other name percent-encoded; magpie v0.1.2658 (ad53a23dc) decodes it. The account list now names an account by its alias or user, not by the provider's display name. - detector.ts: a target's account resolves to the account's id (by id or a unique name for that model's provider), and the job keeps config.account / config.accountName and results[].target.account / accountName. Jobs written before 0.2.2 have neither and load unchanged. - web: the result card names the account. - integration.md: the header's encoding and a Job files section. Run (mote, sandbox HOME): bun install --frozen-lockfile, bun run typecheck, bun test (36 pass, 0 fail), bun run build, bun scripts/check.mjs (exit 0). tests/account.test.ts runs the server against a fake gateway whose quotas list 北冥: an 0.2.1 job loads unchanged, a run pinned to 北冥 reaches the gateway as %E5%8C%97%E5%86%A5 on every request, and the job file names 北冥. The page on mote in Chromium and WebKit at 420px against the same fake gateway: the picker shows "北冥 · workbuddy", 12 requests carry the encoded header, the card says 北冥. Broken by hand: accountHeader returning the raw name turns account.test red (no request reaches the gateway pinned). Not tried: a real WorkBuddy account, Windows, the page in a language other than English.
This commit is contained in:
Vendored
+8
-8
File diff suppressed because one or more lines are too long
Vendored
+7
-7
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
+1
-1
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#f7f7f5" />
|
||||
<title>Magpie · 模型指纹</title>
|
||||
<script type="module" crossorigin src="./assets/index-BguzqVWK.js"></script>
|
||||
<script type="module" crossorigin src="./assets/index-BzHYFND5.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="./assets/index-C9z1QhHD.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -39,14 +39,26 @@ upstream revision is documented in `THIRD_PARTY_NOTICES.md`.
|
||||
The service reads `GET /v1/models` for the text model catalog and
|
||||
`GET /v1/magpie/quotas?kept=1` for cached subscription account labels. The
|
||||
`kept=1` form does not ask vendors for a fresh quota reading. Account rows are
|
||||
projected to provider, user id, and display name only; upstream credentials,
|
||||
balances, and raw quota records are never sent to the browser.
|
||||
projected to provider, user id, and display name (the account's alias, else
|
||||
its user) only; upstream credentials, balances, and raw quota records are never
|
||||
sent to the browser.
|
||||
|
||||
Gateway authentication uses `Authorization: Bearer <key>` when an API key is
|
||||
configured. Loopback Magpie normally needs no key. A remote gateway must be
|
||||
shared and requires its enabled gateway key. `X-Magpie-Account` can pin a
|
||||
gateway request to one account id or signed-in user, but is only meaningful to
|
||||
Magpie and is never forwarded upstream.
|
||||
Magpie and is never forwarded upstream. A header value is ASCII, so a user that
|
||||
isn't (`北冥`) is sent percent-encoded (`encodeURIComponent`), which Magpie
|
||||
v0.1.2658 and later read back; an ASCII user is sent as it is.
|
||||
|
||||
## Job files
|
||||
|
||||
Each batch is saved as `jobs/<id>.json` under the data directory. A pinned
|
||||
target keeps `account` (Magpie's id for the account: its user, an email or a
|
||||
login, which routing matches and rests it by) and, when the catalog listed it,
|
||||
`accountName`, in `config.targets[]` and `results[].target`. When every target
|
||||
is pinned to the same account, `config.account` and `config.accountName` name
|
||||
it too. Jobs saved before 0.2.2 have none of these fields and load as they were.
|
||||
|
||||
## Local development
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/page-fingerprint",
|
||||
"version": "0.2.1",
|
||||
"version": "0.2.2",
|
||||
"description": "Check for suspected model substitution with numeric response fingerprints in Magpie, powered by lm-detector.",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
type DetectConfig,
|
||||
type Sample,
|
||||
} from '../vendor/lmfpd-sdk/index.js';
|
||||
import type { Api, Challenge, Job, Model, RunConfig, TargetResult } from './types.js';
|
||||
import type { Account, Api, Challenge, Job, Model, RunConfig, Target, TargetResult } from './types.js';
|
||||
|
||||
const APIS: Api[] = ['responses', 'chat_completions', 'messages'];
|
||||
const SDK_VERSION = '0.2.0';
|
||||
@@ -60,6 +60,11 @@ function validate(config: RunConfig, models: Model[]): void {
|
||||
if (!['default', 'flex', 'fast', 'ultrafast'].includes(config.serviceTier))
|
||||
fail('unknown service tier');
|
||||
if (!['auto', ...APIS].includes(config.api)) fail('unknown API');
|
||||
if (
|
||||
config.account !== undefined &&
|
||||
(typeof config.account !== 'string' || config.account.length > 256)
|
||||
)
|
||||
fail('account must be at most 256 characters');
|
||||
for (const target of config.targets) {
|
||||
if (typeof target.model !== 'string' || !target.model.trim()) fail('target model must be text');
|
||||
if (
|
||||
@@ -103,13 +108,55 @@ function queuedSample(challenge: Challenge): Sample {
|
||||
};
|
||||
}
|
||||
|
||||
export function createJob(config: RunConfig, models: Model[], builtAt: string): Job {
|
||||
/**
|
||||
* A target as the job keeps it: the account named (its own, else the
|
||||
* config's) as Magpie names it, by the catalog's id when the name matches
|
||||
* one of the model's provider's accounts by id or, alone, by its name, and
|
||||
* that account's name beside it.
|
||||
*/
|
||||
function pinned(target: Target, fallback: string | undefined, model: Model, accounts: Account[]) {
|
||||
const named = target.account || fallback;
|
||||
if (!named) return { model: target.model };
|
||||
const mine = accounts.filter((a) => a.provider === model.provider);
|
||||
const byName = mine.filter((a) => a.name === named);
|
||||
const hit =
|
||||
mine.find((a) => a.id.toLowerCase() === named.toLowerCase()) ??
|
||||
(byName.length === 1 ? byName[0] : undefined);
|
||||
return {
|
||||
model: target.model,
|
||||
account: hit?.id ?? named,
|
||||
...(hit ? { accountName: hit.name } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function createJob(
|
||||
config: RunConfig,
|
||||
models: Model[],
|
||||
builtAt: string,
|
||||
accounts: Account[] = [],
|
||||
): Job {
|
||||
validate(config, models);
|
||||
const targets: Target[] = config.targets.map((target) =>
|
||||
pinned(
|
||||
target,
|
||||
config.account,
|
||||
models.find((candidate) => candidate.id === target.model)!,
|
||||
accounts,
|
||||
),
|
||||
);
|
||||
const keys = targets.map((target) => `${target.model}\0${target.account ?? ''}`);
|
||||
if (new Set(keys).size !== keys.length) fail('duplicate targets are not allowed');
|
||||
// the account every target is pinned to, for a reader of the job file
|
||||
// that asks which seat it measured (plugins#615)
|
||||
const one =
|
||||
targets[0].account !== undefined && targets.every((t) => t.account === targets[0].account)
|
||||
? targets[0]
|
||||
: undefined;
|
||||
const normalizedConfig: RunConfig = {
|
||||
targets: config.targets.map((target) => ({
|
||||
model: target.model,
|
||||
...(target.account === undefined ? {} : { account: target.account }),
|
||||
})),
|
||||
targets,
|
||||
...(one
|
||||
? { account: one.account, ...(one.accountName ? { accountName: one.accountName } : {}) }
|
||||
: {}),
|
||||
api: config.api,
|
||||
effort: config.effort,
|
||||
serviceTier: config.serviceTier,
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import type { Account, Model, Provenance } from './types';
|
||||
import { boundedText } from './http';
|
||||
/**
|
||||
* X-Magpie-Account's value for an account. A header value is ASCII on the
|
||||
* wire and fetch refuses to send any other, so a name that isn't (北冥,
|
||||
* plugins#615) goes percent-encoded, which Magpie reads back decoded. An
|
||||
* ASCII name goes as it is, as every Magpie before that reads it.
|
||||
*/
|
||||
export function accountHeader(account: string) {
|
||||
return /^[\x20-\x7e]*$/.test(account) ? account : encodeURIComponent(account);
|
||||
}
|
||||
export class Gateway {
|
||||
constructor(
|
||||
readonly url: string,
|
||||
@@ -77,9 +86,10 @@ export class Gateway {
|
||||
(!item.kind || item.kind === 'subscription')
|
||||
) {
|
||||
if (!accounts.some((a) => a.provider === item.provider && a.id === item.user))
|
||||
// name is the provider's (WorkBuddy); alias is the account's own
|
||||
accounts.push({
|
||||
id: item.user,
|
||||
name: String(item.name || item.user),
|
||||
name: String(item.alias || item.user),
|
||||
provider: item.provider,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,14 +3,14 @@ import { readFile, mkdir, rename, unlink, access } from 'node:fs/promises';
|
||||
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';
|
||||
import { Gateway, accountHeader } from './gateway';
|
||||
import { Store } from './store';
|
||||
import { boundedText, BodyTooLargeError } from './http';
|
||||
import { normalizeChatStream } from './sse';
|
||||
import { serviceIdentity, VERSION } from './service-identity';
|
||||
import { createJob, runJob } from './detector';
|
||||
import { demoModels, demoHistory, demoAnalysis } from './demo';
|
||||
import type { Job, Model, Provenance, TargetResult, RunConfig } from './types';
|
||||
import type { Account, Job, Model, Provenance, TargetResult, RunConfig } from './types';
|
||||
|
||||
const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
||||
const json = (data: unknown, status = 200, headers: HeadersInit = {}) =>
|
||||
@@ -42,6 +42,7 @@ export async function startServer(input: Options = {}) {
|
||||
bankError = '',
|
||||
loading: Promise<Detector | undefined> | undefined;
|
||||
let models: Model[] = [],
|
||||
accounts: Account[] = [],
|
||||
catalogError = '';
|
||||
let closed = false,
|
||||
creatingJob = false;
|
||||
@@ -121,11 +122,13 @@ export async function startServer(input: Options = {}) {
|
||||
async function catalog() {
|
||||
if (opt.demo) {
|
||||
models = demoModels;
|
||||
return { models, accounts: [] };
|
||||
accounts = [];
|
||||
return { models, accounts };
|
||||
}
|
||||
try {
|
||||
const result = await gateway.catalog();
|
||||
models = result.models;
|
||||
accounts = result.accounts;
|
||||
catalogError = '';
|
||||
return result;
|
||||
} catch (e) {
|
||||
@@ -186,7 +189,9 @@ export async function startServer(input: Options = {}) {
|
||||
const startedAt = Date.now();
|
||||
const headers = gateway.headers({
|
||||
'X-Magpie-Session': provenance.session,
|
||||
...(result.target.account ? { 'X-Magpie-Account': result.target.account } : {}),
|
||||
...(result.target.account
|
||||
? { 'X-Magpie-Account': accountHeader(result.target.account) }
|
||||
: {}),
|
||||
});
|
||||
for (const name of ['anthropic-version', 'anthropic-beta', 'accept']) {
|
||||
const value = req.headers.get(name);
|
||||
@@ -506,7 +511,7 @@ export async function startServer(input: Options = {}) {
|
||||
const config = JSON.parse(text) as RunConfig;
|
||||
await catalog();
|
||||
// Reject malformed targets before allowing any reference download.
|
||||
const job = createJob(config, models, '');
|
||||
const job = createJob(config, models, '', accounts);
|
||||
const engine = await ensureDetector();
|
||||
if (!opt.demo && !engine)
|
||||
return json({ error: bankError || 'Reference data unavailable' }, 503, cors);
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
import { join, resolve } from 'node:path';
|
||||
import { options, type Options } from './config';
|
||||
|
||||
export const VERSION = '0.2.1';
|
||||
export const VERSION = '0.2.2';
|
||||
|
||||
// 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
|
||||
|
||||
@@ -14,10 +14,16 @@ export interface Account {
|
||||
}
|
||||
export interface Target {
|
||||
model: string;
|
||||
/** The account the samples are pinned to: Magpie's own name for it (its user, an email or a login), which routing rests and matches it by. */
|
||||
account?: string;
|
||||
/** Its name as the page listed it, when the catalog had it. */
|
||||
accountName?: string;
|
||||
}
|
||||
export interface RunConfig {
|
||||
targets: Target[];
|
||||
/** The account every target is pinned to, and its name; absent in jobs saved before 0.2.2 and when the targets differ. */
|
||||
account?: string;
|
||||
accountName?: string;
|
||||
api: Api | 'auto';
|
||||
effort: string;
|
||||
serviceTier: 'default' | 'flex' | 'fast' | 'ultrafast';
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { mkdtemp, mkdir, writeFile, readFile, rm, utimes } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { startServer } from '../src/server';
|
||||
import { cacheFixture } from './bank-fixture';
|
||||
|
||||
// StockRabbit's case (plugins#615): Magpie 0.1.2587, workbuddy's
|
||||
// deepseek-v4.1-flash, an account named 北冥 beside one named by its email.
|
||||
const MODEL = 'workbuddy/deepseek-v4.1-flash';
|
||||
const config = (account: string) => ({
|
||||
targets: [{ model: MODEL, account }],
|
||||
api: 'auto',
|
||||
effort: '',
|
||||
serviceTier: 'default',
|
||||
strict: true,
|
||||
targetParallel: 1,
|
||||
sampleParallel: 3,
|
||||
deadlineSeconds: 30,
|
||||
});
|
||||
// a job saved by 0.2.1, as the issue quotes it: no account anywhere
|
||||
const oldJob = {
|
||||
id: 'old-job-0-2-1',
|
||||
createdAt: '2026-11-01T00:00:00.000Z',
|
||||
finishedAt: '2026-11-01T00:01:00.000Z',
|
||||
state: 'completed',
|
||||
config: { ...config(''), targets: [{ model: MODEL }] },
|
||||
challenges: [],
|
||||
results: [
|
||||
{
|
||||
id: 'target-1',
|
||||
target: { model: MODEL },
|
||||
api: 'chat_completions',
|
||||
state: 'completed',
|
||||
samples: [],
|
||||
provenance: [],
|
||||
analysis: null,
|
||||
error: null,
|
||||
},
|
||||
],
|
||||
bank: { builtAt: 'test-snapshot', sdk: '0.2.0' },
|
||||
};
|
||||
|
||||
test('a run pinned to 北冥 reaches Magpie and its job file names the account', async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'fingerprint-account-test-'));
|
||||
const pins: string[] = [];
|
||||
const gateway = Bun.serve({
|
||||
hostname: '127.0.0.1',
|
||||
port: 0,
|
||||
fetch(req) {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === '/v1/models')
|
||||
return Response.json({
|
||||
data: [{ id: MODEL, native_endpoints: ['/v1/chat/completions'] }],
|
||||
});
|
||||
if (url.pathname === '/v1/magpie/quotas')
|
||||
return Response.json({
|
||||
data: [
|
||||
{ provider: 'workbuddy', name: 'WorkBuddy', kind: 'subscription', user: '北冥' },
|
||||
{
|
||||
provider: 'workbuddy',
|
||||
name: 'WorkBuddy',
|
||||
kind: 'subscription',
|
||||
user: 'csmlovenn@gmail.com',
|
||||
},
|
||||
],
|
||||
});
|
||||
if (req.method === 'POST' && url.pathname === '/v1/chat/completions') {
|
||||
pins.push(req.headers.get('x-magpie-account') || '');
|
||||
const chunk = (o: unknown) => `data: ${JSON.stringify(o)}\n\n`;
|
||||
return new Response(
|
||||
chunk({ choices: [{ delta: { content: '1, 2, 3' } }] }) +
|
||||
chunk({ choices: [{ delta: {}, finish_reason: 'stop' }] }) +
|
||||
'data: [DONE]\n\n',
|
||||
{ headers: { 'content-type': 'text/event-stream' } },
|
||||
);
|
||||
}
|
||||
return new Response('not here', { status: 404 });
|
||||
},
|
||||
});
|
||||
let service: Awaited<ReturnType<typeof startServer>> | undefined;
|
||||
try {
|
||||
await mkdir(join(dir, 'ui'));
|
||||
await writeFile(join(dir, 'ui/index.html'), '<head></head>');
|
||||
await writeFile(join(dir, 'reference.bin'), cacheFixture());
|
||||
await utimes(join(dir, 'reference.bin'), new Date(0), new Date(0));
|
||||
await mkdir(join(dir, 'jobs'));
|
||||
await writeFile(join(dir, 'jobs', `${oldJob.id}.json`), JSON.stringify(oldJob));
|
||||
service = await startServer({
|
||||
port: 0,
|
||||
dataDir: dir,
|
||||
uiDir: join(dir, 'ui'),
|
||||
gateway: `http://127.0.0.1:${gateway.port}`,
|
||||
apiKey: 'gateway-secret',
|
||||
bankSource: 'http://127.0.0.1:9/',
|
||||
demo: false,
|
||||
});
|
||||
const base = `http://127.0.0.1:${service.port}`;
|
||||
const html = await (await fetch(base)).text();
|
||||
const token = JSON.parse(html.match(/window\.__FINGERPRINT__=(.*?)<\/script>/)![1]).token;
|
||||
const api = (path: string, init: RequestInit = {}) =>
|
||||
fetch(`${base}/api/${path}`, {
|
||||
...init,
|
||||
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
||||
});
|
||||
|
||||
const boot = await (await api('bootstrap')).json();
|
||||
// the old job loads as it was saved
|
||||
expect(boot.jobs.map((j: { id: string }) => j.id)).toContain(oldJob.id);
|
||||
const old = boot.jobs.find((j: { id: string }) => j.id === oldJob.id);
|
||||
expect(old.config.account).toBeUndefined();
|
||||
expect(old.results[0].target).toEqual({ model: MODEL });
|
||||
// the account selector names the seat, not the provider
|
||||
expect(boot.accounts).toContainEqual({ provider: 'workbuddy', id: '北冥', name: '北冥' });
|
||||
|
||||
const created = await api('jobs', { method: 'POST', body: JSON.stringify(config('北冥')) });
|
||||
expect(created.status).toBe(202);
|
||||
const { id } = await created.json();
|
||||
let job: any;
|
||||
for (let i = 0; i < 500; i++) {
|
||||
job = await (await api(`jobs/${id}`)).json();
|
||||
if (!['queued', 'running'].includes(job.state)) break;
|
||||
await Bun.sleep(10);
|
||||
}
|
||||
// every sample reached Magpie, pinned to 北冥 percent-encoded
|
||||
expect(pins).toEqual(['%E5%8C%97%E5%86%A5', '%E5%8C%97%E5%86%A5', '%E5%8C%97%E5%86%A5']);
|
||||
expect(pins.map(decodeURIComponent)).toEqual(['北冥', '北冥', '北冥']);
|
||||
for (const sample of job.results[0].samples)
|
||||
expect(String(sample.error ?? '')).not.toMatch(/invalid value/i);
|
||||
await service.close();
|
||||
service = undefined;
|
||||
const saved = JSON.parse(await readFile(join(dir, 'jobs', `${id}.json`), 'utf8'));
|
||||
expect(saved.config.account).toBe('北冥');
|
||||
expect(saved.config.accountName).toBe('北冥');
|
||||
expect(saved.config.targets[0]).toEqual({ model: MODEL, account: '北冥', accountName: '北冥' });
|
||||
expect(saved.results[0].target).toEqual({ model: MODEL, account: '北冥', accountName: '北冥' });
|
||||
} finally {
|
||||
await service?.close();
|
||||
gateway.stop(true);
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
// An empty, internally consistent SDK reference fixture, never used for scoring.
|
||||
export function cacheFixture() {
|
||||
const detector = Buffer.from(
|
||||
JSON.stringify({
|
||||
schema: 'shared-detector-v2',
|
||||
bank_built_at: 'test-snapshot',
|
||||
model_ids: [],
|
||||
response_counts: [],
|
||||
}),
|
||||
);
|
||||
const detectorHeader = Buffer.alloc(Math.ceil((4 + detector.length) / 4) * 4);
|
||||
detectorHeader.writeUInt32LE(detector.length);
|
||||
detector.copy(detectorHeader, 4);
|
||||
const bank = Buffer.from(
|
||||
JSON.stringify({
|
||||
schema: 'lmfpd-data-v1',
|
||||
detector_schema: 'shared-detector-v2',
|
||||
built_at: 'test-snapshot',
|
||||
models: [],
|
||||
files: {
|
||||
'shared_detector.bin': {
|
||||
sha256: createHash('sha256').update(detectorHeader).digest('hex'),
|
||||
parts: ['fixture.zst'],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const length = Buffer.alloc(4);
|
||||
length.writeUInt32LE(bank.length);
|
||||
return Buffer.concat([length, bank, detectorHeader]);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtemp, mkdir, writeFile, utimes, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { startServer } from '../src/server';
|
||||
import { cacheFixture } from './bank-fixture';
|
||||
|
||||
const config = {
|
||||
targets: [{ model: 'vendor/model' }],
|
||||
@@ -16,38 +16,6 @@ const config = {
|
||||
deadlineSeconds: 10,
|
||||
};
|
||||
|
||||
// An empty, internally consistent SDK reference fixture, never used for scoring.
|
||||
function cacheFixture() {
|
||||
const detector = Buffer.from(
|
||||
JSON.stringify({
|
||||
schema: 'shared-detector-v2',
|
||||
bank_built_at: 'test-snapshot',
|
||||
model_ids: [],
|
||||
response_counts: [],
|
||||
}),
|
||||
);
|
||||
const detectorHeader = Buffer.alloc(Math.ceil((4 + detector.length) / 4) * 4);
|
||||
detectorHeader.writeUInt32LE(detector.length);
|
||||
detector.copy(detectorHeader, 4);
|
||||
const bank = Buffer.from(
|
||||
JSON.stringify({
|
||||
schema: 'lmfpd-data-v1',
|
||||
detector_schema: 'shared-detector-v2',
|
||||
built_at: 'test-snapshot',
|
||||
models: [],
|
||||
files: {
|
||||
'shared_detector.bin': {
|
||||
sha256: createHash('sha256').update(detectorHeader).digest('hex'),
|
||||
parts: ['fixture.zst'],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const length = Buffer.alloc(4);
|
||||
length.writeUInt32LE(bank.length);
|
||||
return Buffer.concat([length, bank, detectorHeader]);
|
||||
}
|
||||
|
||||
async function fixture(cached = false, downloadable = false) {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'fingerprint-bank-test-'));
|
||||
const downloads: Request[] = [];
|
||||
|
||||
@@ -44,6 +44,56 @@ describe('detector jobs', () => {
|
||||
);
|
||||
});
|
||||
|
||||
// StockRabbit's job files (plugins#615) say which seat a run measured
|
||||
test('records the pinned account and its name in the config and each result', () => {
|
||||
const wb: Model = { ...model, id: 'workbuddy/deepseek-v4.1-flash', provider: 'workbuddy' };
|
||||
const accounts = [
|
||||
{ provider: 'workbuddy', id: '北冥', name: '北冥' },
|
||||
{ provider: 'workbuddy', id: 'csmlovenn@gmail.com', name: 'Main seat' },
|
||||
{ provider: 'other', id: 'elsewhere', name: '北冥' },
|
||||
];
|
||||
const one = { ...config, targets: [{ model: wb.id, account: '北冥' }] };
|
||||
const job = createJob(one, [wb], 'b', accounts);
|
||||
expect(job.config.account).toBe('北冥');
|
||||
expect(job.config.accountName).toBe('北冥');
|
||||
expect(job.results[0].target).toEqual({ model: wb.id, account: '北冥', accountName: '北冥' });
|
||||
// named by its alias, the job keeps the id Magpie pins by
|
||||
const byName = createJob(
|
||||
{ ...config, targets: [{ model: wb.id, account: 'Main seat' }] },
|
||||
[wb],
|
||||
'b',
|
||||
accounts,
|
||||
);
|
||||
expect(byName.results[0].target).toEqual({
|
||||
model: wb.id,
|
||||
account: 'csmlovenn@gmail.com',
|
||||
accountName: 'Main seat',
|
||||
});
|
||||
expect(byName.config.account).toBe('csmlovenn@gmail.com');
|
||||
// config.account pins every target that names none
|
||||
const shared = createJob(
|
||||
{ ...config, account: 'CSMLOVENN@gmail.com', targets: [{ model: wb.id }] },
|
||||
[wb],
|
||||
'b',
|
||||
accounts,
|
||||
);
|
||||
expect(shared.results[0].target.account).toBe('csmlovenn@gmail.com');
|
||||
// one the catalog doesn't list is kept as named, with no name made up
|
||||
const unknown = createJob(
|
||||
{ ...config, targets: [{ model: wb.id, account: '南海' }] },
|
||||
[wb],
|
||||
'b',
|
||||
accounts,
|
||||
);
|
||||
expect(unknown.results[0].target).toEqual({ model: wb.id, account: '南海' });
|
||||
expect(unknown.config.account).toBe('南海');
|
||||
expect(unknown.config.accountName).toBeUndefined();
|
||||
// targets on different accounts (or none) leave config.account out
|
||||
const mixed = createJob(config, [model], 'b', []);
|
||||
expect(mixed.config.account).toBeUndefined();
|
||||
expect(mixed.results[1].target.account).toBe('a');
|
||||
});
|
||||
|
||||
test('uses per-sample endpoint and scores injected samples', async () => {
|
||||
const job = createJob({ ...config, targets: [{ model: 'm1' }] }, [model], 'build');
|
||||
const indexes: number[] = [];
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { Gateway } from '../src/gateway';
|
||||
import { Gateway, accountHeader } from '../src/gateway';
|
||||
|
||||
test('catalog reads cached local and remote subscription accounts without leaking quota data', async () => {
|
||||
const paths: string[] = [];
|
||||
@@ -17,14 +17,15 @@ test('catalog reads cached local and remote subscription accounts without leakin
|
||||
{
|
||||
provider: 'vendor',
|
||||
user: 'local-account',
|
||||
name: 'Local',
|
||||
name: 'Vendor',
|
||||
alias: 'Local',
|
||||
balance: '$42',
|
||||
secret: 'excluded',
|
||||
},
|
||||
{
|
||||
provider: 'vendor',
|
||||
user: 'remote-account',
|
||||
name: 'Remote',
|
||||
name: 'Vendor',
|
||||
kind: 'subscription',
|
||||
},
|
||||
{ provider: 'vendor', user: 'key-card', name: 'Key', kind: 'balance' },
|
||||
@@ -39,9 +40,40 @@ test('catalog reads cached local and remote subscription accounts without leakin
|
||||
expect(paths).toContain('/v1/magpie/quotas?kept=1');
|
||||
expect(accounts).toEqual([
|
||||
{ provider: 'vendor', id: 'local-account', name: 'Local' },
|
||||
{ provider: 'vendor', id: 'remote-account', name: 'Remote' },
|
||||
// name is the provider's; an account with no alias is named by its user
|
||||
{ provider: 'vendor', id: 'remote-account', name: 'remote-account' },
|
||||
]);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
// fetch refuses a header value that isn't ASCII (StockRabbit's 北冥,
|
||||
// plugins#615): such a name goes percent-encoded, an ASCII one as it is
|
||||
test('X-Magpie-Account carries a name that is not ASCII percent-encoded', async () => {
|
||||
expect(accountHeader('北冥')).toBe('%E5%8C%97%E5%86%A5');
|
||||
expect(decodeURIComponent(accountHeader('北冥'))).toBe('北冥');
|
||||
expect(accountHeader('csmlovenn@gmail.com')).toBe('csmlovenn@gmail.com');
|
||||
const seen: string[] = [];
|
||||
const server = Bun.serve({
|
||||
hostname: '127.0.0.1',
|
||||
port: 0,
|
||||
fetch(req) {
|
||||
seen.push(req.headers.get('x-magpie-account') || '');
|
||||
return new Response('ok');
|
||||
},
|
||||
});
|
||||
try {
|
||||
const url = `http://127.0.0.1:${server.port}/`;
|
||||
// the reporter's error, raw
|
||||
const raw = await (async () => fetch(url, { headers: { 'X-Magpie-Account': '北冥' } }))().then(
|
||||
() => '',
|
||||
(e) => String(e),
|
||||
);
|
||||
expect(raw).toMatch(/invalid/i);
|
||||
await fetch(url, { headers: { 'X-Magpie-Account': accountHeader('北冥') } });
|
||||
expect(seen).toEqual(['%E5%8C%97%E5%86%A5']);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1169,6 +1169,7 @@ function ResultRow({
|
||||
<span className="result-model">
|
||||
<strong>{r.target.model}</strong>
|
||||
<small>
|
||||
{r.target.account ? `${r.target.accountName || r.target.account} · ` : ''}
|
||||
{r.api} · {stateLabel(t, r.state)}
|
||||
</small>
|
||||
</span>
|
||||
|
||||
Reference in New Issue
Block a user