release: Lynceuz v0.1 — public web evidence at zero cost, or an honest stop

This commit is contained in:
public-repo-gate
2026-08-31 22:21:33 +03:00
parent b4431b420c
commit 61a7f0d116
97 changed files with 22291 additions and 1 deletions
View File
+526
View File
@@ -0,0 +1,526 @@
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { createPlaywrightAdapter } from '../src/adapters/playwright.mjs';
import {
REQUIRED_BROWSER_PROOF_CHANNELS,
browserCapabilityState,
createChildEgressSandbox,
verifyBrowserSecurityProof,
} from '../src/browser-security.mjs';
import {
CANARY_PROTOCOLS,
createContainmentCanaryHarness,
probeContainmentCanary,
} from './fixtures/pf-containment-canary.mjs';
const NOW_MS = Date.parse('2026-08-30T12:00:00.000Z');
const HASH_A = `sha256:${'a'.repeat(64)}`;
const HASH_B = `sha256:${'b'.repeat(64)}`;
const HASH_C = `sha256:${'c'.repeat(64)}`;
const SAFE_PF_RULES = [
'pass quick on lo0 inet proto tcp from any user 401 to 127.0.0.1 port 48191',
'block drop quick inet from any user 401 to any',
'block drop quick inet6 from any user 401 to any',
].join('\n');
function result(channel, operationSucceeded, response) {
return Object.freeze({
channel,
operation_succeeded: operationSucceeded,
response,
response_confirmed: response === CANARY_PROTOCOLS[channel].response,
});
}
function passedCanary() {
return Object.freeze({
passed: true,
status: 'passed',
reason: 'containment_canary_passed',
exit_code: 0,
detected_channels: Object.freeze([]),
observations: Object.freeze({
proxy_tcp: result('proxy_tcp', true, CANARY_PROTOCOLS.proxy_tcp.response),
direct_tcp: result('direct_tcp', false, null),
udp: result('udp', true, null),
quic: result('quic', true, null),
}),
});
}
function expectedContainment() {
return Object.freeze({
backend: 'pf_uid_anchor_guardproxy',
uid_name: '_lynceuz',
uid: 401,
gid: 401,
guard_proxy_host: '127.0.0.1',
guard_proxy_port: 48191,
anchor_name: 'com.lynceuz/browser',
anchor_path: '/etc/pf.anchors/com.lynceuz.browser',
anchor_sha256: HASH_A,
rules_sha256: HASH_B,
source_hashes: Object.freeze({ macos_containment: HASH_C, canary: HASH_A }),
suite_hashes: Object.freeze({ wave2: HASH_B }),
});
}
function systemFacts(overrides = {}) {
const base = {
uid: { name: '_lynceuz', uid: 401, gid: 401, dedicated: true },
pf: {
active: true,
anchor_name: 'com.lynceuz/browser',
anchor_path: '/etc/pf.anchors/com.lynceuz.browser',
anchor_sha256: HASH_A,
rules_sha256: HASH_B,
rules_text: SAFE_PF_RULES,
},
boot_session: 'boot-session-2026-08-30',
};
return {
...base,
...overrides,
uid: { ...base.uid, ...overrides.uid },
pf: { ...base.pf, ...overrides.pf },
};
}
function validReceipt(overrides = {}) {
const expected = expectedContainment();
const base = {
kind: 'lynceuz_macos_containment_receipt',
schema_version: 1,
status: 'ready',
backend: expected.backend,
generated_at: new Date(NOW_MS - 60_000).toISOString(),
uid: { name: expected.uid_name, uid: expected.uid, gid: expected.gid },
guard_proxy: { host: expected.guard_proxy_host, port: expected.guard_proxy_port },
pf: {
anchor_name: expected.anchor_name,
anchor_path: expected.anchor_path,
anchor_sha256: expected.anchor_sha256,
rules_sha256: expected.rules_sha256,
},
source_hashes: expected.source_hashes,
suite_hashes: expected.suite_hashes,
boot_session: 'boot-session-2026-08-30',
reboot_verified: true,
reboot_verified_at: new Date(NOW_MS - 120_000).toISOString(),
canary: passedCanary(),
};
return {
...base,
...overrides,
uid: { ...base.uid, ...overrides.uid },
guard_proxy: { ...base.guard_proxy, ...overrides.guard_proxy },
pf: { ...base.pf, ...overrides.pf },
};
}
test('Darwin sandbox containment stays closed with the concrete scope reason', async (t) => {
const workspace = await mkdtemp(join(tmpdir(), 'lynceuz-sandbox-contract-'));
t.after(() => rm(workspace, { recursive: true, force: true }));
const sandboxPath = join(workspace, 'sandbox-exec');
await writeFile(sandboxPath, 'fixture');
const containment = await createChildEgressSandbox({
proxyPort: 48191,
platformName: 'darwin',
sandboxPath,
});
assert.equal(containment.state, 'unavailable_security_gate');
assert.equal(containment.proofEligible, false);
assert.equal(containment.reason, 'sandbox_loopback_scope_unproven');
assert.notEqual(containment.state, 'ready');
});
test('browserCapabilityState rejects missing browser proof and keeps all hostile channels', async (t) => {
const workspace = await mkdtemp(join(tmpdir(), 'lynceuz-wave2-proof-'));
t.after(() => rm(workspace, { recursive: true, force: true }));
const dataRoot = join(workspace, '.lynceuz');
await mkdir(dataRoot, { recursive: true });
const proof = await verifyBrowserSecurityProof({
dataRoot,
fingerprint: { digest: HASH_A },
now: () => NOW_MS,
});
assert.deepEqual(proof, { valid: false, reason: 'proof_missing', fingerprint: null });
assert.equal(browserCapabilityState({
id: 'playwright', installed: true, version: 'fixture', allowRendered: true, proof,
}).state, 'unavailable_security_gate');
assert.ok(REQUIRED_BROWSER_PROOF_CHANNELS.includes('webrtc_udp'), 'UDP proof channel');
assert.ok(REQUIRED_BROWSER_PROOF_CHANNELS.includes('quic'), 'QUIC proof channel');
});
test('containment receipt rejects missing stale tampered and reboot-unverified evidence', async () => {
const { verifyMacosContainmentReceipt } = await import('../src/macos-containment.mjs');
const verify = (receipt, options = {}) => verifyMacosContainmentReceipt({
receipt,
expected: expectedContainment(),
system: options.system ?? systemFacts(),
canary: options.canary === undefined ? passedCanary() : options.canary,
now: () => NOW_MS,
maxAgeMs: 5 * 60_000,
});
const unavailable = async (receipt, reason, options) => {
const verdict = await verify(receipt, options);
assert.equal(verdict.state, 'unavailable_security_gate', reason);
assert.equal(verdict.reason, reason);
assert.notEqual(verdict.state, 'ready');
};
await unavailable(undefined, 'containment_receipt_missing');
await unavailable(validReceipt({ generated_at: '2020-01-01T00:00:00.000Z' }), 'containment_receipt_stale');
await unavailable(validReceipt({ pf: { rules_sha256: HASH_C } }), 'containment_receipt_tampered');
await unavailable(validReceipt({ reboot_verified: false }), 'containment_reboot_unverified');
await unavailable(validReceipt({ boot_session: 'previous-boot-session' }), 'containment_boot_session_mismatch');
await unavailable(validReceipt(), 'containment_anchor_inactive', {
system: systemFacts({ pf: { active: false } }),
});
await unavailable(validReceipt(), 'containment_uid_not_dedicated', {
system: systemFacts({ uid: { dedicated: false } }),
});
await unavailable(validReceipt(), 'containment_pf_rules_unsafe', {
system: systemFacts({ pf: { rules_text: `set skip on lo0\n${SAFE_PF_RULES}` } }),
});
await unavailable(validReceipt(), 'containment_pf_rules_unsafe', {
system: systemFacts({ pf: { rules_text: `${SAFE_PF_RULES}\npass quick from any to any` } }),
});
await unavailable(validReceipt(), 'containment_canary_missing', { canary: null });
await unavailable(validReceipt(), 'containment_canary_failed', {
canary: { ...passedCanary(), passed: false, status: 'red', exit_code: 1 },
});
const ready = await verify(validReceipt());
assert.equal(ready.state, 'ready');
assert.equal(ready.reason, 'containment_ready');
assert.equal(systemFacts().pf.active, true, 'active anchor required');
assert.equal(systemFacts().uid.dedicated, true, 'dedicated UID required');
});
test('containment accepts real pfctl output', async () => {
const { safeRules } = await import('../src/macos-containment.mjs');
const expected = expectedContainment();
const real = await readFile(new URL('./fixtures/pf-real-rules.txt', import.meta.url), 'utf8');
assert.equal(safeRules(real, expected), true, 'real pfctl output is accepted');
const withoutInet6 = real.split('\n').filter(Boolean)
.filter((line) => !/\binet6\b/u.test(line)).join('\n');
assert.equal(safeRules(withoutInet6, expected), false, 'a set without the inet6 block is rejected');
assert.equal(safeRules(`set skip on lo0\n${real}`, expected), false, 'set skip on lo0 makes the set unsafe');
const broadPass = real.replace('to 127.0.0.1', 'to any');
assert.notEqual(broadPass, real, 'broad-pass mutation applied');
assert.equal(safeRules(broadPass, expected), false, 'a pass to any address is rejected');
});
test('positive канарейка allows proxy TCP and confirms no direct TCP UDP or QUIC response', async () => {
const tcpExchange = async (channel) => channel === 'proxy_tcp'
? result(channel, true, CANARY_PROTOCOLS[channel].response)
: result(channel, true, null);
const udpExchange = async (channel) => result(channel, true, null);
const verdict = await probeContainmentCanary({
endpoints: {
proxy_tcp: {}, direct_tcp: {}, udp: {}, quic: {},
},
tcpExchange,
udpExchange,
});
assert.equal(verdict.passed, true);
assert.equal(verdict.exit_code, 0);
assert.equal(verdict.observations.proxy_tcp.response_confirmed, true);
assert.equal(verdict.observations.direct_tcp.response_confirmed, false);
assert.equal(verdict.observations.udp.operation_succeeded, true, 'UDP send may succeed');
assert.equal(verdict.observations.udp.response_confirmed, false, 'UDP requires a response');
assert.equal(verdict.observations.quic.operation_succeeded, true, 'QUIC-like UDP send may succeed');
assert.equal(verdict.observations.quic.response_confirmed, false, 'QUIC requires a response');
});
test('negative control without containment detects every local non-loopback channel and turns red', async (t) => {
const harness = await createContainmentCanaryHarness();
t.after(() => harness.close());
assert.notEqual(harness.non_loopback_host, '127.0.0.1');
assert.equal(harness.endpoints.proxy_tcp.host, '127.0.0.1');
for (const channel of ['direct_tcp', 'udp', 'quic']) {
assert.equal(harness.endpoints[channel].host, harness.non_loopback_host, channel);
}
const verdict = await probeContainmentCanary({
endpoints: harness.endpoints,
negativeControl: true,
timeoutMs: 1_000,
});
assert.equal(verdict.passed, false);
assert.equal(verdict.status, 'red');
assert.equal(verdict.exit_code, 1);
assert.equal(verdict.reason, 'containment_removed_channels_reachable');
assert.deepEqual(verdict.detected_channels, ['direct_tcp', 'udp', 'quic']);
for (const channel of verdict.detected_channels) {
assert.equal(verdict.observations[channel].response_confirmed, true, channel);
}
});
test('negative control does not confuse successful UDP sends with responses', async () => {
const sendOnly = async (channel) => result(channel, true, null);
const verdict = await probeContainmentCanary({
endpoints: {
proxy_tcp: {}, direct_tcp: {}, udp: {}, quic: {},
},
negativeControl: true,
tcpExchange: sendOnly,
udpExchange: sendOnly,
});
assert.equal(verdict.passed, false);
assert.equal(verdict.status, 'invalid_negative_control');
assert.equal(verdict.exit_code, 2);
assert.deepEqual(verdict.detected_channels, []);
});
test('containment PF anchor template permits only UID-scoped proxy TCP and blocks all other egress', async () => {
const anchor = await readFile(new URL('../ops/macos/pf/lynceuz-browser.anchor.conf.in', import.meta.url), 'utf8');
assert.doesNotMatch(anchor, /^\s*set\s+skip\s+on\s+lo0\b/imu);
const passLines = anchor.split('\n').filter((line) => /^\s*pass\b/u.test(line));
assert.equal(passLines.length, 1, 'one pass rule only');
const pass = /^\s*pass\s+out\s+quick\s+inet\s+proto\s+tcp\s+from\s+any\s+to\s+127\.0\.0\.1\s+port\s+48191\s+user\s+(\S+)\s*$/u.exec(passLines[0]);
assert.ok(pass, 'dedicated UID may use only proxy TCP on 127.0.0.1:48191');
assert.match(pass[1], /UID/u, 'template substitutes only the numeric UID');
const uid = pass[1].replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
assert.match(anchor, new RegExp(`^\\s*block\\s+drop\\s+out\\s+quick\\s+inet\\s+from\\s+any\\s+to\\s+any\\s+user\\s+${uid}\\s*$`, 'mu'));
assert.match(anchor, new RegExp(`^\\s*block\\s+drop\\s+out\\s+quick\\s+inet6\\s+from\\s+any\\s+to\\s+any\\s+user\\s+${uid}\\s*$`, 'mu'));
assert.doesNotMatch(passLines[0], /\b(?:inet6|udp|quic)\b/iu, 'no IPv6, UDP or QUIC pass');
const tempDirectory = await mkdtemp(join(tmpdir(), 'lynceuz-pf-anchor-'));
try {
const parsedAnchorPath = join(tempDirectory, 'anchor.conf');
await writeFile(parsedAnchorPath, anchor.replaceAll(pass[1], '401'), { mode: 0o600 });
const parsed = spawnSync('/sbin/pfctl', ['-n', '-f', parsedAnchorPath], {
encoding: 'utf8',
shell: false,
timeout: 5_000,
});
assert.equal(parsed.status, 0);
} finally {
await rm(tempDirectory, { recursive: true, force: true });
}
});
test('containment owner templates are syntactically valid and least-privilege', async () => {
const paths = {
installer: fileURLToPath(new URL('../ops/macos/install-containment.sh', import.meta.url)),
launchd: fileURLToPath(new URL('../ops/macos/launchd/com.lynceuz.browser-containment.plist', import.meta.url)),
sudoers: fileURLToPath(new URL('../ops/macos/sudoers/lynceuz-browser', import.meta.url)),
};
const [installer, launchd, sudoers] = await Promise.all(
Object.values(paths).map((path) => readFile(path, 'utf8')),
);
for (const [command, args] of [
['/bin/sh', ['-n', paths.installer]],
['/usr/bin/plutil', ['-lint', paths.launchd]],
['/usr/sbin/visudo', ['-cf', paths.sudoers]],
]) {
const checked = spawnSync(command, args, { encoding: 'utf8', shell: false, timeout: 5_000 });
assert.equal(checked.status, 0, checked.stderr || checked.stdout);
}
for (const flag of ['--dry-run', '--apply', '--rollback']) assert.ok(installer.includes(flag), flag);
for (const fixed of ['_lynceuz', 'com.lynceuz/browser', '/etc/pf.anchors/com.lynceuz.browser']) {
assert.ok(`${installer}\n${launchd}\n${sudoers}`.includes(fixed), fixed);
}
assert.match(installer, /\bid\s+-u\b/u, 'apply and rollback require an existing root shell');
assert.doesNotMatch(installer, /\b(?:sudo|doas)\b/u, 'template must not elevate itself');
assert.match(launchd, /<key>RunAtLoad<\/key>\s*<true\/>/u);
assert.doesNotMatch(launchd, /\/(?:ba|z|c)?sh\b/u, 'launchd uses fixed argv, not a shell');
assert.match(sudoers, /\/sbin\/pfctl\b/u);
assert.doesNotMatch(sudoers, /NOPASSWD:\s*ALL\b|\(\s*ALL(?::ALL)?\s*\)|\*|\/(?:ba|z|c)?sh\b/u);
});
test('containment launcher requires a proven fixed-argv plan before Playwright supervisor spawn', async () => {
const adapterSource = await readFile(new URL('../src/adapters/playwright.mjs', import.meta.url), 'utf8');
assert.match(adapterSource, /shell:\s*false/u, 'contained spawn must set shell:false');
const capability = Object.freeze({
state: 'ready', version: 'fixture', proofFingerprint: HASH_A,
});
const job = Object.freeze({
policy: Object.freeze({ allowRendered: true }),
target: Object.freeze({ url: 'https://public.example.com/' }),
});
const launchPlan = Object.freeze({
kind: 'lynceuz_macos_containment_launch_plan',
executable: '/usr/bin/sudo',
argv: Object.freeze(['-n', '-u', '#401', '--', '/usr/bin/python3', '-I', '/opt/lynceuz/lynceuz-browser.py']),
uid: 401,
gid: 401,
guard_proxy: Object.freeze({ host: '127.0.0.1', port: 48191 }),
env: Object.freeze({ LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', PYTHONNOUSERSITE: '1' }),
shell: false,
});
let supervisorCalls = 0;
let received;
const supervisor = {
async run(profile, payload) {
supervisorCalls += 1;
received = { profile, payload };
return {
kind: 'success', code: 'ok',
response: { version: 1, id: 'render', ok: true, payload: {} },
};
},
};
const run = (sandbox) => createPlaywrightAdapter({ capability, sandbox, supervisor }).run({ job });
await run({ proofEligible: false, reason: 'containment_receipt_missing', launch: () => launchPlan });
await run({ proofEligible: true, launch: () => ({ ...launchPlan, shell: true }) });
assert.equal(supervisorCalls, 0, 'missing or invalid containment proof makes zero spawn calls');
let launchCalls = 0;
await run({
proofEligible: true,
launch() {
launchCalls += 1;
return launchPlan;
},
});
assert.equal(launchCalls, 1, 'adapter must consume sandbox.launch');
assert.equal(supervisorCalls, 1);
assert.equal(received.profile, 'python-browser');
assert.deepEqual(received.payload.launchPlan, launchPlan);
assert.equal(received.payload.launchPlan.shell, false);
});
test('containment receipt emitter refuses without root and writes no receipt', () => {
const script = fileURLToPath(new URL('../scripts/emit-macos-containment-receipt.mjs', import.meta.url));
const receiptPath = fileURLToPath(new URL('../.lynceuz/security/macos-containment-receipt-v1.json', import.meta.url));
const existedBefore = existsSync(receiptPath);
const run = spawnSync(process.execPath, [script], { encoding: 'utf8', shell: false, timeout: 10_000 });
assert.notEqual(run.status, 0, 'a non-root run must exit non-zero');
const printed = JSON.parse(run.stdout.trim().split('\n').filter(Boolean).at(-1));
assert.equal(printed.status, 'impossible');
assert.equal(printed.reason, 'containment_requires_root');
assert.equal(existsSync(receiptPath), existedBefore, 'the refused run must not create or delete the receipt');
});
test('containment canary client is self contained', async (t) => {
const { renderCanaryClientSource } = await import('../scripts/emit-macos-containment-receipt.mjs');
const source = renderCanaryClientSource();
assert.equal(typeof source, 'string');
assert.ok(source.length > 0, 'client source is non-empty');
assert.ok(!source.includes('/Users'), 'no home-directory absolute paths');
const imports = [...source.matchAll(/from\s+(['"])([^'"]+)\1/gu)].map((m) => m[2]);
assert.ok(imports.length > 0, 'client imports at least one module');
for (const specifier of imports) {
assert.ok(specifier.startsWith('node:'), `import must be a node: builtin: ${specifier}`);
}
const dir = await mkdtemp(join(tmpdir(), 'lynceuz-canary-client-'));
t.after(() => rm(dir, { recursive: true, force: true }));
const clientPath = join(dir, 'canary-client.mjs');
await writeFile(clientPath, source);
const checked = spawnSync(process.execPath, ['--check', clientPath], {
encoding: 'utf8', shell: false, timeout: 10_000,
});
assert.equal(checked.status, 0, checked.stderr || checked.stdout);
});
test('gate canary runs inside containment and fails closed when sudo refuses', async () => {
const { positiveCanary } = await import('../scripts/p1-browser-gate.mjs');
const { renderCanaryClientSource } = await import('../scripts/emit-macos-containment-receipt.mjs');
const expected = expectedContainment();
const calls = [];
let clientPath;
const runner = async (executable, argv, options) => {
calls.push({ executable, argv: [...argv], options });
clientPath = argv[4];
assert.equal(await readFile(clientPath, 'utf8'), renderCanaryClientSource());
return { stdout: `${JSON.stringify(passedCanary().observations)}\n`, stderr: '' };
};
const passed = await positiveCanary({ uidName: expected.uid_name, proxyPort: 0, runner });
assert.equal(passed.passed, true);
assert.deepEqual(calls[0].argv.slice(0, 4), ['-n', '-u', expected.uid_name, process.execPath]);
assert.equal(calls[0].executable, '/usr/bin/sudo');
assert.equal(calls[0].options.shell, false);
assert.match(clientPath, /^\/private\/tmp\/lynceuz-gate-canary-/u);
assert.equal(existsSync(clientPath), false, 'successful probe removes staged client');
let deniedPath;
await assert.rejects(
positiveCanary({
uidName: expected.uid_name,
proxyPort: 0,
runner: async (executable, argv) => {
assert.equal(executable, '/usr/bin/sudo');
deniedPath = argv[4];
throw new Error('sudo refused');
},
}),
(error) => error?.reason === 'containment_canary_failed'
&& error?.containment_state === 'unavailable_security_gate',
);
assert.equal(existsSync(deniedPath), false, 'failed probe removes staged client');
});
test('containment reads facts without root through a narrow non-root sudo path', async () => {
const { inspectMacosContainment } = await import('../src/macos-containment.mjs');
const expected = expectedContainment();
const ok = (stdout) => ({ status: 0, signal: null, stdout, stderr: '' });
// euid != 0: the two PF reads must go through `/usr/bin/sudo -n /sbin/pfctl ...`, never direct.
const seen = [];
const grantingRunner = (executable, argv) => {
seen.push({ executable, argv: [...argv] });
if (executable === '/usr/bin/id') return ok('401');
if (executable === '/usr/sbin/sysctl') return ok('{ sec = 1756000000 }');
if (executable === '/usr/bin/shasum') return ok(`${'a'.repeat(64)} ${expected.anchor_path}`);
if (executable === '/usr/bin/sudo') return ok(argv.includes('-sr') ? SAFE_PF_RULES : 'Status: Enabled');
throw new Error(`unexpected direct call: ${executable}`);
};
const facts = await inspectMacosContainment({ expected, runner: grantingRunner, geteuid: () => 1000 });
assert.notEqual(facts.state, 'unavailable_security_gate', 'the sudo path yields facts');
assert.equal(facts.pf.active, true);
assert.ok(!seen.some((c) => c.executable === '/sbin/pfctl'), 'a non-root gate never calls pfctl directly');
assert.deepEqual(
seen.find((c) => c.executable === '/usr/bin/sudo' && c.argv.includes('info'))?.argv,
['-n', '/sbin/pfctl', '-s', 'info'],
);
assert.deepEqual(
seen.find((c) => c.executable === '/usr/bin/sudo' && c.argv.includes('-sr'))?.argv,
['-n', '/sbin/pfctl', '-a', expected.anchor_name, '-sr'],
);
// `sudo -n` denied (no password-less grant): stay fail-closed with the same typed reason.
const denyingRunner = (executable, argv) => {
if (executable === '/usr/bin/sudo') {
return { status: 1, signal: null, stdout: '', stderr: 'sudo: a password is required' };
}
if (executable === '/usr/bin/id') return ok('401');
if (executable === '/usr/sbin/sysctl') return ok('{ sec = 1756000000 }');
if (executable === '/usr/bin/shasum') return ok(`${'a'.repeat(64)} ${expected.anchor_path}`);
throw new Error(`unexpected direct call: ${executable}`);
};
const denied = await inspectMacosContainment({ expected, runner: denyingRunner, geteuid: () => 1000 });
assert.equal(denied.state, 'unavailable_security_gate');
assert.equal(denied.reason, 'containment_system_facts_unavailable');
});
test('containment binary paths in macos-containment.mjs exist on disk', async () => {
const source = await readFile(new URL('../src/macos-containment.mjs', import.meta.url), 'utf8');
// every string literal that is an absolute system binary path (/bin, /sbin, /usr/bin, /usr/sbin)
const paths = [...source.matchAll(/(['"])((?:\/usr)?\/s?bin\/[^'"]*)\1/gu)].map((m) => m[2]);
assert.ok(paths.length > 0, 'no binary paths extracted — selection broke');
for (const path of paths) {
assert.ok(existsSync(path), `binary path does not exist on disk: ${path}`);
}
});
+388
View File
@@ -0,0 +1,388 @@
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { compileJobSpec, parseArgv } from '../src/cli.mjs';
import {
browserCapabilityState,
computeBrowserFingerprint,
createBrowserProofIntegrity,
createChildEgressSandbox,
createGuardProxy,
verifyBrowserSecurityProof,
} from '../src/browser-security.mjs';
import { createPlaywrightAdapter } from '../src/adapters/playwright.mjs';
import { runUrlJob } from '../src/core.mjs';
import { createNodeConnectPinned } from '../src/network.mjs';
import {
buildRoutePlan,
createCapabilitySnapshot,
renderedFallbackSkip,
runModelRoute,
} from '../src/router.mjs';
import { createStorage } from '../src/storage.mjs';
import {
REQUIRED_BROWSER_CHANNELS,
connectViaGuardProxy,
createBrowserHostileHarness,
requestViaGuardProxy,
} from './fixtures/browser-hostile.mjs';
import { baseUrlJob, createNativeFixture } from './fixtures/native-http.mjs';
const helperPath = fileURLToPath(new URL('../src/lynceuz-browser.py', import.meta.url));
const directProbePath = fileURLToPath(new URL('./fixtures/direct-egress-probe.py', import.meta.url));
const gatePath = fileURLToPath(new URL('../scripts/p1-browser-gate.mjs', import.meta.url));
const executablePath = fileURLToPath(new URL('../src/lynceuz.mjs', import.meta.url));
const noNetworkPath = fileURLToPath(new URL('./fixtures/no-network.mjs', import.meta.url));
function descriptor(id, state, reason, networkModel = 'guard-proxy') {
return {
id,
version: 'test',
state,
reason,
automatic: true,
commands: ['url'],
cost: 'local-zero',
price: 0,
networkModel,
};
}
function routeJob(argv = ['https://public.example.com/', '--allow-rendered']) {
return compileJobSpec(parseArgv(argv));
}
test('browser hostile contract is bounded and fail-closed', { timeout: 55_000 }, async (suite) => {
await suite.test('corpus names every TEST-02 channel', () => {
assert.deepEqual(REQUIRED_BROWSER_CHANNELS, [
'navigation', 'redirect', 'iframe', 'popup', 'worker', 'service_worker',
'websocket', 'webrtc_udp', 'webtransport', 'quic',
]);
});
await suite.test('installed package, missing proof and forced engine make zero browser calls', async () => {
const missing = browserCapabilityState({
id: 'playwright', installed: false, version: null, allowRendered: true,
proof: { valid: false, reason: 'proof_missing' },
});
assert.equal(missing.state, 'missing');
const gated = browserCapabilityState({
id: 'playwright', installed: true, version: '1.60.0', allowRendered: true,
proof: { valid: false, reason: 'proof_missing' },
});
assert.equal(gated.state, 'unavailable_security_gate');
const job = routeJob(['https://public.example.com/', '--allow-rendered', '--engine', 'playwright']);
const snapshot = createCapabilitySnapshot([
descriptor('playwright', gated.state, gated.reason),
]);
assert.equal(buildRoutePlan(job, snapshot).candidates[0].eligible, false);
let processCalls = 0;
const adapter = createPlaywrightAdapter({
capability: gated,
supervisor: { run: async () => { processCalls += 1; } },
});
const outcome = await adapter.run({ job });
assert.deepEqual(outcome, {
kind: 'skip', code: 'policy_unenforceable',
details: { reason: 'proof_missing' },
});
assert.equal(processCalls, 0);
const cwd = await mkdtemp(join(tmpdir(), 'lynceuz-forced-browser-'));
try {
const child = spawnSync(process.execPath, [
'--import', noNetworkPath,
executablePath,
'https://public.example.com/', '--allow-rendered', '--engine', 'playwright', '--json',
], {
cwd,
encoding: 'utf8',
timeout: 5_000,
env: { ...process.env, LYNCEUZ_FORBID_NETWORK: '1' },
});
assert.equal(child.status, 4, child.stderr);
const result = JSON.parse(child.stdout);
assert.equal(result.status, 'exhausted');
assert.equal(result.route[0].id, 'playwright');
assert.equal(result.route[0].eligible, false);
assert.match(result.route[0].reason, /sandbox_(?:loopback_scope_unproven|platform_unsupported)/u);
} finally {
await rm(cwd, { recursive: true, force: true });
}
});
await suite.test('allow-rendered is immutable per-run authority and cannot make invalid proof ready', () => {
const enabled = routeJob();
const defaultJob = routeJob(['https://public.example.com/']);
assert.equal(enabled.policy.allowRendered, true);
assert.equal(defaultJob.policy.allowRendered, false);
assert.equal(enabled.policy.moneyBudget, 0);
assert.equal(enabled.policy.auth, 'none');
assert.ok(Object.isFrozen(enabled));
const state = browserCapabilityState({
id: 'playwright', installed: true, version: '1.60.0', allowRendered: true,
proof: { valid: false, reason: 'fingerprint_mismatch' },
});
assert.equal(state.state, 'unavailable_security_gate');
const validProof = { valid: true, reason: 'proof_valid', fingerprint: 'sha256:proof' };
assert.equal(browserCapabilityState({
id: 'playwright', installed: true, version: '1.60.0', allowRendered: false,
proof: validProof,
}).state, 'disabled');
assert.equal(browserCapabilityState({
id: 'playwright', installed: true, version: '1.60.0', allowRendered: true,
proof: validProof,
}).state, 'ready');
});
await suite.test('only typed inadequate content can produce a rendered gate skip', () => {
const job = routeJob();
const route = [{
id: 'playwright', eligible: false, reason: 'sandbox_loopback_scope_unproven',
proofFingerprint: null,
}];
assert.deepEqual(renderedFallbackSkip(job, route, {
kind: 'inadequate', code: 'js_shell',
}), {
kind: 'skip', code: 'policy_unenforceable',
details: { reason: 'sandbox_loopback_scope_unproven' },
});
for (const outcome of [
{ kind: 'terminal', code: 'access_denied' },
{ kind: 'terminal', code: 'captcha' },
{ kind: 'retryable', code: 'rate_limited' },
{ kind: 'inadequate', code: 'wrong_mime' },
]) {
assert.equal(renderedFallbackSkip(job, route, outcome), null, outcome.code);
}
});
await suite.test('native JS shell records a typed browser skip in the normal manifest', async () => {
const parent = await mkdtemp(join(tmpdir(), 'lynceuz-render-skip-'));
const dataRoot = join(parent, '.lynceuz');
const fixture = createNativeFixture({ responses: [{
statusCode: 200,
headers: { 'content-type': 'text/html; charset=utf-8' },
body: Buffer.from('<!doctype html><html><body><script>document.body.textContent="ready"</script></body></html>'),
}] });
try {
const job = baseUrlJob({
policy: { ...baseUrlJob().policy, allowRendered: true },
cache: { mode: 'off', ttlMs: 60_000 },
});
const route = [{
id: 'playwright', eligible: false, reason: 'sandbox_loopback_scope_unproven',
proofFingerprint: null,
}];
const result = await runUrlJob(job, {
gateway: fixture.gateway,
storage: createStorage({ dataRoot, clock: fixture.clock }),
clock: fixture.clock,
sleep: fixture.sleep,
route,
capabilities: [],
});
assert.equal(result.status, 'exhausted');
const manifest = JSON.parse(await readFile(join(dataRoot, result.manifest_path), 'utf8'));
assert.deepEqual(manifest.attempts.at(-1), {
attempt: manifest.attempts.length,
type: 'transform',
adapter: 'playwright',
version: '1',
outcome: 'skip',
code: 'policy_unenforceable',
details: { reason: 'sandbox_loopback_scope_unproven' },
});
assert.equal(manifest.requested_url, job.target.url);
assert.equal(manifest.cost_money, 0);
} finally {
await rm(parent, { recursive: true, force: true });
}
});
await suite.test('terminal outcomes never transition to rendered adapter', async () => {
const terminalCases = [
['policy_denied', 'terminal'], ['robots_denied', 'terminal'],
['access_denied', 'terminal'], ['auth_required', 'terminal'],
['captcha', 'terminal'], ['paywall', 'terminal'], ['paid_required', 'terminal'],
['not_found', 'terminal'], ['gone', 'terminal'], ['hard_limit', 'terminal'],
['rate_limited', 'retryable'],
];
for (const [code, kind] of terminalCases) {
let browserCalls = 0;
const job = routeJob();
const snapshot = createCapabilitySnapshot([
descriptor('native', 'ready', 'ready', 'core-http'),
descriptor('playwright', 'ready', 'proof_valid'),
]);
const result = await runModelRoute(job, snapshot, {
adapters: {
native: { run: async () => ({ kind, code, retryAfterMs: 0 }) },
playwright: { run: async () => { browserCalls += 1; return { kind: 'success', code: 'ok' }; } },
},
});
assert.notEqual(result.status, 'ok', code);
assert.equal(browserCalls, 0, code);
}
});
await suite.test('GuardProxy authenticates and is the sole public fixture path', async () => {
const harness = await createBrowserHostileHarness();
const proxy = await createGuardProxy({ gateway: harness.gateway });
try {
assert.equal(proxy.host, '127.0.0.1');
const denied = await requestViaGuardProxy(proxy, harness.publicUrl, 'wrong-token');
assert.match(denied, /^HTTP\/1\.1 407 /u);
const allowed = await requestViaGuardProxy(proxy, harness.publicUrl, proxy.token);
assert.match(allowed, /^HTTP\/1\.1 200 /u);
assert.match(allowed, /rendered through GuardProxy/u);
const methodDenied = await requestViaGuardProxy(proxy, harness.publicUrl, proxy.token, 'POST');
assert.match(methodDenied, /^HTTP\/1\.1 405 /u);
const tunnel = await connectViaGuardProxy(proxy, proxy.token);
assert.match(tunnel, /^HTTP\/1\.1 200 Connection Established/u);
assert.match(tunnel, /rendered through GuardProxy/u);
assert.equal(harness.counters.privateTcp, 0);
assert.equal(harness.counters.privateUdp, 0);
assert.equal(proxy.stats.authorizedRequests, 2);
} finally {
await proxy.close();
await harness.close();
}
});
await suite.test('production pinned connector rejects an expired permit before dialing', async () => {
let dialCalls = 0;
const connectPinned = createNodeConnectPinned({
now: () => 101,
connect: () => { dialCalls += 1; throw new Error('must not dial'); },
});
await assert.rejects(connectPinned({
permit: {
protocol: 'https:', port: 443, selectedAddress: '93.184.216.34', expiresAtMs: 100,
},
}), /expired/u);
assert.equal(dialCalls, 0);
});
await suite.test('current child containment fails closed before any browser launch', async () => {
const harness = await createBrowserHostileHarness();
const proxy = await createGuardProxy({ gateway: harness.gateway });
try {
const sandbox = await createChildEgressSandbox({
proxyPort: proxy.port,
probeScript: directProbePath,
});
assert.equal(sandbox.state, 'unavailable_security_gate');
assert.equal(sandbox.proofEligible, false);
assert.match(sandbox.reason, /(?:unsupported|unenforceable|unproven|port_filter)/u);
assert.equal(harness.counters.privateTcp, 0);
assert.equal(harness.counters.privateUdp, 0);
} finally {
await proxy.close();
await harness.close();
}
});
await suite.test('proof is exact, complete, local-only and drift-sensitive', async () => {
const parent = await mkdtemp(join(tmpdir(), 'lynceuz-proof-'));
const dataRoot = join(parent, '.lynceuz');
await mkdir(join(dataRoot, 'security'), { recursive: true, mode: 0o700 });
const component = join(parent, 'component.mjs');
await writeFile(component, 'export const value = 1;\n');
try {
const fingerprint = await computeBrowserFingerprint({
sourcePaths: { component },
runtime: {
platform: 'test-platform', arch: 'test-arch', node: 'test-node',
python: 'test-python', playwright: 'test-playwright', chromium: 'test-chromium',
containment: 'test-containment', profile: 'test-profile',
},
});
const channels = Object.fromEntries(REQUIRED_BROWSER_CHANNELS.map((name) => [name, true]));
const minimalForgery = {
kind: 'browser_security_proof', schema_version: 1, status: 'passed',
fingerprint: fingerprint.digest, channels, generated_at: new Date().toISOString(),
};
await writeFile(join(dataRoot, 'security/browser-proof-v1.json'), JSON.stringify(minimalForgery));
assert.equal((await verifyBrowserSecurityProof({ dataRoot, fingerprint })).valid, false);
const suites = [
'evals/browser-hostile.test.mjs',
'evals/router.test.mjs',
'evals/p0-acceptance.test.mjs',
].map((suite) => ({
suite, passed: true, skipped: false, exit_code: 0, signal: null,
duration_ms: 1, stdout_hash: `sha256:${'1'.repeat(64)}`,
stderr_hash: `sha256:${'2'.repeat(64)}`,
}));
const passedDraft = {
kind: 'browser_security_proof', schema_version: 1, status: 'passed',
reason: 'proof_valid', fingerprint: fingerprint.digest,
generated_at: new Date().toISOString(),
platform: fingerprint.runtime.platform, arch: fingerprint.runtime.arch,
runtime: fingerprint.runtime, source_hashes: fingerprint.sources, channels, suites,
};
const passed = {
...passedDraft,
marker_hash: createBrowserProofIntegrity(passedDraft),
};
await writeFile(join(dataRoot, 'security/browser-proof-v1.json'), JSON.stringify(passed));
assert.equal((await verifyBrowserSecurityProof({ dataRoot, fingerprint })).valid, true);
await writeFile(component, 'export const value = 2;\n');
const drifted = await computeBrowserFingerprint({
sourcePaths: { component }, fingerprintRuntime: fingerprint.runtime,
});
const verification = await verifyBrowserSecurityProof({ dataRoot, fingerprint: drifted });
assert.equal(verification.valid, false);
assert.equal(verification.reason, 'fingerprint_mismatch');
} finally {
await rm(parent, { recursive: true, force: true });
}
});
await suite.test('browser helper rejects interactive operations without launching Playwright', () => {
const result = spawnSync('python3', ['-I', helperPath], {
input: `${JSON.stringify({ version: 1, id: 'forbidden', operation: 'click' })}\n`,
encoding: 'utf8', timeout: 3_000,
});
assert.equal(result.status, 0, result.stderr);
const response = JSON.parse(result.stdout);
assert.equal(response.ok, false);
assert.equal(response.code, 'unsupported_operation');
assert.equal(result.stdout.trim().split(/\r?\n/u).length, 1);
});
});
if (process.env.LYNCEUZ_GATE_SUITE !== '1') {
test('release gate atomically records an honest containment failure', { timeout: 55_000 }, async () => {
const parent = await mkdtemp(join(tmpdir(), 'lynceuz-gate-'));
const dataRoot = join(parent, '.lynceuz');
try {
const result = spawnSync(process.execPath, [gatePath, '--json', '--data-root', dataRoot], {
cwd: fileURLToPath(new URL('..', import.meta.url)),
encoding: 'utf8',
timeout: 45_000,
env: { ...process.env, LYNCEUZ_GATE_TEST: '1' },
});
assert.equal(result.status, 1, result.stderr);
assert.equal(result.signal, null);
assert.equal(result.stdout.trim().split(/\r?\n/u).length, 1);
const output = JSON.parse(result.stdout);
assert.equal(output.kind, 'browser_security_proof');
assert.equal(output.status, 'failed');
assert.equal(output.reason, 'sandbox_loopback_scope_unproven');
const marker = JSON.parse(await readFile(
join(dataRoot, 'security/browser-proof-v1.json'), 'utf8',
));
assert.equal(marker.status, 'failed');
assert.equal(marker.fingerprint, output.fingerprint);
} finally {
await rm(parent, { recursive: true, force: true });
}
});
}
+279
View File
@@ -0,0 +1,279 @@
import assert from 'node:assert/strict';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { isAbsolute, join, resolve, sep } from 'node:path';
import test from 'node:test';
import { compileJobSpec, parseArgv, runCli } from '../src/cli.mjs';
import { createProductionExecutor } from '../src/core.mjs';
import { createDefaultRegistry } from '../src/router.mjs';
import { createStorage } from '../src/storage.mjs';
import { createNativeFixture } from './fixtures/native-http.mjs';
const TARGET = 'https://public.example.org/page';
const START_MS = Date.parse('2026-08-26T08:00:00.000Z');
const REGISTRY = createDefaultRegistry(process.version).map((capability) => (
capability.id === 'native'
? {
...capability,
version: '1',
state: 'ready',
reason: 'native_http_ready',
}
: capability
));
function memoryIo() {
let stdout = '';
let stderr = '';
return {
io: {
stdout: { write: (value) => { stdout += value; } },
stderr: { write: (value) => { stderr += value; } },
},
read: () => ({ stdout, stderr }),
};
}
async function temporaryDataRoot(t) {
const workspace = await mkdtemp(join(tmpdir(), 'lynceuz-cli-native-'));
t.after(async () => rm(workspace, { recursive: true, force: true }));
return {
workspace,
dataRoot: join(workspace, '.lynceuz'),
};
}
async function productionHarness(t, responses) {
const { workspace, dataRoot } = await temporaryDataRoot(t);
const fixture = createNativeFixture({ responses, startMs: START_MS });
const storage = await createStorage({ dataRoot, clock: fixture.clock });
const executeJob = createProductionExecutor({
gateway: fixture.gateway,
storage,
clock: fixture.clock,
sleep: fixture.sleep,
});
assert.equal(typeof executeJob, 'function');
return { workspace, dataRoot, fixture, storage, executeJob };
}
async function invoke(executeJob, argv) {
const output = memoryIo();
const exitCode = await runCli(argv, {
io: output.io,
registry: REGISTRY,
executeJob,
now: () => new Date(START_MS),
});
return { exitCode, ...output.read() };
}
function parseSingleJson(stdout) {
assert.equal(stdout.endsWith('\n'), true);
assert.equal(stdout.split('\n').filter(Boolean).length, 1);
return JSON.parse(stdout);
}
function assertRelativeInside(dataRoot, relativePath) {
assert.equal(typeof relativePath, 'string');
assert.equal(isAbsolute(relativePath), false);
const root = resolve(dataRoot);
const target = resolve(root, relativePath);
assert.equal(target.startsWith(`${root}${sep}`), true);
return target;
}
function headerValue(headers, wantedName) {
const entry = Object.entries(headers ?? {})
.find(([name]) => name.toLowerCase() === wantedName.toLowerCase());
return entry?.[1];
}
async function readManifest(dataRoot, result) {
const path = assertRelativeInside(dataRoot, result.manifest_path);
return JSON.parse(await readFile(path, 'utf8'));
}
test('URL flags compile to bounded Phase 2 defaults and explicit options', () => {
const defaults = compileJobSpec(parseArgv(['url', TARGET]));
assert.equal(defaults.goal, 'markdown');
assert.deepEqual(defaults.output, {
json: false,
format: 'markdown',
path: null,
dataRoot: null,
});
assert.deepEqual(defaults.cache, { mode: 'use', ttlMs: 3_600_000 });
for (const format of ['raw', 'markdown', 'metadata', 'links', 'json']) {
const spec = compileJobSpec(parseArgv([
TARGET,
'--format', format,
'--output', `exports/page.${format}`,
'--data-root', 'state/.lynceuz',
'--cache', 'refresh',
'--ttl', '17',
'--json',
]));
assert.equal(spec.goal, format);
assert.deepEqual(spec.output, {
json: true,
format,
path: `exports/page.${format}`,
dataRoot: 'state/.lynceuz',
});
assert.deepEqual(spec.cache, { mode: 'refresh', ttlMs: 17_000 });
assert.ok(Object.isFrozen(spec.output));
assert.ok(Object.isFrozen(spec.cache));
}
});
test('format, cache, TTL, output and data-root inputs fail closed', () => {
const invalid = [
[TARGET, '--format', 'html'],
[TARGET, '--cache', 'stale-ok'],
[TARGET, '--ttl', '0'],
[TARGET, '--ttl', '-1'],
[TARGET, '--ttl', 'Infinity'],
[TARGET, '--ttl', '9007199254740'],
[TARGET, '--ttl', 'not-a-number'],
[TARGET, '--output', '../escape.md'],
[TARGET, '--output', '/tmp/escape.md'],
[TARGET, '--output', '.'],
[TARGET, '--data-root', 'state'],
[TARGET, '--data-root', '.lynceuz/child'],
];
for (const argv of invalid) {
assert.throws(() => compileJobSpec(parseArgv(argv)), /invalid input/);
}
const absoluteRoot = compileJobSpec(parseArgv([
TARGET,
'--data-root', '/tmp/acceptance/.lynceuz',
'--cache', 'off',
]));
assert.equal(absoluteRoot.output.dataRoot, '/tmp/acceptance/.lynceuz');
assert.equal(absoluteRoot.cache.mode, 'off');
});
test('one URL command emits one JSON result, keeps warnings on stderr and writes only below data root', async (t) => {
const body = Buffer.from([0x00, 0x01, 0x02, 0xff]);
const harness = await productionHarness(t, [{
statusCode: 200,
headers: { 'content-type': 'application/octet-stream' },
body,
}]);
const outputPath = 'exports/evidence.bin';
const run = await invoke(harness.executeJob, [
TARGET,
'--format', 'raw',
'--output', outputPath,
'--data-root', harness.dataRoot,
'--cache', 'off',
'--json',
]);
const result = parseSingleJson(run.stdout);
assert.equal(run.exitCode, 0);
assert.equal(result.schema_version, 1);
assert.equal(result.command, 'url');
assert.equal(result.status, 'ok');
assert.equal(result.code, 'ok');
assert.equal(result.cache_status, 'off');
assert.match(result.source_hash, /^sha256:[a-f0-9]{64}$/u);
assert.match(run.stderr, /^warning: unknown_mime_raw_preserved\n$/u);
assert.deepEqual(result.warnings, ['unknown_mime_raw_preserved']);
const manifestPath = assertRelativeInside(harness.dataRoot, result.manifest_path);
const artifactPath = assertRelativeInside(harness.dataRoot, result.artifact_path);
assert.equal(result.artifact_path, outputPath);
assert.deepEqual(await readFile(artifactPath), body);
const manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
assert.equal(manifest.schema_version, 1);
assert.equal(manifest.source_hash, result.source_hash);
await assert.rejects(
readFile(join(harness.workspace, '.gitignore')),
(error) => error?.code === 'ENOENT',
);
});
test('fresh TTL cache hit performs zero DNS and transport calls', async (t) => {
const harness = await productionHarness(t, [{
statusCode: 200,
headers: {
'content-type': 'text/html; charset=utf-8',
etag: '"v1"',
'last-modified': 'Wed, 26 Aug 2026 07:00:00 GMT',
},
body: Buffer.from('<h1>Cached</h1>'),
}]);
const argv = [TARGET, '--data-root', harness.dataRoot, '--ttl', '60', '--json'];
const first = parseSingleJson((await invoke(harness.executeJob, argv)).stdout);
const callsAfterMiss = {
lookupAll: harness.fixture.calls.lookupAll.length,
requestPinned: harness.fixture.calls.requestPinned.length,
};
harness.fixture.advance(1_000);
const secondRun = await invoke(harness.executeJob, argv);
const second = parseSingleJson(secondRun.stdout);
assert.equal(secondRun.exitCode, 0);
assert.equal(first.cache_status, 'miss');
assert.equal(second.cache_status, 'hit');
assert.equal(second.source_hash, first.source_hash);
assert.deepEqual({
lookupAll: harness.fixture.calls.lookupAll.length,
requestPinned: harness.fixture.calls.requestPinned.length,
}, callsAfterMiss);
const firstManifest = await readManifest(harness.dataRoot, first);
const secondManifest = await readManifest(harness.dataRoot, second);
assert.equal(secondManifest.fetched_at, firstManifest.fetched_at);
assert.notEqual(secondManifest.served_at, null);
});
test('stale cache sends ETag and Last-Modified once; 304 preserves provenance timestamps', async (t) => {
const etag = '"fixture-v1"';
const lastModified = 'Wed, 26 Aug 2026 07:00:00 GMT';
const harness = await productionHarness(t, [
{
statusCode: 200,
headers: {
'content-type': 'text/html; charset=utf-8',
etag,
'last-modified': lastModified,
},
body: Buffer.from('<h1>Stable source</h1>'),
},
{
statusCode: 304,
headers: { etag, 'last-modified': lastModified },
body: Buffer.alloc(0),
},
]);
const argv = [TARGET, '--data-root', harness.dataRoot, '--ttl', '1', '--json'];
const first = parseSingleJson((await invoke(harness.executeJob, argv)).stdout);
const firstManifest = await readManifest(harness.dataRoot, first);
harness.fixture.advance(2_000);
const secondRun = await invoke(harness.executeJob, argv);
const second = parseSingleJson(secondRun.stdout);
const secondManifest = await readManifest(harness.dataRoot, second);
assert.equal(secondRun.exitCode, 0);
assert.equal(first.cache_status, 'miss');
assert.equal(second.cache_status, 'revalidated');
assert.equal(harness.fixture.calls.requestPinned.length, 2);
const conditional = harness.fixture.calls.requestPinned[1];
assert.equal(headerValue(conditional.headers, 'if-none-match'), etag);
assert.equal(headerValue(conditional.headers, 'if-modified-since'), lastModified);
assert.equal(second.source_hash, first.source_hash);
assert.equal(secondManifest.source_hash, firstManifest.source_hash);
assert.equal(secondManifest.fetched_at, firstManifest.fetched_at);
assert.notEqual(secondManifest.served_at, null);
assert.notEqual(secondManifest.revalidated_at, null);
assert.notEqual(secondManifest.served_at, firstManifest.served_at);
});
+212
View File
@@ -0,0 +1,212 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
ATTEMPT_CODE,
ATTEMPT_KIND,
CAPABILITY_STATE,
EXIT_CODE,
RUN_STATUS,
createResultEnvelope,
exitCodeForStatus,
validateResultEnvelope,
} from '../src/contracts.mjs';
import { compileJobSpec, parseArgv, runCli, writeResult } from '../src/cli.mjs';
function memoryIo({ failStdout = false } = {}) {
let stdout = '';
let stderr = '';
return {
io: {
stdout: { write: (value) => {
if (failStdout) throw new Error('disk full');
stdout += value;
} },
stderr: { write: (value) => { stderr += value; } },
},
read: () => ({ stdout, stderr }),
};
}
function validResult(overrides = {}) {
return createResultEnvelope({
command: 'url',
status: RUN_STATUS.OK,
code: 'ok',
message: 'captured',
route: [],
capabilities: [],
warnings: [],
...overrides,
});
}
test('contract enums and exit mapping are frozen and stable', () => {
assert.deepEqual(RUN_STATUS, {
OK: 'ok',
INVALID_INPUT: 'invalid_input',
PARTIAL: 'partial',
EXHAUSTED: 'exhausted',
BLOCKED: 'blocked',
INTERNAL_ERROR: 'internal_error',
OUTPUT_FAILURE: 'output_failure',
INTERRUPTED: 'interrupted',
});
assert.deepEqual(EXIT_CODE, {
OK: 0,
INVALID_INPUT: 2,
PARTIAL: 3,
EXHAUSTED: 4,
BLOCKED: 5,
INTERNAL_ERROR: 70,
OUTPUT_FAILURE: 74,
TIMEOUT: 124,
SIGINT: 130,
SIGTERM: 143,
});
assert.ok(Object.isFrozen(RUN_STATUS));
assert.ok(Object.isFrozen(EXIT_CODE));
assert.ok(Object.isFrozen(ATTEMPT_KIND));
assert.ok(Object.isFrozen(ATTEMPT_CODE));
assert.ok(Object.isFrozen(CAPABILITY_STATE));
assert.equal(exitCodeForStatus('ok'), 0);
assert.equal(exitCodeForStatus('exhausted'), 4);
assert.equal(exitCodeForStatus('interrupted', { reason: 'timeout' }), 124);
assert.equal(exitCodeForStatus('interrupted', { signal: 'SIGINT' }), 130);
assert.equal(exitCodeForStatus('interrupted', { signal: 'SIGTERM' }), 143);
assert.throws(() => exitCodeForStatus('wat'), /unknown run status/);
});
test('result envelope is strict, schema-versioned and deeply frozen', () => {
const result = validResult({ route: [{ adapter: 'native' }] });
assert.equal(result.schema_version, 1);
assert.ok(Object.isFrozen(result));
assert.ok(Object.isFrozen(result.route));
assert.ok(Object.isFrozen(result.route[0]));
assert.equal(validateResultEnvelope(result), true);
assert.throws(() => createResultEnvelope({ ...result, status: 'wat' }), /status/);
assert.throws(() => createResultEnvelope({ ...result, code: 'wat' }), /code/);
assert.throws(() => createResultEnvelope({ ...result, manifest: {} }), /unexpected field/);
assert.throws(
() => createResultEnvelope({ ...result, status: 'blocked', code: 'ok' }),
/does not match status/,
);
});
test('all Phase 1 command forms compile into immutable zero-authority JobSpec', () => {
const cases = [
{ argv: ['https://example.com/a#frag'], kind: 'url', target: { url: 'https://example.com/a#frag' } },
{ argv: ['url', 'https://example.com'], kind: 'url', target: { url: 'https://example.com' } },
{ argv: ['crawl', 'https://example.com'], kind: 'crawl', target: { url: 'https://example.com' } },
{
argv: ['extract', 'https://example.com', '--schema', 'schema.json'],
kind: 'extract',
target: { url: 'https://example.com', schemaPath: 'schema.json' },
},
{ argv: ['search', 'public records'], kind: 'search', target: { query: 'public records' } },
{ argv: ['health'], kind: 'health', target: {} },
];
for (const item of cases) {
const spec = compileJobSpec(parseArgv(item.argv));
assert.equal(spec.schemaVersion, 1);
assert.equal(spec.kind, item.kind);
assert.deepEqual(spec.target, item.target);
assert.equal(spec.policy.network, 'public-only');
assert.equal(spec.policy.auth, 'none');
assert.equal(spec.policy.moneyBudget, 0);
assert.equal(spec.policy.allowFreeCloud, false);
assert.equal(spec.policy.allowRendered, false);
assert.equal(spec.limits.maxRetryAfterMs, 15_000);
for (const value of Object.values(spec.limits)) {
assert.equal(Number.isFinite(value), true);
assert.ok(value > 0);
}
assert.ok(Object.isFrozen(spec));
assert.ok(Object.isFrozen(spec.target));
assert.ok(Object.isFrozen(spec.limits));
assert.ok(Object.isFrozen(spec.policy));
}
});
test('flags are explicit, scoped and cannot expand authority', () => {
const spec = compileJobSpec(parseArgv([
'https://example.com', '--json', '--explain', '--engine', 'native',
]));
assert.deepEqual(spec.output, { json: true });
assert.deepEqual(spec.routing, { explain: true, forcedEngine: 'native' });
assert.equal(spec.policy.moneyBudget, 0);
assert.equal(spec.policy.allowFreeCloud, false);
assert.equal(spec.policy.allowRendered, false);
const invalid = [
[],
['url'],
['health', 'extra'],
['extract', 'https://example.com'],
['crawl', 'https://example.com', '--schema', 'x.json'],
['search', 'one', 'two'],
['https://example.com', '--wat'],
['https://example.com', '--engine'],
['https://example.com', '--engine', '../bad'],
['ftp://example.com'],
];
for (const argv of invalid) assert.throws(() => parseArgv(argv), /invalid input/);
});
test('runCli rejects malformed argv before dependencies', async () => {
const output = memoryIo();
let calls = 0;
const code = await runCli(['health', '--wat', '--json'], {
io: output.io,
registry: [],
executeJob: async () => { calls += 1; },
now: () => new Date(0),
});
const written = output.read();
assert.equal(code, EXIT_CODE.INVALID_INPUT);
assert.equal(calls, 0);
assert.equal(written.stdout.endsWith('\n'), true);
assert.equal(written.stdout.split('\n').filter(Boolean).length, 1);
assert.equal(JSON.parse(written.stdout).status, RUN_STATUS.INVALID_INPUT);
assert.equal(written.stderr.includes('--wat'), false);
});
test('JSON output is one document while warnings stay on stderr', async () => {
const output = memoryIo();
const result = validResult({ warnings: ['adapter missing'] });
const code = await runCli(['https://example.com', '--json'], {
io: output.io,
registry: [],
executeJob: async () => result,
now: () => new Date(0),
});
const written = output.read();
assert.equal(code, 0);
assert.deepEqual(JSON.parse(written.stdout), result);
assert.equal(written.stdout.match(/\n/g)?.length, 1);
assert.equal(written.stdout.includes('adapter missing'), true);
assert.match(written.stderr, /warning: adapter missing/);
});
test('write failure is distinct from result failure', async () => {
const output = memoryIo({ failStdout: true });
const code = await runCli(['health', '--json'], {
io: output.io,
registry: [],
executeJob: async () => validResult({ command: 'health' }),
now: () => new Date(0),
});
assert.equal(code, EXIT_CODE.OUTPUT_FAILURE);
assert.match(output.read().stderr, /output_failure/);
});
test('writeResult rejects an invalid executable payload', () => {
const output = memoryIo();
assert.throws(
() => writeResult({ status: 'ok', code: 'ok' }, output.io, { json: true }),
/result envelope/,
);
});
+279
View File
@@ -0,0 +1,279 @@
// RED contract for the fail-closed free-cloud gate (COST-02 opt-in, COST-03 ledger).
//
// v1 forbids any network provider, so cloud is a dead model proven by fakes on
// frozen JobSpec/policy literals — never a CLI flag, never live network, never a
// new package. Every test dynamic-imports the future src/cloud.mjs *inside* its
// body; until that model exists they fail with ERR_MODULE_NOT_FOUND, the intended
// red state. They green once src/cloud.mjs ships the additive gate:
//
// evaluateCloudGate(job, { provider, ledger, baseline, clock }) -> decision
// Fail-closed opt-in gate, runs BEFORE any provider preflight/execute.
// { outcome, reason, executed, route, eligibility, cost_money (numeric),
// credits_used, trust_boundary:{kind,evidence_is_local_public_only},
// local_public_only_equivalent }
// reserveWorstCase(ledger, { job, provider, clock }) -> reservation
// Inspects the provider's declared worst-case reservation only.
// { outcome, broken, committed, cost_money, credits_used }
// runCloudAttempt(job, { provider, ledger, clock }) -> { attempt, manifest }
// Both records stamped with the money/credit/trust-boundary invariants.
import assert from 'node:assert/strict';
import test from 'node:test';
import { deepFreeze } from '../src/contracts.mjs';
const CLOUD_MODEL = '../src/cloud.mjs';
const NOW = '2026-08-26T17:00:00.000Z';
// Frozen policy literal: default v1 stance — zero money budget, free cloud off,
// public-only, no auth. Overrides flip a single field for a given test.
const FROZEN_POLICY = deepFreeze({
moneyBudget: 0,
allowFreeCloud: false,
network: 'public-only',
auth: 'none',
});
function frozenJob(overrides = {}) {
const { policy, ...rest } = overrides;
return deepFreeze({
schemaVersion: 1,
command: 'url',
goal: 'source-capture',
target: { url: 'https://public.example.test/records' },
policy: policy ? deepFreeze({ ...FROZEN_POLICY, ...policy }) : FROZEN_POLICY,
...rest,
});
}
// The local-first route/eligibility computed before cloud is ever considered.
// The gate must return these byte-for-byte when it blocks — cloud adds no hop.
function localFirstBaseline() {
return deepFreeze({
route: [
{ engine: 'core-http', decision: 'attempted', cost: 'local-zero' },
{ engine: 'rendered-fallback', decision: 'not-needed', cost: 'local-zero' },
],
eligibility: {
'core-http': 'ready',
'rendered-fallback': 'ready',
'fixture-cloud': 'ineligible_cloud_disabled',
},
});
}
// A cloud provider fixture with present credentials/binary and call counters.
// Defaults are maximally UNPROVEN (unknown price, unknown/stale balance, no
// hard ceiling, zero free credits) so the base fixture is fail-closed. Its
// preflight() CAN charge and execute() is billable — both must stay uncalled.
function cloudProvider(overrides = {}) {
const counters = { preflight: 0, billable: 0, sampled: 0 };
return Object.assign({
id: 'fixture-cloud',
version: '1',
cost: 'cloud-free-credits',
price: 'unknown',
balance: 'unknown',
balanceObservedAt: null,
hardCeiling: null,
freeCredits: 0,
worstCaseCredits: 5,
preflightMayCharge: true,
credentials: 'present',
binary: '/opt/lynceuz/cloud-scraper',
networkModel: 'provider-managed',
counters,
preflight: async () => { counters.preflight += 1; return { charge: 1 }; },
execute: async () => {
counters.billable += 1;
return { body: 'PROVIDER PAID BODY', hash: `sha256:${'b'.repeat(64)}`, charged: 1 };
},
sampleEvidence: async () => {
counters.sampled += 1;
return { body: 'PROVIDER SAMPLE', hash: `sha256:${'c'.repeat(64)}` };
},
}, overrides);
}
// A cloud provider whose cost is fully proven safe on every axis. The base for
// COST-02/COST-03 flip tests: toggling ONE risk field must re-block it.
function provableCloud(overrides = {}) {
return cloudProvider({
price: 0,
balance: 100,
balanceObservedAt: NOW,
hardCeiling: 10,
freeCredits: 100,
worstCaseCredits: 5,
preflightMayCharge: false,
...overrides,
});
}
function creditLedger(overrides = {}) {
return {
balance: 'unknown',
observedAt: null,
hardCeiling: null,
committed: 0,
reservations: [],
...overrides,
};
}
function provableLedger(overrides = {}) {
return creditLedger({ balance: 100, observedAt: NOW, hardCeiling: 10, ...overrides });
}
// --- COST-02: fail-closed cloud opt-in gate ---
test('COST-02 cloud gate leaves route and eligibility untouched and calls nothing when free cloud is off despite a present API key and binary', async () => {
const { evaluateCloudGate } = await import(CLOUD_MODEL);
const provider = cloudProvider({ credentials: 'present', binary: '/opt/lynceuz/cloud-scraper' });
const baseline = localFirstBaseline();
const decision = await evaluateCloudGate(frozenJob({ policy: { allowFreeCloud: false } }), {
provider,
ledger: creditLedger(),
baseline,
clock: () => new Date(NOW),
});
assert.equal(decision.outcome, 'unknown_and_blocked');
assert.equal(decision.executed, false);
// Route and eligibility are returned unchanged — cloud adds no hop when off.
assert.deepEqual(decision.route, baseline.route);
assert.deepEqual(decision.eligibility, baseline.eligibility);
// No billable run and no preflight, even though the credential and binary exist.
assert.equal(provider.counters.billable, 0);
assert.equal(provider.counters.preflight, 0);
assert.equal(decision.cost_money, 0);
assert.equal(typeof decision.cost_money, 'number');
assert.equal(decision.local_public_only_equivalent, false);
});
test('COST-02 cloud gate returns unknown_and_blocked before provider execution for every unproven-cost condition', async () => {
const { evaluateCloudGate } = await import(CLOUD_MODEL);
// The opt-in flag is ON — the block must come from unproven cost, not the flag.
const optIn = { allowFreeCloud: true };
const conditions = [
{ label: 'unknown or stale balance', provider: { balance: 'unknown', balanceObservedAt: null }, ledger: { balance: 'unknown', observedAt: null } },
{ label: 'unknown price', provider: { price: 'unknown' } },
{ label: 'absent hard ceiling', provider: { hardCeiling: null }, ledger: { hardCeiling: null } },
{ label: 'insufficient free credits', provider: { freeCredits: 1, worstCaseCredits: 5 } },
{ label: 'preflight able to charge', provider: { preflightMayCharge: true } },
];
for (const { label, provider: p, ledger: l } of conditions) {
const provider = provableCloud(p);
const decision = await evaluateCloudGate(frozenJob({ policy: optIn }), {
provider,
ledger: provableLedger(l),
baseline: localFirstBaseline(),
clock: () => new Date(NOW),
});
assert.equal(decision.outcome, 'unknown_and_blocked', label);
assert.equal(decision.executed, false, label);
assert.equal(provider.counters.billable, 0, label);
assert.equal(provider.counters.preflight, 0, label);
assert.equal(decision.cost_money, 0, label);
}
});
// --- COST-03: worst-case reservation ledger ---
test('COST-03 credit ledger refuses two worst-case reservations without over-debiting the shared ledger', async () => {
const { reserveWorstCase } = await import(CLOUD_MODEL);
// Balance leaves room for at most one 5-credit worst case; two must not both pass.
const ledger = provableLedger({ balance: 8 });
const a = provableCloud({ id: 'cloud-a', worstCaseCredits: 5 });
const b = provableCloud({ id: 'cloud-b', worstCaseCredits: 5 });
const job = frozenJob({ policy: { allowFreeCloud: true } });
const first = reserveWorstCase(ledger, { job, provider: a, clock: () => new Date(NOW) });
const second = reserveWorstCase(ledger, { job, provider: b, clock: () => new Date(NOW) });
// v1 fail-closed: neither reservation commits, the shared ledger is never debited.
assert.equal(ledger.committed, 0);
assert.deepEqual(ledger.reservations, []);
for (const reservation of [first, second]) {
assert.equal(reservation.outcome, 'unknown_and_blocked');
assert.equal(reservation.committed, false);
assert.equal(reservation.cost_money, 0);
assert.equal(reservation.credits_used, 'unknown_and_blocked');
}
assert.equal(a.counters.billable, 0);
assert.equal(b.counters.billable, 0);
});
test('COST-03 credit ledger treats an impossible, negative, or over-reserve report as a broken provider contract not a free success', async () => {
const { reserveWorstCase } = await import(CLOUD_MODEL);
const brokenReports = [
{ label: 'negative worst case', provider: { worstCaseCredits: -5 } },
{ label: 'NaN worst case', provider: { worstCaseCredits: Number.NaN } },
{ label: 'non-finite worst case', provider: { worstCaseCredits: Number.POSITIVE_INFINITY } },
{ label: 'over-reserve above hard ceiling', provider: { worstCaseCredits: 999, hardCeiling: 10 } },
{ label: 'over-reserve above balance', provider: { worstCaseCredits: 999, balance: 100 } },
];
for (const { label, provider: p } of brokenReports) {
const provider = provableCloud(p);
const ledger = provableLedger({ balance: 100 });
const reservation = reserveWorstCase(ledger, {
job: frozenJob({ policy: { allowFreeCloud: true } }),
provider,
clock: () => new Date(NOW),
});
// A negative/impossible charge is a broken contract, never "cost went down → free success".
assert.equal(reservation.broken, true, label);
assert.equal(reservation.outcome, 'unknown_and_blocked', label);
assert.notEqual(reservation.outcome, 'reserved', label);
assert.equal(reservation.committed, false, label);
assert.equal(ledger.committed, 0, label);
assert.equal(provider.counters.billable, 0, label);
}
});
test('COST-03 credit ledger stamps every attempt and manifest with numeric zero cost, provider-managed boundary and non-local evidence', async () => {
const { runCloudAttempt } = await import(CLOUD_MODEL);
const provider = cloudProvider();
const { attempt, manifest } = await runCloudAttempt(frozenJob({ policy: { allowFreeCloud: true } }), {
provider,
ledger: creditLedger(),
clock: () => new Date(NOW),
});
for (const record of [attempt, manifest]) {
assert.equal(record.cost_money, 0);
assert.equal(typeof record.cost_money, 'number');
assert.equal(record.credits_used, 'unknown_and_blocked');
assert.equal(record.trust_boundary.kind, 'provider-managed');
assert.equal(record.local_public_only_equivalent, false);
}
assert.equal(provider.counters.billable, 0);
assert.equal(provider.counters.preflight, 0);
});
test('COST-03 credit ledger never accepts a provider-supplied body or hash as local public-only evidence', async () => {
const { runCloudAttempt } = await import(CLOUD_MODEL);
const providerHash = `sha256:${'c'.repeat(64)}`;
const provider = cloudProvider({
sampleEvidence: async () => ({ body: 'PROVIDER SUPPLIED BODY', hash: providerHash }),
});
const { attempt, manifest } = await runCloudAttempt(frozenJob({ policy: { allowFreeCloud: true } }), {
provider,
ledger: creditLedger(),
clock: () => new Date(NOW),
});
// Provider content stays quarantined behind the provider-managed boundary,
// never promoted to local public-only evidence, never a top-level source hash.
assert.equal(attempt.local_public_only_equivalent, false);
assert.equal(manifest.local_public_only_equivalent, false);
assert.equal(manifest.trust_boundary.kind, 'provider-managed');
assert.equal(manifest.trust_boundary.evidence_is_local_public_only, false);
assert.equal(manifest.source_hash, undefined);
assert.notEqual(manifest.source_hash, providerHash);
assert.equal(provider.counters.billable, 0);
});
+471
View File
@@ -0,0 +1,471 @@
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { createPythonTransformAdapter } from '../src/adapters/python-helper.mjs';
import { compileJobSpec, parseArgv } from '../src/cli.mjs';
import { ATTEMPT_CODE, ATTEMPT_KIND } from '../src/contracts.mjs';
import { runCrawlJob, runExtractJob, runUrlPipeline } from '../src/core.mjs';
import {
canonicalFrontierKey,
createFrontier,
runBoundedCrawl,
} from '../src/frontier.mjs';
import { PYTHON_HELPER_PATH } from '../src/process.mjs';
import { createRobotsGate, parseRobots } from '../src/robots.mjs';
import { acceptRepresentation, decideTransition } from '../src/router.mjs';
import { createStorage } from '../src/storage.mjs';
import {
DEFAULT_GRAPH,
DEFAULT_ROBOTS,
P0_ORIGIN,
createP0SiteFixture,
} from './fixtures/p0-site.mjs';
const TARGET = `${P0_ORIGIN}/`;
const PYTHON_PROBE = spawnSync('python3', ['-c', 'import sys; print(sys.executable)'], {
encoding: 'utf8',
});
const PYTHON = PYTHON_PROBE.status === 0 ? PYTHON_PROBE.stdout.trim() : '/usr/bin/python3';
const PARSER_AVAILABLE = PYTHON_PROBE.status === 0
&& spawnSync(PYTHON, ['-I', PYTHON_HELPER_PATH, '--self-check'], { encoding: 'utf8' }).status === 0;
const OPTIONAL_PARSER_SKIP = PARSER_AVAILABLE ? false : 'optional Python parser is unavailable';
async function temporaryStorage(t, prefix) {
const workspace = await mkdtemp(join(tmpdir(), prefix));
t.after(async () => rm(workspace, { recursive: true, force: true }));
const dataRoot = join(workspace, '.lynceuz');
return { dataRoot, storage: createStorage({ dataRoot }) };
}
async function readStoredJson(storage, relativePath) {
return JSON.parse(await readFile(await storage.resolve(relativePath), 'utf8'));
}
function urlJob(url) {
return compileJobSpec(parseArgv(['url', url, '--cache', 'off']));
}
test('crawl CLI compiles explicit scope, discovery and positive finite limits', () => {
const spec = compileJobSpec(parseArgv([
'crawl', TARGET,
'--include', '/docs/**',
'--include', '/news/*',
'--exclude', '/docs/private/**',
'--discover', 'sitemap,rss,api',
'--prefer-discovered-source',
'--max-pages', '7',
'--max-depth', '2',
'--max-time', '12.5',
'--max-bytes', '65536',
'--max-frontier', '20',
'--concurrency', '2',
'--delay', '0.1',
'--max-redirects', '3',
'--retries', '1',
'--data-root', '/tmp/lynceuz-p0/.lynceuz',
]));
assert.deepEqual(spec.scope.include, ['/docs/**', '/news/*']);
assert.deepEqual(spec.scope.exclude, ['/docs/private/**']);
assert.deepEqual(spec.discovery.sources, ['api', 'rss', 'sitemap']);
assert.equal(spec.discovery.preferDiscoveredSource, true);
assert.equal(spec.limits.maxPages, 7);
assert.equal(spec.limits.maxDepth, 2);
assert.equal(spec.limits.wallMs, 12_500);
assert.equal(spec.limits.maxTotalBytes, 65_536);
assert.equal(spec.limits.maxFrontier, 20);
assert.equal(spec.limits.concurrency, 2);
assert.equal(spec.limits.delayMs, 100);
assert.equal(spec.output.dataRoot, '/tmp/lynceuz-p0/.lynceuz');
for (const argv of [
['crawl', TARGET, '--max-pages', '0'],
['crawl', TARGET, '--concurrency', 'Infinity'],
['crawl', TARGET, '--include', '../escape/**'],
['crawl', TARGET, '--include', '/foo/[abc]'],
['url', TARGET, '--discover', 'sitemap'],
]) {
assert.throws(() => compileJobSpec(parseArgv(argv)), /invalid input/u);
}
});
test('goal acceptance rejects empty, JS-shell and wrong representations precisely', () => {
assert.deepEqual(
acceptRepresentation({ goal: 'markdown', representation: { kind: 'html', text: '', scriptCount: 0 } }),
{ kind: ATTEMPT_KIND.INADEQUATE, code: ATTEMPT_CODE.EMPTY, details: { reason: 'empty_main_content' } },
);
assert.deepEqual(
acceptRepresentation({ goal: 'markdown', representation: { kind: 'html', text: '', scriptCount: 2 } }),
{ kind: ATTEMPT_KIND.INADEQUATE, code: ATTEMPT_CODE.JS_SHELL, details: { reason: 'proven_js_shell' } },
);
assert.deepEqual(
acceptRepresentation({ goal: 'json', representation: { kind: 'binary', text: 'bytes' } }),
{ kind: ATTEMPT_KIND.INADEQUATE, code: ATTEMPT_CODE.WRONG_MIME, details: { reason: 'wrong_representation' } },
);
assert.equal(
acceptRepresentation({ goal: 'markdown', representation: { kind: 'html', text: 'Public facts' } }).kind,
ATTEMPT_KIND.SUCCESS,
);
assert.equal(
decideTransition(
{ kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.ROBOTS_DENIED },
{ hasNext: true },
).action,
'stop',
);
});
test('robots parser uses selected user-agent, longest match and Allow tie-break', () => {
const wildcard = parseRobots(DEFAULT_ROBOTS, { userAgent: 'OtherBot/1.0' });
assert.equal(wildcard.allows(`${P0_ORIGIN}/private/blocked`), false);
assert.equal(wildcard.allows(`${P0_ORIGIN}/private/public`), true);
assert.equal(wildcard.crawlDelayMs, 100);
assert.deepEqual(wildcard.sitemaps, [`${P0_ORIGIN}/sitemap.xml`]);
const parsed = parseRobots(`
User-agent: Lynceuz
Disallow: /same
Allow: /same
Disallow: /encoded/%2Fsecret$
`, { userAgent: 'Lynceuz/1.0' });
assert.equal(parsed.allows(`${P0_ORIGIN}/same`), true);
assert.equal(parsed.allows(`${P0_ORIGIN}/encoded/%2Fsecret`), false);
assert.equal(parsed.allows(`${P0_ORIGIN}/encoded/%2Fsecret/child`), true);
});
test('robots gate uses EgressGateway, caches at most 24h and fails closed', async () => {
const fixture = createP0SiteFixture();
const gate = createRobotsGate({
gateway: fixture.gateway,
clock: fixture.clock,
ttlMs: 48 * 60 * 60 * 1000,
maxBodyBytes: 32 * 1024,
maxRedirects: 2,
});
const allowed = await gate.check(`${P0_ORIGIN}/a`, { runId: 'robots-allow' });
const denied = await gate.check(`${P0_ORIGIN}/private/blocked`, { runId: 'robots-deny' });
assert.equal(allowed.kind, ATTEMPT_KIND.SUCCESS);
assert.equal(denied.kind, ATTEMPT_KIND.TERMINAL);
assert.equal(denied.code, ATTEMPT_CODE.ROBOTS_DENIED);
assert.equal(fixture.calls.requestPinned.length, 1, 'second decision must use bounded robots cache');
assert.equal(fixture.calls.requestPinned[0].purpose, 'robots');
assert.ok(gate.ttlMs <= 24 * 60 * 60 * 1000);
for (const robots of [
{ statusCode: 403, headers: {}, body: Buffer.from('denied') },
{ statusCode: 429, headers: { 'retry-after': '1' }, body: Buffer.from('slow') },
{ statusCode: 503, headers: {}, body: Buffer.from('down') },
new Error('unreachable'),
]) {
const blockedFixture = createP0SiteFixture({ robots });
const blockedGate = createRobotsGate({ gateway: blockedFixture.gateway });
const result = await blockedGate.check(`${P0_ORIGIN}/a`, { runId: 'robots-fail' });
assert.equal(result.kind, ATTEMPT_KIND.TERMINAL);
assert.equal(result.code, ATTEMPT_CODE.ROBOTS_DENIED);
}
const missingFixture = createP0SiteFixture({
robots: { statusCode: 404, headers: {}, body: Buffer.from('missing') },
});
assert.equal(
(await createRobotsGate({ gateway: missingFixture.gateway })
.check(`${P0_ORIGIN}/a`, { runId: 'robots-404' })).kind,
ATTEMPT_KIND.SUCCESS,
);
});
test('frontier preserves queries, strips fragments and never broadens exact origin', () => {
assert.equal(
canonicalFrontierKey(`${P0_ORIGIN}/a#one`, P0_ORIGIN),
`${P0_ORIGIN}/a`,
);
assert.notEqual(
canonicalFrontierKey(`${P0_ORIGIN}/query?a=1`, P0_ORIGIN),
canonicalFrontierKey(`${P0_ORIGIN}/query?a=2`, P0_ORIGIN),
);
assert.throws(
() => canonicalFrontierKey('https://off-origin.example.net/a', P0_ORIGIN),
/exact origin/u,
);
const frontier = createFrontier({
seedUrl: TARGET,
include: ['/**'],
exclude: ['/private/**'],
limits: { maxFrontier: 3, maxDepth: 2 },
});
assert.equal(frontier.enqueue(`${P0_ORIGIN}/a#x`, { depth: 1, source: TARGET }).accepted, true);
assert.equal(frontier.enqueue(`${P0_ORIGIN}/a#y`, { depth: 1, source: TARGET }).reason, 'duplicate');
assert.equal(frontier.enqueue(`${P0_ORIGIN}/private/x`, { depth: 1, source: TARGET }).reason, 'excluded');
assert.equal(frontier.enqueue('https://off-origin.example.net/x', { depth: 1, source: TARGET }).reason, 'off_origin');
});
test('bounded crawl checks robots before every page and reports partial ledger', async () => {
const visited = [];
const checked = [];
const links = new Map([
[TARGET, [`${P0_ORIGIN}/a`, `${P0_ORIGIN}/private/blocked`, 'https://off-origin.example.net/out']],
[`${P0_ORIGIN}/a`, [`${P0_ORIGIN}/b`, TARGET]],
[`${P0_ORIGIN}/b`, []],
]);
const result = await runBoundedCrawl({
job: { kind: 'crawl', target: { url: TARGET }, goal: 'markdown' },
context: {},
adapters: {},
robotsGate: {
async check(url) {
checked.push(url);
return url.includes('/private/')
? { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.ROBOTS_DENIED }
: { kind: ATTEMPT_KIND.SUCCESS, code: ATTEMPT_CODE.OK, crawlDelayMs: 0 };
},
},
runUrlPipeline: async ({ job }) => {
visited.push(job.target.url);
return {
outcome: { kind: ATTEMPT_KIND.SUCCESS, code: ATTEMPT_CODE.OK },
representation: { links: links.get(job.target.url) ?? [] },
usage: { wireBytes: 10, decodedBytes: 10, artifactBytes: 10 },
};
},
limits: {
maxPages: 2,
maxDepth: 3,
wallMs: 10_000,
maxTotalBytes: 1_000,
maxFrontier: 10,
concurrency: 1,
delayMs: 1,
},
include: ['/**'],
exclude: [],
clock: (() => { let value = 0; return () => value++; })(),
sleep: async () => {},
});
assert.equal(result.status, 'partial');
assert.deepEqual(visited, [TARGET, `${P0_ORIGIN}/a`]);
assert.equal(checked.includes(`${P0_ORIGIN}/private/blocked`), true);
assert.equal(checked.some((url) => url.includes('off-origin')), false);
assert.equal(result.accepted.length, 2);
assert.equal(result.unvisited.some((entry) => entry.url === `${P0_ORIGIN}/b`), true);
assert.equal(result.skipped.some((entry) => entry.reason === 'off_origin'), true);
assert.equal(result.blocked.some((entry) => entry.reason === ATTEMPT_CODE.ROBOTS_DENIED), true);
assert.equal(result.limit, 'max_pages');
});
test('URL pipeline stops on terminal native outcome without Python fallback', async (t) => {
const { storage } = await temporaryStorage(t, 'lynceuz-pipeline-terminal-');
const fixture = createP0SiteFixture({
graph: {
...DEFAULT_GRAPH,
'/denied': {
statusCode: 403,
headers: { 'content-type': 'text/html' },
body: Buffer.from('<main>denied</main>'),
},
},
});
const run = await storage.beginRun({ command: 'url', requested_url: `${P0_ORIGIN}/denied` });
let pythonCalls = 0;
const result = await runUrlPipeline({
job: urlJob(`${P0_ORIGIN}/denied`),
context: { storage, run, gateway: fixture.gateway, clock: fixture.clock, sleep: fixture.sleep },
adapters: {
python: {
async parseHtml() {
pythonCalls += 1;
throw new Error('terminal outcomes must not fall through');
},
},
},
});
assert.equal(result.outcome.kind, ATTEMPT_KIND.TERMINAL);
assert.equal(result.outcome.code, ATTEMPT_CODE.ACCESS_DENIED);
assert.equal(pythonCalls, 0);
assert.deepEqual(
fixture.calls.requestPinned.map(({ url }) => url),
[`${P0_ORIGIN}/denied`],
);
});
test('URL pipeline permits one local Python transform only after inadequate HTML', async (t) => {
const { storage } = await temporaryStorage(t, 'lynceuz-pipeline-inadequate-');
const fixture = createP0SiteFixture();
const run = await storage.beginRun({ command: 'url', requested_url: `${P0_ORIGIN}/empty` });
const pythonCalls = [];
const result = await runUrlPipeline({
job: urlJob(`${P0_ORIGIN}/empty`),
context: { storage, run, gateway: fixture.gateway, clock: fixture.clock, sleep: fixture.sleep },
adapters: {
python: {
id: 'python-parser',
networkModel: 'none',
async parseHtml(input) {
pythonCalls.push(input);
const markdown = '# Recovered locally\n';
const markdownRef = await storage.putObject(run, Buffer.from(markdown), {
role: 'derived',
media_type: 'text/markdown; charset=utf-8',
derived_from: input.sourceRef.hash,
});
return {
kind: ATTEMPT_KIND.SUCCESS,
code: ATTEMPT_CODE.OK,
value: {
title: 'Recovered locally',
canonicalCandidate: null,
text: 'Recovered locally',
markdown,
links: [],
metadata: {},
alternateCandidates: [],
jsonld: [],
artifacts: { markdown: markdownRef },
},
};
},
},
},
});
assert.equal(result.outcome.kind, ATTEMPT_KIND.SUCCESS);
assert.equal(result.representation.text, 'Recovered locally');
assert.equal(pythonCalls.length, 1);
assert.equal(pythonCalls[0].run.id, run.id);
assert.match(pythonCalls[0].sourceRef.hash, /^sha256:[0-9a-f]{64}$/u);
assert.equal(pythonCalls[0].baseUrl, `${P0_ORIGIN}/empty`);
assert.deepEqual(
fixture.calls.requestPinned.map(({ url }) => url),
[`${P0_ORIGIN}/empty`],
);
});
test('extract job commits valid JSON and records required-field miss', {
skip: OPTIONAL_PARSER_SKIP,
}, async (t) => {
const { storage } = await temporaryStorage(t, 'lynceuz-extract-integration-');
const fixture = createP0SiteFixture();
const adapter = createPythonTransformAdapter({ pythonPath: PYTHON, storage });
const successSchema = {
schema_version: 1,
fields: {
price: { source: 'css', selector: '.price', take: 'text', required: true, type: 'number' },
sku: { source: 'jsonld', path: ['sku'], required: true, type: 'string' },
},
};
const successJob = {
...compileJobSpec(parseArgv(['extract', `${P0_ORIGIN}/extract`, '--schema', 'fixture.json'])),
schema: successSchema,
};
const success = await runExtractJob(successJob, {
gateway: fixture.gateway,
storage,
pythonAdapter: adapter,
clock: fixture.clock,
sleep: fixture.sleep,
});
const successManifest = await readStoredJson(storage, success.manifest_path);
const successArtifact = await readStoredJson(storage, success.artifact_path);
assert.equal(success.status, 'ok');
assert.deepEqual(successArtifact, { price: 19.5, sku: 'sku-1' });
assert.equal(successManifest.status, 'ok');
assert.equal(successManifest.engine.id, 'python-parser');
assert.equal(successManifest.requested_url, `${P0_ORIGIN}/extract`);
assert.match(successManifest.source_hash, /^sha256:[0-9a-f]{64}$/u);
assert.match(successManifest.artifact_hash, /^sha256:[0-9a-f]{64}$/u);
assert.equal(successManifest.cost_money, 0);
let helperOutcome;
const trackedAdapter = {
...adapter,
async extractSchema(input) {
helperOutcome = await adapter.extractSchema(input);
return helperOutcome;
},
};
const missingSchema = {
schema_version: 1,
fields: {
sku: { source: 'css', selector: '.sku', take: 'text', required: true },
},
};
const missingJob = {
...compileJobSpec(parseArgv([
'extract', `${P0_ORIGIN}/extract-missing`, '--schema', 'fixture-missing.json',
])),
schema: missingSchema,
};
const missing = await runExtractJob(missingJob, {
gateway: fixture.gateway,
storage,
pythonAdapter: trackedAdapter,
clock: fixture.clock,
sleep: fixture.sleep,
});
const missingManifest = await readStoredJson(storage, missing.manifest_path);
assert.equal(helperOutcome.kind, ATTEMPT_KIND.INADEQUATE);
assert.equal(helperOutcome.code, ATTEMPT_CODE.PARSE_FAILED);
assert.equal(helperOutcome.details.reason, 'required_fields_missing');
assert.deepEqual(helperOutcome.details.missing, ['sku']);
assert.equal(missing.status, 'exhausted');
assert.equal(missingManifest.status, 'exhausted');
assert.equal(missingManifest.artifact_hash, null);
assert.match(missingManifest.source_hash, /^sha256:[0-9a-f]{64}$/u);
});
test('crawl job writes a truthful manifest and robots runs before page fetches', async (t) => {
const { storage } = await temporaryStorage(t, 'lynceuz-crawl-integration-');
const fixture = createP0SiteFixture();
const job = compileJobSpec(parseArgv([
'crawl', TARGET,
'--max-pages', '3',
'--max-depth', '2',
'--max-time', '10',
'--max-bytes', '65536',
'--max-frontier', '20',
'--concurrency', '1',
'--delay', '0.001',
]));
const result = await runCrawlJob(job, {
gateway: fixture.gateway,
storage,
clock: fixture.clock,
sleep: fixture.sleep,
});
const manifest = await readStoredJson(storage, result.manifest_path);
const artifact = await readStoredJson(storage, result.artifact_path);
const requests = fixture.calls.requestPinned;
assert.equal(result.status, 'partial');
assert.equal(result.code, 'partial');
assert.equal(requests[0].url, `${P0_ORIGIN}/robots.txt`);
assert.equal(requests[0].purpose, 'robots');
assert.equal(requests[1].url, TARGET);
assert.equal(requests.some(({ url }) => url === `${P0_ORIGIN}/private/blocked`), false);
assert.equal(requests.filter(({ purpose }) => purpose === 'robots').length, 1);
assert.equal(manifest.status, 'partial');
assert.equal(manifest.requested_url, TARGET);
assert.equal(manifest.source_hash, result.source_hash);
assert.equal(manifest.artifact_hash, result.source_hash);
assert.equal(manifest.cost_money, 0);
assert.equal(manifest.credits_used, 0);
assert.deepEqual(artifact, manifest.crawl);
assert.deepEqual(manifest.attempts, manifest.crawl.ledger);
assert.equal(manifest.crawl.limit, 'max_pages');
assert.equal(manifest.crawl.accepted.length, 3);
assert.equal(manifest.crawl.blocked.some(({ reason }) => reason === ATTEMPT_CODE.ROBOTS_DENIED), true);
assert.equal(manifest.crawl.skipped.some(({ reason }) => reason === 'off_origin'), true);
assert.equal(manifest.crawl.unvisited.length > 0, true);
for (const page of manifest.crawl.accepted) {
assert.match(page.source_hash, /^sha256:[0-9a-f]{64}$/u);
assert.equal(manifest.artifacts.some(({ hash }) => hash === page.source_hash), true);
assert.equal(manifest.evidence.some(({ url, hash }) => url === page.url && hash === page.source_hash), true);
}
});
+188
View File
@@ -0,0 +1,188 @@
import { once } from 'node:events';
import { createServer as createHttpServer } from 'node:http';
import { createServer as createTcpServer, connect as connectTcp } from 'node:net';
import { createSocket } from 'node:dgram';
import { Readable } from 'node:stream';
import { createEgressGateway } from '../../src/network.mjs';
export const SYNTHETIC_PUBLIC_ADDRESS = '93.184.216.34';
export const SYNTHETIC_PUBLIC_HOST = 'public.example.com';
export const REQUIRED_BROWSER_CHANNELS = Object.freeze([
'navigation',
'redirect',
'iframe',
'popup',
'worker',
'service_worker',
'websocket',
'webrtc_udp',
'webtransport',
'quic',
]);
function hostileHtml(tcpPort, udpPort) {
const privateHttp = `http://127.0.0.1:${tcpPort}`;
return `<!doctype html>
<html><body><main id="rendered">rendered through GuardProxy</main>
<script>
globalThis.__lynceuzChannels = ${JSON.stringify(REQUIRED_BROWSER_CHANNELS)};
const privateHttp = ${JSON.stringify(privateHttp)};
const udpPort = ${JSON.stringify(udpPort)};
fetch(privateHttp + '/fetch').catch(() => {});
const image = new Image(); image.src = privateHttp + '/image';
const frame = document.createElement('iframe'); frame.src = privateHttp + '/iframe'; document.body.append(frame);
try { window.open(privateHttp + '/popup'); } catch {}
try { new Worker('/hostile-worker.js'); } catch {}
navigator.serviceWorker?.register('/hostile-sw.js').catch(() => {});
try { new WebSocket('ws://127.0.0.1:${tcpPort}/socket'); } catch {}
try {
const peer = new RTCPeerConnection({iceServers:[{urls:'stun:127.0.0.1:' + udpPort}]});
peer.createDataChannel('probe'); peer.createOffer().then((offer) => peer.setLocalDescription(offer)).catch(() => {});
} catch {}
try { new WebTransport('https://127.0.0.1:${tcpPort}/transport'); } catch {}
</script></body></html>`;
}
async function listen(server) {
server.listen(0, '127.0.0.1');
await once(server, 'listening');
return server.address().port;
}
async function closeServer(server) {
if (!server.listening) return;
server.close();
await once(server, 'close');
}
function responseForPath(path, ports) {
if (path === '/redirect') {
return { statusCode: 302, headers: { location: `http://${SYNTHETIC_PUBLIC_HOST}/` }, body: '' };
}
if (path === '/hostile-worker.js' || path === '/hostile-sw.js') {
return { statusCode: 200, headers: { 'content-type': 'text/javascript' }, body: 'fetch("http://127.0.0.1:9/").catch(()=>{});' };
}
return {
statusCode: 200,
headers: { 'content-type': 'text/html; charset=utf-8' },
body: hostileHtml(ports.tcpCanary, ports.udpCanary),
};
}
export async function createBrowserHostileHarness() {
const counters = { public: 0, privateTcp: 0, privateUdp: 0 };
const sockets = new Set();
const tcpCanary = createTcpServer((socket) => {
counters.privateTcp += 1;
socket.destroy();
});
const tcpCanaryPort = await listen(tcpCanary);
const udpCanary = createSocket('udp4');
udpCanary.on('message', () => { counters.privateUdp += 1; });
udpCanary.bind(0, '127.0.0.1');
await once(udpCanary, 'listening');
const udpCanaryPort = udpCanary.address().port;
const publicServer = createHttpServer((request, response) => {
counters.public += 1;
const fixture = responseForPath(new URL(request.url, 'http://fixture').pathname, {
tcpCanary: tcpCanaryPort,
udpCanary: udpCanaryPort,
});
response.writeHead(fixture.statusCode, fixture.headers);
response.end(request.method === 'HEAD' ? undefined : fixture.body);
});
publicServer.on('connection', (socket) => {
sockets.add(socket);
socket.once('close', () => sockets.delete(socket));
});
const publicPort = await listen(publicServer);
const lookupAll = async () => [{ address: SYNTHETIC_PUBLIC_ADDRESS, family: 4 }];
const connectPinned = async ({ permit, signal }) => new Promise((resolve, reject) => {
const socket = connectTcp({ host: '127.0.0.1', port: publicPort });
const abort = () => socket.destroy(signal.reason ?? new Error('aborted'));
signal?.addEventListener('abort', abort, { once: true });
socket.once('connect', () => {
signal?.removeEventListener('abort', abort);
resolve({ socket, peerAddress: permit.selectedAddress });
});
socket.once('error', reject);
});
const requestPinned = async ({ permit, method }) => {
const path = new URL(permit.canonicalUrl).pathname;
const fixture = responseForPath(path, {
tcpCanary: tcpCanaryPort,
udpCanary: udpCanaryPort,
});
counters.public += 1;
return {
statusCode: fixture.statusCode,
headers: fixture.headers,
body: Readable.from(method === 'HEAD' ? [] : [fixture.body]),
peerAddress: permit.selectedAddress,
};
};
const gateway = createEgressGateway({ lookupAll, connectPinned, requestPinned });
return Object.freeze({
gateway,
counters,
publicUrl: `http://${SYNTHETIC_PUBLIC_HOST}/`,
tcpCanaryPort,
udpCanaryPort,
hostileHtml: hostileHtml(tcpCanaryPort, udpCanaryPort),
async close() {
for (const socket of sockets) socket.destroy();
udpCanary.close();
await Promise.all([closeServer(publicServer), closeServer(tcpCanary), once(udpCanary, 'close')]);
},
});
}
export async function requestViaGuardProxy(proxy, targetUrl, token, method = 'GET') {
const { host, port } = proxy;
return new Promise((resolve, reject) => {
const socket = connectTcp({ host, port });
const chunks = [];
socket.setTimeout(2_000, () => socket.destroy(new Error('proxy fixture timeout')));
socket.once('connect', () => {
const target = new URL(targetUrl);
socket.write(
`${method} ${target.href} HTTP/1.1\r\nHost: ${target.host}\r\n`
+ `Proxy-Authorization: Bearer ${token}\r\nConnection: close\r\n\r\n`,
);
});
socket.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
socket.once('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
socket.once('error', reject);
});
}
export async function connectViaGuardProxy(proxy, token) {
return new Promise((resolve, reject) => {
const socket = connectTcp({ host: proxy.host, port: proxy.port });
const chunks = [];
let tunnelReady = false;
socket.setTimeout(2_000, () => socket.destroy(new Error('proxy tunnel fixture timeout')));
socket.once('connect', () => {
socket.write(
`CONNECT ${SYNTHETIC_PUBLIC_HOST}:443 HTTP/1.1\r\n`
+ `Host: ${SYNTHETIC_PUBLIC_HOST}:443\r\n`
+ `Proxy-Authorization: Bearer ${token}\r\n\r\n`,
);
});
socket.on('data', (chunk) => {
chunks.push(Buffer.from(chunk));
const current = Buffer.concat(chunks).toString('utf8');
if (!tunnelReady && current.includes('\r\n\r\n')) {
tunnelReady = true;
socket.write(`GET / HTTP/1.1\r\nHost: ${SYNTHETIC_PUBLIC_HOST}\r\nConnection: close\r\n\r\n`);
}
});
socket.once('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
socket.once('error', reject);
});
}
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Offline TCP/UDP canary used by the browser containment proof."""
from __future__ import annotations
import json
import socket
import sys
MAX_INPUT_BYTES = 16 * 1024
TIMEOUT_SECONDS = 0.75
def attempt_tcp(host: str, port: int, request: bytes | None = None) -> bool:
try:
with socket.create_connection((host, port), timeout=TIMEOUT_SECONDS) as connection:
if request:
connection.sendall(request)
connection.recv(128)
return True
except OSError:
return False
def attempt_udp(host: str, port: int) -> bool:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(TIMEOUT_SECONDS)
try:
sock.sendto(b"lynceuz-containment-canary", (host, port))
return True
except OSError:
return False
finally:
sock.close()
def main() -> int:
raw = sys.stdin.buffer.readline(MAX_INPUT_BYTES + 1)
if not raw or len(raw) > MAX_INPUT_BYTES or sys.stdin.buffer.read(1):
return 2
try:
request = json.loads(raw)
if set(request) != {
"version", "proxy_host", "proxy_port", "proxy_token",
"tcp_host", "tcp_port", "udp_host", "udp_port",
}:
return 2
if request["version"] != 1:
return 2
ports = [request["proxy_port"], request["tcp_port"], request["udp_port"]]
if any(not isinstance(port, int) or not 1 <= port <= 65535 for port in ports):
return 2
for key in ("proxy_host", "proxy_token", "tcp_host", "udp_host"):
if not isinstance(request[key], str) or not request[key]:
return 2
except (json.JSONDecodeError, TypeError, ValueError):
return 2
proxy_request = (
"HEAD http://public.example.com/probe HTTP/1.1\r\n"
"Host: public.example.com\r\n"
f"Proxy-Authorization: Bearer {request['proxy_token']}\r\n"
"Connection: close\r\n\r\n"
).encode("ascii")
result = {
"version": 1,
"proxy_tcp": attempt_tcp(
request["proxy_host"], request["proxy_port"], proxy_request
),
"direct_tcp": attempt_tcp(request["tcp_host"], request["tcp_port"]),
"direct_udp_send": attempt_udp(request["udp_host"], request["udp_port"]),
}
sys.stdout.write(json.dumps(result, separators=(",", ":")) + "\n")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+29
View File
@@ -0,0 +1,29 @@
export function capability(overrides = {}) {
return {
id: 'native',
version: 'test-1',
state: 'ready',
reason: 'fixture_ready',
automatic: true,
commands: ['url'],
cost: 'local-zero',
price: 0,
networkModel: 'core-http',
...overrides,
};
}
export function scriptedAdapter(outcomes) {
const script = [...outcomes];
const calls = [];
return {
calls,
async run(job) {
calls.push(job);
if (script.length === 0) throw new Error('script exhausted');
const next = script.shift();
if (next instanceof Error) throw next;
return typeof next === 'function' ? next(job, calls.length) : next;
},
};
}
+37
View File
@@ -0,0 +1,37 @@
{
"allow": [
{ "input": "https://example.com/path#evidence", "canonical": "https://example.com/path" },
{ "input": "http://93.184.216.34/", "canonical": "http://93.184.216.34/" },
{ "input": "https://bücher.de/", "canonical": "https://xn--bcher-kva.de/" },
{ "input": "https://example.com:443/a", "canonical": "https://example.com/a" }
],
"deny": [
"file:///etc/passwd",
"data:text/plain,no",
"javascript:alert(1)",
"ftp://example.com/file",
"https://user@example.com/",
"https://user:password@example.com/",
"https://example.com:8080/",
"https://example.com/?access_token=secret-value",
"https://example.com/?Api-Key=secret-value",
"https://example.com/?client_secret=secret-value",
"https://example.com\\@127.0.0.1/",
"https://example.com%2f@127.0.0.1/",
"https://example.com/%0d%0aHost:evil.test",
"http://localhost/",
"http://localhost./",
"http://service.internal/",
"http://example.test/",
"http://127.1/",
"http://2130706433/",
"http://0x7f000001/",
"http://017700000001/",
"http://169.254.169.254/latest/meta-data/",
"http://[::1]/",
"http://[fc00::1]/",
"http://[fe80::1]/",
"http://[::ffff:127.0.0.1]/",
"http://[fe80::1%25en0]/"
]
}
+103
View File
@@ -0,0 +1,103 @@
// Deterministic interruption worker for evals/recovery.test.mjs.
//
// Reaches a fixed milestone (beginRun -> putObject -> appendAttempt), confirms
// it via IPC, then keeps the event loop alive and waits for the parent to send
// a real signal:
// mode=crash -> waits for a real SIGKILL strictly BEFORE commitManifest, so
// the on-disk run stays incomplete (uses only shipped storage APIs).
// mode=signal -> installs the future core interruption guard; a real
// SIGINT/SIGTERM must commit ONE interrupted manifest and exit
// with the mapped code.
// mode=timeout -> the guard's own wall deadline fires and commits an
// interrupted (reason=timeout) manifest, exit 124.
//
// No live network, no sleep-based readiness: the parent waits on the IPC
// milestone (or an early exit), never on a timer.
import { createStorage } from '../../src/storage.mjs';
import * as core from '../../src/core.mjs';
const FIXED_TIME = '2026-08-26T12:15:40.123Z';
const REQUESTED_URL = 'https://example.com/interrupted';
const EVIDENCE = Buffer.from('interrupted public evidence');
function buildInterruptedManifest(run, source, termination) {
return {
schema_version: 1,
run_id: run.id,
status: 'interrupted',
requested_url: REQUESTED_URL,
effective_url: REQUESTED_URL,
requested_format: 'markdown',
format: 'markdown',
alternatives: [],
fetched_at: null,
served_at: FIXED_TIME,
revalidated_at: null,
engine: { id: 'native', version: '1' },
policy: { version: '1', network: 'public-only', auth: 'none', money_budget: 0 },
attempts: [{
type: 'attempt_finished', at: FIXED_TIME, outcome: 'ok', source_hash: source.hash,
}],
source_hash: source.hash,
artifact_hash: null,
artifact_path: null,
artifacts: [source],
evidence: [{ url: REQUESTED_URL, hash: source.hash, status: 'source_captured' }],
warnings: [],
cost_money: 0,
credits_used: 0,
termination,
};
}
function keepAlive() {
// Ref'd timer keeps the process alive until a signal or the guard exits it.
// Not a readiness sleep: it never fires meaningfully.
setInterval(() => {}, 1 << 30);
}
async function main() {
const config = JSON.parse(process.argv[2] ?? '{}');
const clock = () => new Date(FIXED_TIME);
const storage = createStorage({ dataRoot: config.dataRoot, clock });
const run = await storage.beginRun({
schema_version: 1,
command: 'url',
requested_url: REQUESTED_URL,
method: 'GET',
format: 'markdown',
cache: 'use',
});
const source = await storage.putObject(run, EVIDENCE, {
role: 'raw', media_type: 'text/plain', derived_from: null,
});
await storage.appendAttempt(run, {
type: 'attempt_finished', at: FIXED_TIME, outcome: 'ok', source_hash: source.hash,
});
const milestone = { ready: true, runId: run.id, sourceHash: source.hash, dataRoot: storage.dataRoot };
if (config.mode === 'crash') {
process.send?.(milestone);
keepAlive();
return;
}
// signal / timeout modes exercise the future core interruption guard.
const guard = core.createInterruptionGuard({
storage,
run,
wallMs: config.mode === 'timeout' ? (config.wallMs ?? 50) : null,
buildInterruptedManifest: (termination) => buildInterruptedManifest(run, source, termination),
});
guard.install();
process.send?.(milestone);
keepAlive();
}
main().catch((error) => {
process.stderr.write(`${error?.stack ?? error}\n`);
process.exit(1);
});
+194
View File
@@ -0,0 +1,194 @@
import { Readable } from 'node:stream';
import { brotliCompressSync, deflateSync, gzipSync } from 'node:zlib';
import { createEgressGateway } from '../../src/network.mjs';
export const FIXTURE_ADDRESS = '93.184.216.34';
export const FIXTURE_URL = 'https://public.example.com/source';
const bytes = (value) => (Buffer.isBuffer(value) ? value : Buffer.from(value));
export const RESPONSE_FIXTURES = Object.freeze({
html: Object.freeze({
statusCode: 200,
headers: Object.freeze({
'content-type': 'text/html; charset=utf-8',
etag: '"html-v1"',
'last-modified': 'Wed, 26 Aug 2026 12:00:00 GMT',
}),
body: Buffer.from('<!doctype html><html><head><title>Eyes</title></head><body><h1>Lynceuz</h1><p>Sees public facts.</p><a href="/next">Next</a></body></html>'),
}),
json: Object.freeze({
statusCode: 200,
headers: Object.freeze({ 'content-type': 'application/json' }),
body: Buffer.from('{"name":"Lynceuz","free":true}'),
}),
malformedJson: Object.freeze({
statusCode: 200,
headers: Object.freeze({ 'content-type': 'application/json' }),
body: Buffer.from('{"broken":'),
}),
xml: Object.freeze({
statusCode: 200,
headers: Object.freeze({ 'content-type': 'application/xml' }),
body: Buffer.from('<?xml version="1.0"?><records><record id="1"/></records>'),
}),
rss: Object.freeze({
statusCode: 200,
headers: Object.freeze({ 'content-type': 'application/rss+xml' }),
body: Buffer.from('<?xml version="1.0"?><rss version="2.0"><channel><title>News</title></channel></rss>'),
}),
atom: Object.freeze({
statusCode: 200,
headers: Object.freeze({ 'content-type': 'application/atom+xml' }),
body: Buffer.from('<?xml version="1.0"?><feed xmlns="http://www.w3.org/2005/Atom"><title>News</title></feed>'),
}),
sitemap: Object.freeze({
statusCode: 200,
headers: Object.freeze({ 'content-type': 'application/xml' }),
body: Buffer.from('<?xml version="1.0"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://public.example.com/a</loc></url></urlset>'),
}),
binary: Object.freeze({
statusCode: 200,
headers: Object.freeze({ 'content-type': 'application/octet-stream' }),
body: Buffer.from([0, 1, 2, 3, 255, 0, 17]),
}),
redirect: Object.freeze({
statusCode: 302,
headers: Object.freeze({ location: '/final' }),
body: Buffer.alloc(0),
}),
forbidden: Object.freeze({ statusCode: 403, headers: Object.freeze({}), body: Buffer.from('no') }),
notFound: Object.freeze({ statusCode: 404, headers: Object.freeze({}), body: Buffer.from('missing') }),
retryAfter: Object.freeze({
statusCode: 429,
headers: Object.freeze({ 'retry-after': '120' }),
body: Buffer.from('slow down'),
}),
unavailable: Object.freeze({ statusCode: 503, headers: Object.freeze({}), body: Buffer.from('later') }),
notModified: Object.freeze({
statusCode: 304,
headers: Object.freeze({ etag: '"html-v1"' }),
body: Buffer.alloc(0),
}),
});
export function encodedResponse(encoding, value, overrides = {}) {
const source = bytes(value);
const encoders = { gzip: gzipSync, deflate: deflateSync, br: brotliCompressSync };
if (!encoders[encoding]) throw new TypeError('unsupported fixture encoding');
return {
statusCode: 200,
headers: { 'content-type': 'text/plain', 'content-encoding': encoding },
body: encoders[encoding](source),
...overrides,
};
}
export function createFakeClock(startMs = Date.parse('2026-08-26T12:00:00.000Z')) {
let currentMs = startMs;
const sleeps = [];
return Object.freeze({
now: () => currentMs,
date: () => new Date(currentMs),
advance: (milliseconds) => { currentMs += milliseconds; },
sleep: async (milliseconds) => {
sleeps.push(milliseconds);
currentMs += milliseconds;
},
sleeps,
});
}
function cloneResponse(response, peerAddress) {
return {
statusCode: response.statusCode,
headers: { ...(response.headers ?? {}) },
body: Readable.from([bytes(response.body ?? Buffer.alloc(0))]),
peerAddress: response.peerAddress ?? peerAddress,
};
}
export function createNativeFixture({
responses = [RESPONSE_FIXTURES.html],
address = FIXTURE_ADDRESS,
clock: suppliedClock,
startMs,
} = {}) {
const clock = suppliedClock ?? createFakeClock(startMs);
const queue = [...responses];
const calls = { lookupAll: [], requestPinned: [], connectPinned: [], sleeps: clock.sleeps };
const lookupAll = async (hostname, options = {}) => {
calls.lookupAll.push({ hostname, signal: options.signal ?? null });
return [{ address, family: address.includes(':') ? 6 : 4 }];
};
const requestPinned = async (request) => {
calls.requestPinned.push({ ...request, headers: { ...(request.headers ?? {}) } });
if (request.signal?.aborted) throw request.signal.reason ?? new Error('aborted');
if (queue.length === 0) throw new Error('fixture response queue exhausted');
const scripted = queue.shift();
if (scripted instanceof Error) throw scripted;
const response = typeof scripted === 'function' ? await scripted(request, calls) : scripted;
if (response instanceof Error) throw response;
return cloneResponse(response, address);
};
const connectPinned = async (request) => {
calls.connectPinned.push(request);
throw new Error('fixture tunnel is not available');
};
const gateway = createEgressGateway({ lookupAll, requestPinned, connectPinned, now: clock.now });
return Object.freeze({
gateway,
lookupAll,
requestPinned,
connectPinned,
calls,
clock: clock.now,
sleep: clock.sleep,
advance: clock.advance,
fakeClock: clock,
queue,
});
}
export function baseUrlJob(overrides = {}) {
return {
schemaVersion: 1,
kind: 'url',
target: { url: FIXTURE_URL },
goal: 'markdown',
limits: {
wallMs: 10_000,
perAttemptMs: 2_000,
maxBytesPerPage: 64 * 1024,
maxTotalBytes: 256 * 1024,
maxPages: 1,
maxDepth: 1,
concurrency: 1,
maxRedirects: 3,
retriesPerAdapter: 2,
maxRetryAfterMs: 1_500,
maxWireBytes: 64 * 1024,
maxDecodedBytes: 128 * 1024,
maxArtifactBytes: 128 * 1024,
},
policy: {
network: 'public-only',
auth: 'none',
moneyBudget: 0,
allowFreeCloud: false,
allowRendered: false,
respectRobots: true,
},
output: {
json: true,
format: 'markdown',
path: null,
dataRoot: null,
},
cache: { mode: 'use', ttlMs: 60_000 },
routing: { explain: false, forcedEngine: null },
...overrides,
};
}
+66
View File
@@ -0,0 +1,66 @@
import childProcess from 'node:child_process';
import dns from 'node:dns';
import dnsPromises from 'node:dns/promises';
import http from 'node:http';
import https from 'node:https';
import net from 'node:net';
import tls from 'node:tls';
import { syncBuiltinESMExports } from 'node:module';
export function createNoNetworkPorts(overrides = {}) {
const counters = {
lookupAll: 0,
connectPinned: 0,
requestPinned: 0,
spawn: 0,
};
const port = (name) => async (...args) => {
counters[name] += 1;
if (overrides[name]) return overrides[name](...args);
throw new Error(`forbidden test port called: ${name}`);
};
return {
counters,
lookupAll: port('lookupAll'),
connectPinned: port('connectPinned'),
requestPinned: port('requestPinned'),
spawn: port('spawn'),
};
}
export function installNetworkTripwire() {
if (globalThis.__lynceuzNetworkTripwireInstalled) return;
globalThis.__lynceuzNetworkTripwireInstalled = true;
const deny = (name) => {
throw new Error(`network tripwire: ${name}`);
};
const denyCallback = (name) => (...args) => {
const callback = args.findLast((value) => typeof value === 'function');
const error = new Error(`network tripwire: ${name}`);
if (callback) return queueMicrotask(() => callback(error));
throw error;
};
globalThis.fetch = async () => deny('fetch');
dns.lookup = denyCallback('dns.lookup');
dns.resolve = denyCallback('dns.resolve');
dnsPromises.lookup = async () => deny('dns.promises.lookup');
dnsPromises.resolve = async () => deny('dns.promises.resolve');
http.request = () => deny('http.request');
http.get = () => deny('http.get');
https.request = () => deny('https.request');
https.get = () => deny('https.get');
net.connect = () => deny('net.connect');
net.createConnection = () => deny('net.createConnection');
tls.connect = () => deny('tls.connect');
childProcess.spawn = () => deny('child_process.spawn');
childProcess.exec = () => deny('child_process.exec');
childProcess.execFile = () => deny('child_process.execFile');
childProcess.fork = () => deny('child_process.fork');
syncBuiltinESMExports();
}
if (process.env.LYNCEUZ_FORBID_NETWORK === '1') installNetworkTripwire();
+159
View File
@@ -0,0 +1,159 @@
import { Readable } from 'node:stream';
import { createEgressGateway } from '../../src/network.mjs';
export const P0_ORIGIN = 'https://public.example.com';
export const P0_ADDRESS = '93.184.216.34';
const html = (body, head = '') => Buffer.from(`<!doctype html><html><head>${head}</head><body>${body}</body></html>`);
const DEFAULT_ROBOTS = `User-agent: *
Disallow: /private
Allow: /private/public
Crawl-delay: 0.1
Sitemap: ${P0_ORIGIN}/sitemap.xml
`;
const DEFAULT_GRAPH = Object.freeze({
'/': {
statusCode: 200,
headers: { 'content-type': 'text/html; charset=utf-8' },
body: html(
'<main><h1>Root</h1><p>Public facts.</p><a href="/a">A</a><a href="/private/blocked">Private</a><a href="/query?a=1#one">Query</a><a href="https://off-origin.example.net/out">Off</a></main>',
'<title>Root</title><link rel="alternate" type="application/rss+xml" href="/feed.xml">',
),
},
'/a': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html('<main><h1>A</h1><a href="/b">B</a><a href="/">Cycle</a></main>', '<link rel="canonical" href="/a#alias">'),
},
'/b': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html('<main><h1>B</h1><p>Last page.</p></main>'),
},
'/query?a=1': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html('<main><h1>Query one</h1></main>'),
},
'/query?a=2': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html('<main><h1>Query two</h1></main>'),
},
'/private/blocked': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html('<main>Must never be fetched</main>'),
},
'/private/public': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html('<main>Allowed exception</main>'),
},
'/empty': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html(''),
},
'/shell': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html('<div id="app"></div><script src="/app.js"></script>'),
},
'/extract': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html(
'<main><h1>Product</h1><span class="price">19.5</span></main>',
'<title>Product</title><script type="application/ld+json">{"@type":"Product","sku":"sku-1","name":"Lens"}</script>',
),
},
'/extract-missing': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: html('<main><h1>No SKU</h1></main>'),
},
'/sitemap.xml': {
statusCode: 200,
headers: { 'content-type': 'application/xml' },
body: Buffer.from(`<?xml version="1.0"?><urlset><url><loc>${P0_ORIGIN}/a</loc></url><url><loc>${P0_ORIGIN}/private/blocked</loc></url></urlset>`),
},
'/feed.xml': {
statusCode: 200,
headers: { 'content-type': 'application/rss+xml' },
body: Buffer.from(`<?xml version="1.0"?><rss><channel><link>${P0_ORIGIN}/a</link></channel></rss>`),
},
'/api.json': {
statusCode: 200,
headers: { 'content-type': 'application/json' },
body: Buffer.from(`{"next":"${P0_ORIGIN}/b"}`),
},
'/redirect-private': {
statusCode: 302,
headers: { location: 'http://127.0.0.1/private' },
body: Buffer.alloc(0),
},
});
function keyFor(value) {
const url = new URL(value);
return `${url.pathname}${url.search}`;
}
function cloneResponse(response) {
return {
statusCode: response.statusCode,
headers: { ...(response.headers ?? {}) },
body: Readable.from([Buffer.from(response.body ?? '')]),
peerAddress: P0_ADDRESS,
};
}
export function createP0SiteFixture({
robots = { statusCode: 200, headers: { 'content-type': 'text/plain' }, body: Buffer.from(DEFAULT_ROBOTS) },
graph = DEFAULT_GRAPH,
startMs = Date.parse('2026-08-26T12:00:00.000Z'),
} = {}) {
let nowMs = startMs;
const calls = { lookupAll: [], requestPinned: [], sleeps: [] };
const lookupAll = async (hostname, options = {}) => {
calls.lookupAll.push({ hostname, signal: options.signal ?? null });
return [{ address: P0_ADDRESS, family: 4 }];
};
const requestPinned = async (request) => {
calls.requestPinned.push({
url: request.permit.canonicalUrl,
purpose: request.permit.purpose,
headers: { ...(request.headers ?? {}) },
});
const key = keyFor(request.permit.canonicalUrl);
const selected = key === '/robots.txt' ? robots : graph[key];
if (selected instanceof Error) throw selected;
return cloneResponse(selected ?? {
statusCode: 404,
headers: { 'content-type': 'text/plain' },
body: Buffer.from('missing'),
});
};
const gateway = createEgressGateway({
lookupAll,
requestPinned,
connectPinned: async () => { throw new Error('fixture tunnel disabled'); },
now: () => nowMs,
});
return Object.freeze({
gateway,
calls,
clock: () => nowMs,
sleep: async (milliseconds) => {
calls.sleeps.push(milliseconds);
nowMs += milliseconds;
},
advance: (milliseconds) => { nowMs += milliseconds; },
});
}
export { DEFAULT_GRAPH, DEFAULT_ROBOTS };
+82
View File
@@ -0,0 +1,82 @@
{
"kind": "lynceuz_eval_baseline",
"schema_version": 1,
"files": [
{
"path": "evals/.gitkeep",
"sha256": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
{
"path": "evals/browser-hostile.test.mjs",
"sha256": "sha256:d219e51ccc2f1895736fcc36010a445db6d72e7ff732d6b98bb240da00907899"
},
{
"path": "evals/cli-native.test.mjs",
"sha256": "sha256:f2ea4cf3dac1afa0b01f273c49e6cb008037eb77e6bc191e493cd921fd97b9ac"
},
{
"path": "evals/cli.test.mjs",
"sha256": "sha256:1644e8a84866bfae1d05c6e4dd69631d342f579c943974733074856c38521519"
},
{
"path": "evals/extract-crawl.test.mjs",
"sha256": "sha256:953bc0aa0cdf3bc54b32d04007e023c80d964102f75a9cc6a1a0ade18f23a12f"
},
{
"path": "evals/fixtures/browser-hostile.mjs",
"sha256": "sha256:1bec9e4739f366f5f91401cbc784e3b6411e139960bdb3f215404428925b0e14"
},
{
"path": "evals/fixtures/direct-egress-probe.py",
"sha256": "sha256:7db832c54c7fc7810579ce102dad8ef8eb05bcee3b78b3a98dd772df14b46f2f"
},
{
"path": "evals/fixtures/fake-adapters.mjs",
"sha256": "sha256:143d77a613c3918a02ba92652c438efd4bcf72e88393ceb4c083fdf15989a2cd"
},
{
"path": "evals/fixtures/hostile-urls.json",
"sha256": "sha256:28128b1faff53c22bc73b27324cd5cc77eb644a1618b9bd00c02414a674f77d4"
},
{
"path": "evals/fixtures/native-http.mjs",
"sha256": "sha256:3fc3cfc8b9ebee33d2ddd200d2c4ab6f66d9b99133985e53d336fd6e71b828ee"
},
{
"path": "evals/fixtures/no-network.mjs",
"sha256": "sha256:acc0303a75e40c2db730c5501531234a2c7eb3b5fab142dad1a6777195da27b2"
},
{
"path": "evals/fixtures/p0-site.mjs",
"sha256": "sha256:00ccb5798e319f514ee2f9a36e2765f634cb9e30b202c0697fb4c38d5cdc49ad"
},
{
"path": "evals/local-fallback-process.test.mjs",
"sha256": "sha256:aa8188ec3568fb8957badd46508a2948e18bd56b15fa355f668c3e867b341772"
},
{
"path": "evals/native-url.test.mjs",
"sha256": "sha256:9011e3df5d7dc4347ace4aaa2adebf1b05d575675fc7e06d7a74d1a1cbba3284"
},
{
"path": "evals/p0-acceptance.test.mjs",
"sha256": "sha256:a6190c4dcaff155b8d4fd201e0b3d804450fd1175aafec5717cbf914eef8b421"
},
{
"path": "evals/policy.test.mjs",
"sha256": "sha256:25751538e547ea6b87ea3a23bbee8c50a89004035b45b2ecdd725cafc8d77e39"
},
{
"path": "evals/router.test.mjs",
"sha256": "sha256:63eb59858f780ab67eb088894be341d08c8f1172fbcbd7876a63ef3fdb8845e3"
},
{
"path": "evals/search-cloud.test.mjs",
"sha256": "sha256:b218200d526a51e57984b479752b72a53390b60f4451005b2818571ccf6bfafc"
},
{
"path": "evals/storage.test.mjs",
"sha256": "sha256:8552c2a44ed1ad056f6daa4c48492067af2cceb800330a969adf8c40d7332681"
}
]
}
+46
View File
@@ -0,0 +1,46 @@
{
"kind": "lynceuz_p1_suite_manifest",
"schema_version": 1,
"baseline_manifest": {
"path": "evals/fixtures/p0-suite-hashes.json",
"sha256": "sha256:04a2b985fd0b98f49f19b9ac5781c3386f1c249e2fd196cb2927d924eefd3b92"
},
"files": [
{
"path": "evals/cloud.test.mjs",
"sha256": "sha256:636926aa663551f922d4d44972e6dcc542cfdc394c774ac8b7e5c3776c6a2cab",
"role": "cloud-contract",
"run_by_release_gate": true
},
{
"path": "evals/fixtures/interruption-worker.mjs",
"sha256": "sha256:7d1f3726539cb63166d669e9b4a4090986513be2659b29b6479a25de1be3261b",
"role": "recovery-fixture",
"run_by_release_gate": false
},
{
"path": "evals/p1-release.test.mjs",
"sha256": "sha256:284cdd160929499ee76cef20185e3f674b7fc1e6d33720672ca701e1bbdfd398",
"role": "gate-contract",
"run_by_release_gate": false
},
{
"path": "evals/recovery.test.mjs",
"sha256": "sha256:e5e51cf43c5025feadd7297274784cbc69494d26c036c50a4ddb9c6cf40aed95",
"role": "recovery-contract",
"run_by_release_gate": true
},
{
"path": "evals/search-budget.test.mjs",
"sha256": "sha256:3c9ac908913e3bc00155b4d83e94cadfffdb45c946d31cc3f80542c2f54d36ae",
"role": "search-budget-contract",
"run_by_release_gate": true
},
{
"path": "evals/search-cloud.test.mjs",
"sha256": "sha256:b218200d526a51e57984b479752b72a53390b60f4451005b2818571ccf6bfafc",
"role": "search-contract",
"run_by_release_gate": true
}
]
}
+256
View File
@@ -0,0 +1,256 @@
import { once } from 'node:events';
import { createSocket } from 'node:dgram';
import { connect, createServer } from 'node:net';
import { networkInterfaces } from 'node:os';
const LOOPBACK = '127.0.0.1';
const MAX_MESSAGE_BYTES = 256;
export const CANARY_PROTOCOLS = Object.freeze({
proxy_tcp: Object.freeze({ request: 'LYNCEUZ_PROXY_TCP?', response: 'LYNCEUZ_PROXY_TCP_OK' }),
direct_tcp: Object.freeze({ request: 'LYNCEUZ_DIRECT_TCP?', response: 'LYNCEUZ_DIRECT_TCP_LEAK' }),
udp: Object.freeze({ request: 'LYNCEUZ_UDP?', response: 'LYNCEUZ_UDP_LEAK' }),
quic: Object.freeze({ request: 'LYNCEUZ_QUIC_INITIAL?', response: 'LYNCEUZ_QUIC_RETRY_LEAK' }),
});
function selectNonLoopbackIpv4(interfaces = networkInterfaces()) {
const candidates = Object.entries(interfaces)
.sort(([left], [right]) => left.localeCompare(right))
.flatMap(([name, addresses]) => (addresses ?? []).map((address) => ({ name, ...address })))
.filter(({ address, family, internal }) => (
(family === 'IPv4' || family === 4)
&& internal === false
&& !address.startsWith('127.')
&& address !== '0.0.0.0'
));
const routed = candidates.find(({ netmask }) => netmask !== '255.255.255.255');
const selected = routed ?? candidates[0];
if (!selected) throw new Error('local_non_loopback_ipv4_missing');
return selected.address;
}
async function closeTcp(server, sockets) {
for (const socket of sockets) socket.destroy();
if (!server.listening) return;
const closed = once(server, 'close');
server.close();
await closed;
}
async function createTcpResponder(host, protocol, port = 0) {
const sockets = new Set();
const stats = { requests: 0, responses: 0 };
const server = createServer((socket) => {
sockets.add(socket);
socket.once('close', () => sockets.delete(socket));
const chunks = [];
let bytes = 0;
socket.on('data', (chunk) => {
bytes += chunk.length;
if (bytes > MAX_MESSAGE_BYTES) {
socket.destroy();
return;
}
chunks.push(Buffer.from(chunk));
const request = Buffer.concat(chunks).toString('utf8');
if (request === protocol.request) {
stats.requests += 1;
stats.responses += 1;
socket.end(protocol.response);
}
});
});
server.listen(port, host);
await once(server, 'listening');
const address = server.address();
if (!address || typeof address === 'string') throw new Error('tcp_responder_address_missing');
return {
endpoint: Object.freeze({ host, port: address.port }),
stats,
close: () => closeTcp(server, sockets),
};
}
async function createUdpResponder(host, protocol) {
const socket = createSocket('udp4');
const stats = { requests: 0, responses: 0 };
socket.on('message', (message, peer) => {
if (message.length > MAX_MESSAGE_BYTES || message.toString('utf8') !== protocol.request) return;
stats.requests += 1;
socket.send(protocol.response, peer.port, peer.address, (error) => {
if (!error) stats.responses += 1;
});
});
socket.bind(0, host);
await once(socket, 'listening');
const address = socket.address();
return {
endpoint: Object.freeze({ host, port: address.port }),
stats,
async close() {
const closed = once(socket, 'close');
socket.close();
await closed;
},
};
}
function observation(channel, operationSucceeded, response) {
const expected = CANARY_PROTOCOLS[channel].response;
return Object.freeze({
channel,
operation_succeeded: operationSucceeded,
response,
response_confirmed: response === expected,
});
}
export async function exchangeTcp(channel, endpoint, { timeoutMs = 250 } = {}) {
const protocol = CANARY_PROTOCOLS[channel];
return new Promise((resolve) => {
let operationSucceeded = false;
let settled = false;
const chunks = [];
const socket = connect(endpoint);
const finish = (response = null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
socket.destroy();
resolve(observation(channel, operationSucceeded, response));
};
const timer = setTimeout(() => finish(), timeoutMs);
socket.once('connect', () => {
operationSucceeded = true;
socket.write(protocol.request);
});
socket.on('data', (chunk) => {
if (Buffer.concat(chunks).length + chunk.length > MAX_MESSAGE_BYTES) return finish();
chunks.push(Buffer.from(chunk));
});
socket.once('end', () => finish(Buffer.concat(chunks).toString('utf8')));
socket.once('error', () => finish());
});
}
export async function exchangeUdp(channel, endpoint, { timeoutMs = 250 } = {}) {
const protocol = CANARY_PROTOCOLS[channel];
return new Promise((resolve) => {
const socket = createSocket('udp4');
let operationSucceeded = false;
let settled = false;
const finish = (response = null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
socket.close();
resolve(observation(channel, operationSucceeded, response));
};
const timer = setTimeout(() => finish(), timeoutMs);
socket.once('error', () => finish());
socket.on('message', (message, peer) => {
if (peer.port === endpoint.port && message.length <= MAX_MESSAGE_BYTES) {
finish(message.toString('utf8'));
}
});
socket.send(protocol.request, endpoint.port, endpoint.host, (error) => {
operationSucceeded = !error;
if (error) finish();
});
});
}
export function evaluateCanaryObservations(observations, { negativeControl = false } = {}) {
const proxyAllowed = observations.proxy_tcp?.response_confirmed === true;
const directChannels = ['direct_tcp', 'udp', 'quic'];
const confirmed = directChannels.filter((channel) => observations[channel]?.response_confirmed === true);
if (negativeControl) {
const detectedEveryChannel = confirmed.length === directChannels.length;
return Object.freeze({
passed: false,
status: detectedEveryChannel ? 'red' : 'invalid_negative_control',
reason: detectedEveryChannel
? 'containment_removed_channels_reachable'
: 'negative_control_channel_unconfirmed',
exit_code: detectedEveryChannel ? 1 : 2,
detected_channels: Object.freeze(confirmed),
observations,
});
}
const passed = proxyAllowed && confirmed.length === 0;
return Object.freeze({
passed,
status: passed ? 'passed' : 'red',
reason: passed ? 'containment_canary_passed' : 'containment_canary_failed',
exit_code: passed ? 0 : 1,
detected_channels: Object.freeze(confirmed),
observations,
});
}
export async function probeContainmentCanary({
endpoints,
negativeControl = false,
tcpExchange = exchangeTcp,
udpExchange = exchangeUdp,
timeoutMs = 250,
} = {}) {
if (!endpoints || typeof tcpExchange !== 'function' || typeof udpExchange !== 'function') {
throw new TypeError('canary dependencies are invalid');
}
const [proxyTcp, directTcp, udp, quic] = await Promise.all([
tcpExchange('proxy_tcp', endpoints.proxy_tcp, { timeoutMs }),
tcpExchange('direct_tcp', endpoints.direct_tcp, { timeoutMs }),
udpExchange('udp', endpoints.udp, { timeoutMs }),
udpExchange('quic', endpoints.quic, { timeoutMs }),
]);
return evaluateCanaryObservations({
proxy_tcp: proxyTcp,
direct_tcp: directTcp,
udp,
quic,
}, { negativeControl });
}
export async function createContainmentCanaryHarness({
nonLoopbackHost = selectNonLoopbackIpv4(),
proxyPort = 0,
} = {}) {
if (typeof nonLoopbackHost !== 'string' || nonLoopbackHost.startsWith('127.')
|| nonLoopbackHost === '0.0.0.0') {
throw new TypeError('canary responder must use a local non-loopback IPv4 address');
}
if (!Number.isInteger(proxyPort) || proxyPort < 0 || proxyPort > 65_535) {
throw new TypeError('proxy responder port must be a valid TCP port');
}
const responders = [];
try {
// proxyPort 0 (default) keeps the ephemeral-port behaviour every existing caller relies on;
// the receipt emitter pins it to the guard-proxy port so a contained uid can actually reach it.
responders.push(await createTcpResponder(LOOPBACK, CANARY_PROTOCOLS.proxy_tcp, proxyPort));
responders.push(await createTcpResponder(nonLoopbackHost, CANARY_PROTOCOLS.direct_tcp));
responders.push(await createUdpResponder(nonLoopbackHost, CANARY_PROTOCOLS.udp));
responders.push(await createUdpResponder(nonLoopbackHost, CANARY_PROTOCOLS.quic));
} catch (error) {
await Promise.allSettled(responders.map((responder) => responder.close()));
throw error;
}
return Object.freeze({
non_loopback_host: nonLoopbackHost,
endpoints: Object.freeze({
proxy_tcp: responders[0].endpoint,
direct_tcp: responders[1].endpoint,
udp: responders[2].endpoint,
quic: responders[3].endpoint,
}),
stats: Object.freeze({
proxy_tcp: responders[0].stats,
direct_tcp: responders[1].stats,
udp: responders[2].stats,
quic: responders[3].stats,
}),
async close() {
await Promise.all(responders.map((responder) => responder.close()));
},
});
}
+3
View File
@@ -0,0 +1,3 @@
pass out quick inet proto tcp from any to 127.0.0.1 port = 48191 user = 401 flags S/SA keep state
block drop out quick inet all user = 401
block drop out quick inet6 all user = 401
+17
View File
@@ -0,0 +1,17 @@
{
"kind": "lynceuz_wave2_suite_manifest",
"files": [
{
"path": "evals/browser-containment.test.mjs",
"sha256": "sha256:637432b45ca544b9dbd8511522259d54692cc9153cb769b70ebe30748a5df837"
},
{
"path": "evals/fixtures/pf-containment-canary.mjs",
"sha256": "sha256:b52fd3530f05b49942c62e6fa92c52f57ae57fd80fdc456fca39608c0ebc7dc7"
},
{
"path": "evals/fixtures/pf-real-rules.txt",
"sha256": "sha256:d708bd71d06e4a13babbc9e9dc8b0c7838efd00143527ae50dcbe760a8a86152"
}
]
}
+411
View File
@@ -0,0 +1,411 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { createPythonTransformAdapter, validateExtractSchema } from '../src/adapters/python-helper.mjs';
import { createProcessSupervisor } from '../src/process.mjs';
import { createStorage } from '../src/storage.mjs';
const PYTHON_PROBE = spawnSync('python3', ['-c', 'import sys; print(sys.executable)'], {
encoding: 'utf8',
});
const PYTHON_AVAILABLE = PYTHON_PROBE.status === 0;
const PYTHON = PYTHON_AVAILABLE ? PYTHON_PROBE.stdout.trim() : '/usr/bin/python3';
const HELPER = fileURLToPath(new URL('../src/lynceuz-helper.py', import.meta.url));
const PARSER_AVAILABLE = PYTHON_AVAILABLE
&& spawnSync(PYTHON, ['-I', HELPER, '--self-check'], { encoding: 'utf8' }).status === 0;
const OPTIONAL_SKIP = PARSER_AVAILABLE ? false : 'optional Python parser is unavailable';
function processProfile(helperPath, overrides = {}) {
return {
command: PYTHON,
args: ['-I', helperPath],
cwd: dirname(helperPath),
env: {
LANG: 'C.UTF-8',
LC_ALL: 'C.UTF-8',
PYTHONHASHSEED: '0',
PYTHONIOENCODING: 'utf-8',
PYTHONNOUSERSITE: '1',
},
maxInputBytes: 128 * 1024,
maxStdoutBytes: 64 * 1024,
maxStderrBytes: 64 * 1024,
timeoutMs: 2_000,
...overrides,
};
}
async function prepareHtmlRun() {
const workspace = await mkdtemp(join(tmpdir(), 'lynceuz-phase3-'));
const storage = createStorage({ dataRoot: join(workspace, '.lynceuz') });
const run = await storage.beginRun({ command: 'extract', requested_url: 'https://public.example.com/' });
const sourceRef = await storage.putObject(
run,
Buffer.from(`<!doctype html>
<html>
<head>
<title>Collector</title>
<link rel="canonical" href="/main" />
<meta name="description" content="Free facts" />
<script type="application/ld+json">{"@type":"Article","headline":"Collector story","author":{"name":"Fil"}}</script>
<script>globalThis.PWNED = true</script>
</head>
<body>
<article>
<h1>Collector story</h1>
<p>Find public data.</p>
<a href="/next">Next</a>
<span class="price">19.5</span>
</article>
</body>
</html>`),
{ role: 'raw', media_type: 'text/html', derived_from: null },
);
return { workspace, storage, run, sourceRef };
}
test('helper self-check works in isolated mode', { skip: OPTIONAL_SKIP }, () => {
const result = spawnSync(PYTHON, ['-I', HELPER, '--self-check'], { encoding: 'utf8' });
assert.equal(result.status, 0, result.stderr);
const payload = JSON.parse(result.stdout.trim());
assert.equal(payload.ok, true);
assert.equal(typeof payload.payload.python, 'string');
});
test('validateExtractSchema rejects hostile shapes', () => {
assert.throws(
() => validateExtractSchema({
schema_version: 1,
fields: { price: { source: 'css', selector: '.price', take: '@onclick' } },
}),
/attr is invalid/u,
);
assert.throws(
() => validateExtractSchema({ schema_version: 2, fields: {} }),
/schema_version/u,
);
});
test('python adapter parses stored HTML and commits derived artifacts', { skip: OPTIONAL_SKIP }, async () => {
const { workspace, storage, run, sourceRef } = await prepareHtmlRun();
try {
const adapter = createPythonTransformAdapter({
pythonPath: PYTHON,
helperPath: HELPER,
storage,
});
const health = await adapter.probe();
assert.equal(health.state, 'ready');
const result = await adapter.parseHtml({
run,
sourceRef,
baseUrl: 'https://public.example.com/start',
});
assert.equal(result.kind, 'success');
assert.equal(result.value.title, 'Collector');
assert.equal(result.value.canonicalCandidate, 'https://public.example.com/main');
assert.deepEqual(result.value.links, ['https://public.example.com/next']);
assert.equal(result.value.jsonld[0].headline, 'Collector story');
assert.doesNotMatch(result.value.text, /PWNED/u);
const markdown = await storage.readObject(result.value.artifacts.markdown, { maxBytes: 64 * 1024 });
assert.match(markdown.toString('utf8'), /Collector story/u);
} finally {
await rm(workspace, { recursive: true, force: true });
}
});
test('invalid schema is rejected before the helper can spawn', async () => {
const { workspace, storage, run, sourceRef } = await prepareHtmlRun();
let spawnCalls = 0;
try {
const adapter = createPythonTransformAdapter({
pythonPath: PYTHON,
helperPath: HELPER,
storage,
supervisor: {
async run() {
spawnCalls += 1;
throw new Error('must not spawn');
},
},
});
const result = await adapter.extractSchema({
run,
sourceRef,
baseUrl: 'https://public.example.com/start',
schema: {
schema_version: 1,
fields: { unsafe: { source: 'css', selector: ':has(*)', take: 'text' } },
},
});
assert.equal(result.kind, 'inadequate');
assert.equal(result.details.reason, 'invalid_schema');
assert.equal(spawnCalls, 0);
} finally {
await rm(workspace, { recursive: true, force: true });
}
});
test('helper output and scratch failures remain broken, never inadequate fallback', async () => {
const { workspace, storage, run, sourceRef } = await prepareHtmlRun();
try {
const adapter = createPythonTransformAdapter({
pythonPath: PYTHON,
storage,
supervisor: {
async run(_profile, payload) {
return {
kind: 'success',
code: 'ok',
response: {
version: 1,
id: payload.request.id,
ok: false,
code: 'adapter_error',
},
};
},
},
});
const result = await adapter.parseHtml({
run,
sourceRef,
baseUrl: 'https://public.example.com/start',
});
assert.equal(result.kind, 'broken');
assert.equal(result.code, 'adapter_protocol_error');
assert.equal(result.details.reason, 'helper_boundary_failure');
} finally {
await rm(workspace, { recursive: true, force: true });
}
});
test('schema extract publishes only valid JSON and required-field miss is typed inadequate', { skip: OPTIONAL_SKIP }, async () => {
const { workspace, storage, run, sourceRef } = await prepareHtmlRun();
try {
const adapter = createPythonTransformAdapter({
pythonPath: PYTHON,
helperPath: HELPER,
storage,
});
const ok = await adapter.extractSchema({
run,
sourceRef,
baseUrl: 'https://public.example.com/start',
schema: {
schema_version: 1,
fields: {
title: { source: 'jsonld', path: ['headline'], required: true, type: 'string' },
price: { source: 'css', selector: '.price', take: 'text', required: true, type: 'number' },
},
},
});
assert.equal(ok.kind, 'success');
assert.deepEqual(ok.value.data, { title: 'Collector story', price: 19.5 });
const saved = await storage.readObject(ok.value.artifact, { maxBytes: 64 * 1024 });
assert.deepEqual(JSON.parse(saved.toString('utf8')), { price: 19.5, title: 'Collector story' });
const missing = await adapter.extractSchema({
run,
sourceRef,
baseUrl: 'https://public.example.com/start',
schema: {
schema_version: 1,
fields: {
sku: { source: 'css', selector: '.sku', take: 'text', required: true },
},
},
});
assert.equal(missing.kind, 'inadequate');
assert.equal(missing.code, 'parse_failed');
assert.deepEqual(missing.details.missing, ['sku']);
} finally {
await rm(workspace, { recursive: true, force: true });
}
});
test('process supervisor bounds protocol and maps extra stdout to protocol error', {
skip: PYTHON_AVAILABLE ? false : 'optional Python is unavailable',
}, async () => {
const workspace = await mkdtemp(join(tmpdir(), 'lynceuz-process-'));
try {
const script = join(workspace, 'lynceuz-helper.py');
await writeFile(script, 'import sys\nprint("{\\"version\\":1,\\"id\\":\\"x\\",\\"ok\\":true}")\nprint("noise")\n');
const supervisor = createProcessSupervisor({
profiles: new Map([[
'python-parser',
processProfile(HELPER, { maxInputBytes: 4096, maxStdoutBytes: 4096 }),
]]),
spawnImpl(_command, _args, options) {
return spawn(PYTHON, ['-I', script], options);
},
});
const result = await supervisor.run('python-parser', {
request: { version: 1, id: 'x', operation: 'self_check' },
scratchDir: workspace,
});
assert.equal(result.kind, 'broken');
assert.equal(result.code, 'adapter_protocol_error');
} finally {
await rm(workspace, { recursive: true, force: true });
}
});
test('process registry rejects arbitrary argv and inherited PATH', () => {
assert.throws(
() => createPythonTransformAdapter({
pythonPath: PYTHON,
helperPath: '/tmp/lynceuz-helper.py',
storage: {},
}),
/built-in Lynceuz helper/u,
);
assert.throws(
() => createProcessSupervisor({
profiles: new Map([['python-parser', {
...processProfile(HELPER),
args: ['-c', 'print(1)'],
}]]),
}),
/fixed helper argv/u,
);
assert.throws(
() => createProcessSupervisor({
profiles: new Map([['python-parser', {
...processProfile(HELPER),
env: { PATH: '/usr/bin' },
}]]),
}),
/not allowlisted/u,
);
});
test('stored page bytes travel over stdin only and path escape is rejected before spawn', async () => {
const workspace = await mkdtemp(join(tmpdir(), 'lynceuz-process-boundary-'));
try {
const storageRoot = join(workspace, 'objects');
const scratchRoot = join(workspace, 'scratch');
const outside = join(workspace, 'outside.html');
const output = join(scratchRoot, 'result.json');
await Promise.all([
mkdir(storageRoot),
mkdir(scratchRoot),
writeFile(outside, '<p>SECRET-PAGE-BODY</p>'),
]);
let spawnCalls = 0;
const supervisor = createProcessSupervisor({
profiles: new Map([['python-parser', processProfile(HELPER)]]),
spawnImpl(...args) {
spawnCalls += 1;
return spawn(...args);
},
});
const result = await supervisor.run('python-parser', {
request: {
version: 1,
id: 'escape',
operation: 'parse_html',
input_path: outside,
input_hash: `sha256:${createHash('sha256').update('<p>SECRET-PAGE-BODY</p>').digest('hex')}`,
base_url: 'https://public.example.com/',
output_path: output,
},
inputRoot: storageRoot,
scratchDir: scratchRoot,
});
assert.equal(result.kind, 'broken');
assert.equal(result.details.reason, 'invalid_request');
assert.equal(spawnCalls, 0);
assert.doesNotMatch(JSON.stringify(processProfile(HELPER)), /SECRET-PAGE-BODY/u);
} finally {
await rm(workspace, { recursive: true, force: true });
}
});
test('timeout kills the Python process tree and waits for close', {
skip: PYTHON_AVAILABLE ? false : 'optional Python is unavailable',
}, async () => {
const workspace = await mkdtemp(join(tmpdir(), 'lynceuz-process-timeout-'));
try {
const script = join(workspace, 'lynceuz-helper.py');
const pidFile = join(workspace, 'pid.txt');
await writeFile(script, `import os,time\nopen(${JSON.stringify(pidFile)}, "w").write(str(os.getpid()))\nwhile True: time.sleep(1)\n`);
const supervisor = createProcessSupervisor({
profiles: new Map([['python-parser', processProfile(HELPER, { timeoutMs: 200 })]]),
spawnImpl(_command, _args, options) {
return spawn(PYTHON, ['-I', script], options);
},
});
const result = await supervisor.run('python-parser', {
request: { version: 1, id: 'timeout', operation: 'self_check' },
scratchDir: workspace,
});
assert.equal(result.kind, 'retryable');
assert.equal(result.code, 'timeout');
const pid = Number(await readFile(pidFile, 'utf8'));
assert.throws(() => process.kill(pid, 0), /ESRCH/u);
} finally {
await rm(workspace, { recursive: true, force: true });
}
});
test('missing Python is a typed unavailable capability', async () => {
const supervisor = createProcessSupervisor({
profiles: new Map([['python-parser', {
...processProfile(HELPER),
command: '/definitely-missing/python3',
}]]),
});
const result = await supervisor.run('python-parser', {
request: { version: 1, id: 'missing', operation: 'self_check' },
});
assert.equal(result.kind, 'skip');
assert.equal(result.code, 'unavailable');
});
test('missing optional parser dependency is a typed missing capability', async () => {
const adapter = createPythonTransformAdapter({
pythonPath: PYTHON,
storage: {
readObject() {},
resolve() {},
putObject() {},
},
supervisor: {
async run() {
return {
kind: 'success',
code: 'ok',
response: {
version: 1,
id: 'self-check',
ok: false,
code: 'dependency_unavailable',
details: { parser: 'beautifulsoup4' },
},
};
},
},
});
const health = await adapter.probe();
assert.equal(health.state, 'missing');
assert.equal(health.reason, 'unavailable');
});
test('helper source installs the network tripwire before parser imports and exposes no runner', async () => {
const source = await readFile(HELPER, 'utf8');
assert.ok(source.indexOf('install_network_tripwire()') < source.indexOf('from bs4 import'));
assert.doesNotMatch(source, /\b(?:subprocess|eval|exec)\s*\(/u);
assert.doesNotMatch(source, /\b(?:requests|urllib\.request|httpx|aiohttp)\b/u);
});
+266
View File
@@ -0,0 +1,266 @@
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Readable } from 'node:stream';
import test from 'node:test';
import { createNativeHttpAdapter } from '../src/adapters/native-http.mjs';
import { runNativeAttempts } from '../src/core.mjs';
import { deriveRepresentation, detectRepresentation } from '../src/formats.mjs';
import { createNodeRequestPinned } from '../src/network.mjs';
import {
FIXTURE_ADDRESS,
FIXTURE_URL,
RESPONSE_FIXTURES,
baseUrlJob,
createFakeClock,
createNativeFixture,
encodedResponse,
} from './fixtures/native-http.mjs';
test('production request port pins selected address while preserving Host and TLS SNI', async () => {
const calls = [];
const fakeRequest = (options, onResponse) => {
calls.push(options);
const request = new EventEmitter();
request.setTimeout = () => request;
request.destroy = (error) => { if (error) request.emit('error', error); };
request.end = () => queueMicrotask(() => {
const response = Readable.from([Buffer.from('redirect')]);
response.statusCode = 302;
response.headers = { location: 'https://public.example.com/final' };
response.socket = { remoteAddress: FIXTURE_ADDRESS };
onResponse(response);
});
return request;
};
const requestPinned = createNodeRequestPinned({ httpRequest: fakeRequest, httpsRequest: fakeRequest });
const permit = {
canonicalUrl: `${FIXTURE_URL}?x=1`,
protocol: 'https:',
hostname: 'public.example.com',
port: 443,
selectedAddress: FIXTURE_ADDRESS,
expiresAtMs: Date.now() + 5_000,
};
const response = await requestPinned({
permit,
method: 'GET',
headers: { Accept: 'text/html' },
signal: new AbortController().signal,
});
assert.equal(calls.length, 1, 'request port must not follow redirects');
assert.equal(calls[0].hostname, permit.hostname);
assert.equal(calls[0].servername, permit.hostname);
assert.equal(calls[0].headers.Host, permit.hostname);
assert.equal(calls[0].agent, false);
await new Promise((resolve, reject) => {
calls[0].lookup(permit.hostname, { all: false }, (error, address, family) => {
if (error) return reject(error);
assert.equal(address, permit.selectedAddress);
assert.equal(family, 4);
resolve();
});
});
assert.equal(response.peerAddress, permit.selectedAddress);
assert.equal(response.statusCode, 302);
});
test('native adapter composes only through gateway and keeps selected peer evidence', async () => {
const fixture = createNativeFixture({ responses: [RESPONSE_FIXTURES.html] });
const adapter = createNativeHttpAdapter({ gateway: fixture.gateway });
const outcome = await adapter.run({
runId: 'run-native-1',
url: FIXTURE_URL,
method: 'GET',
remaining: { wallMs: 5_000, bytes: 64 * 1024, redirects: 2 },
limits: { maxWireBytes: 64 * 1024, maxDecodedBytes: 64 * 1024 },
});
assert.equal(outcome.kind, 'success');
assert.equal(outcome.code, 'ok');
assert.equal(outcome.response.permit.selectedAddress, FIXTURE_ADDRESS);
assert.equal(fixture.calls.lookupAll.length, 1);
assert.equal(fixture.calls.requestPinned.length, 1);
assert.equal(outcome.response.body.includes(Buffer.from('Lynceuz')), true);
});
test('declared and sniffed representations cover native public formats', () => {
const cases = [
[RESPONSE_FIXTURES.html, 'html'],
[RESPONSE_FIXTURES.json, 'json'],
[RESPONSE_FIXTURES.xml, 'xml'],
[RESPONSE_FIXTURES.rss, 'rss'],
[RESPONSE_FIXTURES.atom, 'atom'],
[RESPONSE_FIXTURES.sitemap, 'sitemap'],
[RESPONSE_FIXTURES.binary, 'binary'],
];
for (const [fixture, expected] of cases) {
const detected = detectRepresentation({ headers: fixture.headers, prefixBytes: fixture.body });
assert.equal(detected.kind, expected);
assert.equal(typeof detected.mediaType, 'string');
}
const sniffed = detectRepresentation({
headers: { 'content-type': 'text/plain' },
prefixBytes: RESPONSE_FIXTURES.rss.body,
});
assert.equal(sniffed.kind, 'rss');
assert.equal(sniffed.sniffedType, 'rss');
const binary = detectRepresentation({ headers: {}, prefixBytes: RESPONSE_FIXTURES.binary.body });
assert.equal(binary.kind, 'binary');
assert.ok(binary.warnings.includes('unknown_mime_raw_preserved'));
});
test('native projections are deterministic, source preserving and reject malformed JSON', async () => {
const directory = await mkdtemp(join(tmpdir(), 'lynceuz-format-'));
try {
const htmlPath = join(directory, 'source.html');
const jsonPath = join(directory, 'source.json');
const invalidPath = join(directory, 'invalid.json');
await writeFile(htmlPath, RESPONSE_FIXTURES.html.body);
await writeFile(jsonPath, RESPONSE_FIXTURES.json.body);
await writeFile(invalidPath, RESPONSE_FIXTURES.malformedJson.body);
const markdown = await deriveRepresentation({
format: 'markdown', sourcePath: htmlPath, mediaType: 'text/html', finalUrl: FIXTURE_URL,
maxArtifactBytes: 64 * 1024,
});
assert.equal(markdown.format, 'markdown');
assert.match(markdown.bytes.toString(), /# Lynceuz/);
assert.match(markdown.bytes.toString(), /\[Next\]\(https:\/\/public\.example\.com\/next\)/);
const raw = await deriveRepresentation({
format: 'raw', sourcePath: htmlPath, mediaType: 'text/html', finalUrl: FIXTURE_URL,
maxArtifactBytes: 64 * 1024,
});
assert.deepEqual(raw.bytes, RESPONSE_FIXTURES.html.body);
const metadata = await deriveRepresentation({
format: 'metadata', sourcePath: htmlPath, mediaType: 'text/html', finalUrl: FIXTURE_URL,
maxArtifactBytes: 64 * 1024,
});
assert.deepEqual(JSON.parse(metadata.bytes), {
bytes: RESPONSE_FIXTURES.html.body.length,
final_url: FIXTURE_URL,
media_type: 'text/html',
});
const links = await deriveRepresentation({
format: 'links', sourcePath: htmlPath, mediaType: 'text/html', finalUrl: FIXTURE_URL,
maxArtifactBytes: 64 * 1024,
});
assert.deepEqual(JSON.parse(links.bytes), ['https://public.example.com/next']);
const json = await deriveRepresentation({
format: 'json', sourcePath: jsonPath, mediaType: 'application/json', finalUrl: FIXTURE_URL,
maxArtifactBytes: 64 * 1024,
});
assert.deepEqual(JSON.parse(json.bytes), { free: true, name: 'Lynceuz' });
await assert.rejects(
deriveRepresentation({
format: 'json', sourcePath: invalidPath, mediaType: 'application/json', finalUrl: FIXTURE_URL,
maxArtifactBytes: 64 * 1024,
}),
(error) => error?.code === 'output_failure',
);
await assert.rejects(
deriveRepresentation({
format: 'pdf', sourcePath: htmlPath, mediaType: 'text/html', finalUrl: FIXTURE_URL,
maxArtifactBytes: 64 * 1024,
}),
(error) => error?.code === 'unsupported_format',
);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test('wire and decoded limits reject compressed overflow without partial success', async () => {
for (const encoding of ['gzip', 'deflate', 'br']) {
const fixture = createNativeFixture({ responses: [encodedResponse(encoding, 'x'.repeat(32 * 1024))] });
const adapter = createNativeHttpAdapter({ gateway: fixture.gateway });
const outcome = await adapter.run({
runId: `run-${encoding}`,
url: FIXTURE_URL,
method: 'GET',
remaining: { wallMs: 5_000, bytes: 64 * 1024, redirects: 1 },
limits: { maxWireBytes: 64 * 1024, maxDecodedBytes: 1024 },
});
assert.deepEqual({ kind: outcome.kind, code: outcome.code }, { kind: 'terminal', code: 'hard_limit' });
assert.equal('response' in outcome, false);
}
const malformed = createNativeFixture({
responses: [{
statusCode: 200,
headers: { 'content-type': 'text/plain', 'content-encoding': 'gzip' },
body: Buffer.from('not gzip'),
}],
});
const outcome = await createNativeHttpAdapter({ gateway: malformed.gateway }).run({
runId: 'run-malformed', url: FIXTURE_URL, method: 'GET',
remaining: { wallMs: 5_000, bytes: 64 * 1024, redirects: 1 },
limits: { maxWireBytes: 64 * 1024, maxDecodedBytes: 64 * 1024 },
});
assert.deepEqual(
{ kind: outcome.kind, code: outcome.code },
{ kind: 'broken', code: 'adapter_protocol_error' },
);
});
test('retry owner bounds attempts, wall deadline and Retry-After while preserving timeline', async () => {
const clock = createFakeClock();
const scripted = [
{ kind: 'retryable', code: 'network' },
{ kind: 'retryable', code: 'rate_limited', retryAfterMs: 120_000 },
{ kind: 'success', code: 'ok', response: { body: Buffer.from('ok') } },
];
const adapter = { run: async () => scripted.shift() };
const result = await runNativeAttempts(baseUrlJob(), {
adapter,
clock: clock.now,
sleep: clock.sleep,
});
assert.equal(result.outcome.kind, 'success');
assert.equal(result.timeline.length, 3);
assert.deepEqual(clock.sleeps, [0, 1_500]);
assert.equal(result.timeline[1].delay_ms, 1_500);
assert.equal(result.timeline[1].retry_after_capped, true);
const deadlineClock = createFakeClock();
const deadlineJob = baseUrlJob({
limits: { ...baseUrlJob().limits, wallMs: 1_000, maxRetryAfterMs: 1_500 },
});
const deadline = await runNativeAttempts(deadlineJob, {
adapter: { run: async () => ({ kind: 'retryable', code: 'rate_limited', retryAfterMs: 3_000 }) },
clock: deadlineClock.now,
sleep: deadlineClock.sleep,
});
assert.deepEqual(
{ kind: deadline.outcome.kind, code: deadline.outcome.code },
{ kind: 'terminal', code: 'hard_limit' },
);
assert.equal(deadline.timeline.length, 1);
});
test('403 and 404 are terminal and never retried', async () => {
for (const [response, expected] of [
[RESPONSE_FIXTURES.forbidden, ['terminal', 'access_denied']],
[RESPONSE_FIXTURES.notFound, ['terminal', 'not_found']],
]) {
const fixture = createNativeFixture({ responses: [response, RESPONSE_FIXTURES.html] });
const adapter = createNativeHttpAdapter({ gateway: fixture.gateway });
const result = await runNativeAttempts(baseUrlJob(), {
adapter, clock: fixture.clock, sleep: fixture.sleep,
});
assert.deepEqual([result.outcome.kind, result.outcome.code], expected);
assert.equal(fixture.calls.requestPinned.length, 1);
assert.equal(result.timeline.length, 1);
}
});
+854
View File
@@ -0,0 +1,854 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import {
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
rm,
writeFile,
} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, relative, sep } from 'node:path';
import { Readable } from 'node:stream';
import test from 'node:test';
import { createPythonTransformAdapter } from '../src/adapters/python-helper.mjs';
import { compileJobSpec, parseArgv, runCli } from '../src/cli.mjs';
import { ATTEMPT_CODE, ATTEMPT_KIND } from '../src/contracts.mjs';
import {
createProductionExecutor,
runCrawlJob,
runExtractJob,
runUrlJob,
runUrlPipeline,
} from '../src/core.mjs';
import { runBoundedCrawl } from '../src/frontier.mjs';
import { createEgressGateway } from '../src/network.mjs';
import { PYTHON_HELPER_PATH } from '../src/process.mjs';
import { acceptRepresentation, createDefaultRegistry } from '../src/router.mjs';
import { createStorage } from '../src/storage.mjs';
import { RESPONSE_FIXTURES } from './fixtures/native-http.mjs';
import {
DEFAULT_GRAPH,
P0_ADDRESS,
P0_ORIGIN,
createP0SiteFixture,
} from './fixtures/p0-site.mjs';
const PYTHON_PROBE = spawnSync('python3', ['-c', 'import sys; print(sys.executable)'], {
encoding: 'utf8',
});
const PYTHON = PYTHON_PROBE.status === 0 ? PYTHON_PROBE.stdout.trim() : '/usr/bin/python3';
const PARSER_AVAILABLE = PYTHON_PROBE.status === 0
&& spawnSync(PYTHON, ['-I', PYTHON_HELPER_PATH, '--self-check'], { encoding: 'utf8' }).status === 0;
const OPTIONAL_PARSER_SKIP = PARSER_AVAILABLE ? false : 'optional Python parser is unavailable';
const HASH = /^sha256:[0-9a-f]{64}$/u;
const REGISTRY = createDefaultRegistry(process.version).map((capability) => (
capability.id === 'native'
? { ...capability, state: 'ready', version: '1', reason: 'offline_fixture_ready' }
: capability
));
async function withStorage(t, prefix = 'lynceuz-p0-') {
const workspace = await mkdtemp(join(tmpdir(), prefix));
t.after(async () => rm(workspace, { recursive: true, force: true }));
const dataRoot = join(workspace, '.lynceuz');
return { workspace, dataRoot, storage: createStorage({ dataRoot }) };
}
async function storedJson(storage, path) {
return JSON.parse(await readFile(await storage.resolve(path), 'utf8'));
}
function urlJob(url, ...flags) {
return compileJobSpec(parseArgv(['url', url, '--cache', 'off', ...flags]));
}
function crawlJob(url, ...flags) {
return compileJobSpec(parseArgv(['crawl', url, '--cache', 'off', ...flags]));
}
function extractJob(url, schemaPath, schema) {
return {
...compileJobSpec(parseArgv(['extract', url, '--schema', schemaPath, '--cache', 'off'])),
schema,
};
}
function sha256(bytes) {
return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
}
function memoryIo() {
let stdout = '';
let stderr = '';
return {
io: {
stdout: { write: (value) => { stdout += value; } },
stderr: { write: (value) => { stderr += value; } },
},
read: () => ({ stdout, stderr }),
};
}
async function walk(root) {
const paths = [];
async function visit(path) {
const info = await lstat(path);
paths.push(path);
if (!info.isDirectory()) return;
for (const name of await readdir(path)) await visit(join(path, name));
}
await visit(root);
return paths;
}
async function assertManifestHashes(storage, manifest, rawBytes) {
assert.match(manifest.source_hash, HASH);
assert.match(manifest.artifact_hash, HASH);
const source = manifest.artifacts.find(({ hash }) => hash === manifest.source_hash);
const artifact = manifest.artifacts.find(({ hash }) => hash === manifest.artifact_hash);
assert.ok(source);
assert.ok(artifact);
const storedSource = await readFile(await storage.resolve(source.path));
const storedArtifact = await readFile(await storage.resolve(artifact.path));
assert.equal(manifest.source_hash, sha256(rawBytes));
assert.equal(manifest.source_hash, sha256(storedSource));
assert.equal(manifest.artifact_hash, sha256(storedArtifact));
if (artifact.hash !== source.hash) assert.equal(artifact.derived_from, source.hash);
}
test('P0 preserves requested target and records discovered alternatives with immutable evidence', async (t) => {
const { storage } = await withStorage(t, 'lynceuz-p0-alternatives-');
const fixture = createP0SiteFixture();
let forbiddenFallbackCalls = 0;
const result = await runUrlJob(urlJob(`${P0_ORIGIN}/`), {
gateway: fixture.gateway,
storage,
clock: fixture.clock,
sleep: fixture.sleep,
pythonAdapter: {
async parseHtml() {
forbiddenFallbackCalls += 1;
throw new Error('accepted native HTML must not fall through');
},
},
});
const manifest = await storedJson(storage, result.manifest_path);
assert.equal(result.status, 'ok');
assert.equal(forbiddenFallbackCalls, 0);
assert.equal(manifest.requested_url, `${P0_ORIGIN}/`);
assert.equal(manifest.effective_url, `${P0_ORIGIN}/`);
assert.deepEqual(manifest.alternatives, [{
type: 'application/rss+xml',
url: `${P0_ORIGIN}/feed.xml`,
}]);
assert.match(manifest.source_hash, /^sha256:[0-9a-f]{64}$/u);
assert.match(manifest.artifact_hash, /^sha256:[0-9a-f]{64}$/u);
assert.equal(manifest.artifacts.some(({ hash }) => hash === manifest.source_hash), true);
assert.equal(manifest.artifacts.some(({ hash }) => hash === manifest.artifact_hash), true);
assert.equal(manifest.evidence.some(({ hash }) => hash === manifest.source_hash), true);
assert.equal(manifest.cost_money, 0);
assert.equal(manifest.credits_used, 0);
});
test('P0 native format matrix keeps dual hashes and CLI state inside an explicit data root', async (t) => {
const workspace = await mkdtemp(join(tmpdir(), 'lynceuz-p0-formats-'));
const caller = join(workspace, 'unrelated-cwd');
const dataRoot = join(workspace, 'selected', '.lynceuz');
await mkdir(caller, { recursive: true });
const sentinel = join(caller, 'sentinel.txt');
await writeFile(sentinel, 'unchanged\n');
t.after(async () => rm(workspace, { recursive: true, force: true }));
const cases = [
['html', RESPONSE_FIXTURES.html, 'markdown'],
['html-raw', RESPONSE_FIXTURES.html, 'raw'],
['json', RESPONSE_FIXTURES.json, 'json'],
['xml', RESPONSE_FIXTURES.xml, 'markdown'],
['rss', RESPONSE_FIXTURES.rss, 'markdown'],
['atom', RESPONSE_FIXTURES.atom, 'markdown'],
['sitemap', RESPONSE_FIXTURES.sitemap, 'markdown'],
['unknown', RESPONSE_FIXTURES.binary, 'raw'],
];
const graph = { ...DEFAULT_GRAPH };
for (const [name, response] of cases) graph[`/formats/${name}`] = response;
const fixture = createP0SiteFixture({ graph });
const storage = createStorage({ dataRoot, clock: fixture.clock });
const previousCwd = process.cwd();
try {
process.chdir(caller);
for (const [name, response, format] of cases) {
const target = `${P0_ORIGIN}/formats/${name}`;
const result = await runUrlJob(urlJob(target, '--format', format), {
gateway: fixture.gateway,
storage,
clock: fixture.clock,
sleep: fixture.sleep,
});
const manifest = await storedJson(storage, result.manifest_path);
assert.equal(result.status, 'ok', name);
assert.equal(manifest.requested_url, target);
assert.equal(manifest.effective_url, target);
assert.equal(manifest.cost_money, 0);
assert.equal(manifest.credits_used, 0);
await assertManifestHashes(storage, manifest, response.body);
}
const executeJob = createProductionExecutor({
gateway: fixture.gateway,
storage,
clock: fixture.clock,
sleep: fixture.sleep,
});
const output = memoryIo();
const exitCode = await runCli([
'url', `${P0_ORIGIN}/formats/unknown`,
'--format', 'raw',
'--cache', 'off',
'--data-root', dataRoot,
'--json',
], {
io: output.io,
registry: REGISTRY,
executeJob,
now: () => new Date(fixture.clock()),
});
const streams = output.read();
assert.equal(exitCode, 0);
assert.equal(streams.stdout.split('\n').filter(Boolean).length, 1);
assert.equal(JSON.parse(streams.stdout).status, 'ok');
assert.equal(streams.stderr, 'warning: unknown_mime_raw_preserved\n');
} finally {
process.chdir(previousCwd);
}
assert.equal(await readFile(sentinel, 'utf8'), 'unchanged\n');
const paths = await walk(workspace);
const files = [];
for (const path of paths) if ((await lstat(path)).isFile()) files.push(path);
assert.deepEqual(files.filter((path) => path.endsWith(`${sep}.gitignore`)), [join(dataRoot, '.gitignore')]);
assert.equal(await readFile(join(dataRoot, '.gitignore'), 'utf8'), '*\n!.gitignore\n');
for (const path of files) {
assert.equal(
path === sentinel || relative(dataRoot, path).split(sep)[0] !== '..',
true,
`unexpected write outside selected data root: ${path}`,
);
}
});
test('P0 raw acceptance requires captured bytes', () => {
assert.deepEqual(
acceptRepresentation({ goal: 'raw', representation: { kind: 'html' } }),
{
kind: ATTEMPT_KIND.INADEQUATE,
code: ATTEMPT_CODE.EMPTY,
details: { reason: 'empty_main_content' },
},
);
});
test('P0 terminal outcomes, redirect SSRF and mixed DNS make zero fallback calls', async () => {
const terminalCodes = [
ATTEMPT_CODE.POLICY_DENIED,
ATTEMPT_CODE.ROBOTS_DENIED,
ATTEMPT_CODE.ACCESS_DENIED,
ATTEMPT_CODE.AUTH_REQUIRED,
ATTEMPT_CODE.CAPTCHA,
ATTEMPT_CODE.PAYWALL,
ATTEMPT_CODE.PAID_REQUIRED,
ATTEMPT_CODE.NOT_FOUND,
ATTEMPT_CODE.RATE_LIMITED,
ATTEMPT_CODE.HARD_LIMIT,
];
for (const code of terminalCodes) {
const calls = { native: 0, python: 0, browser: 0, cloud: 0 };
const result = await runUrlPipeline({
job: urlJob(`${P0_ORIGIN}/terminal-${code}`),
adapters: {
native: {
async run() {
calls.native += 1;
return { kind: ATTEMPT_KIND.TERMINAL, code };
},
},
python: { async parseHtml() { calls.python += 1; } },
browser: { async run() { calls.browser += 1; } },
cloud: { async run() { calls.cloud += 1; } },
},
});
assert.equal(result.outcome.kind, ATTEMPT_KIND.TERMINAL, code);
assert.equal(result.outcome.code, code);
assert.deepEqual(calls, { native: 1, python: 0, browser: 0, cloud: 0 });
}
let poisonCalls = 0;
const redirectFixture = createP0SiteFixture();
const redirect = await runUrlPipeline({
job: urlJob(`${P0_ORIGIN}/redirect-private`),
context: { gateway: redirectFixture.gateway, clock: redirectFixture.clock, sleep: redirectFixture.sleep },
adapters: {
python: { async parseHtml() { poisonCalls += 1; } },
browser: { async run() { poisonCalls += 1; } },
cloud: { async run() { poisonCalls += 1; } },
},
});
assert.deepEqual(
{ kind: redirect.outcome.kind, code: redirect.outcome.code },
{ kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.POLICY_DENIED },
);
assert.equal(poisonCalls, 0);
assert.deepEqual(
redirectFixture.calls.requestPinned.map(({ url }) => url),
[`${P0_ORIGIN}/redirect-private`],
);
let pinnedCalls = 0;
const mixedGateway = createEgressGateway({
lookupAll: async () => [
{ address: P0_ADDRESS, family: 4 },
{ address: '127.0.0.1', family: 4 },
],
requestPinned: async () => {
pinnedCalls += 1;
throw new Error('mixed-address target must be denied before transport');
},
connectPinned: async () => { throw new Error('tunnel disabled'); },
});
const mixed = await runUrlPipeline({
job: urlJob(`${P0_ORIGIN}/mixed-address`),
context: { gateway: mixedGateway },
adapters: { python: { async parseHtml() { poisonCalls += 1; } } },
});
assert.deepEqual(
{ kind: mixed.outcome.kind, code: mixed.outcome.code },
{ kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.POLICY_DENIED },
);
assert.equal(pinnedCalls, 0);
assert.equal(poisonCalls, 0);
});
test('P0 unreachable robots fails crawl closed before any page or fallback', async (t) => {
const { storage } = await withStorage(t, 'lynceuz-p0-robots-');
const fixture = createP0SiteFixture({ robots: new Error('offline robots failure') });
let parserCalls = 0;
const result = await runCrawlJob(crawlJob(`${P0_ORIGIN}/`,
'--max-pages', '3', '--max-depth', '2', '--max-time', '5', '--max-bytes', '65536',
'--max-frontier', '10', '--concurrency', '1', '--delay', '0.001'), {
gateway: fixture.gateway,
storage,
clock: fixture.clock,
sleep: fixture.sleep,
pythonAdapter: { async parseHtml() { parserCalls += 1; } },
});
const manifest = await storedJson(storage, result.manifest_path);
assert.equal(result.status, 'blocked');
assert.equal(result.code, ATTEMPT_CODE.ROBOTS_DENIED);
assert.equal(parserCalls, 0);
assert.deepEqual(
fixture.calls.requestPinned.map(({ url }) => url),
[`${P0_ORIGIN}/robots.txt`],
);
assert.equal(manifest.crawl.accepted.length, 0);
assert.equal(manifest.crawl.blocked[0].reason, ATTEMPT_CODE.ROBOTS_DENIED);
assert.equal(manifest.cost_money, 0);
assert.equal(manifest.credits_used, 0);
});
test('P0 inadequate HTML may reach only the missing local helper and then stops honestly', async (t) => {
const { workspace, storage } = await withStorage(t, 'lynceuz-p0-missing-helper-');
const fixture = createP0SiteFixture();
const run = await storage.beginRun({
schema_version: 1,
command: 'url',
requested_url: `${P0_ORIGIN}/empty`,
});
const python = createPythonTransformAdapter({
pythonPath: join(workspace, 'missing', 'python3'),
storage,
});
let poisonCalls = 0;
const result = await runUrlPipeline({
job: urlJob(`${P0_ORIGIN}/empty`),
context: {
storage,
run,
gateway: fixture.gateway,
clock: fixture.clock,
sleep: fixture.sleep,
},
adapters: {
python,
browser: { async run() { poisonCalls += 1; } },
cloud: { async run() { poisonCalls += 1; } },
},
});
assert.deepEqual(
{ kind: result.outcome.kind, code: result.outcome.code },
{ kind: ATTEMPT_KIND.SKIP, code: ATTEMPT_CODE.UNAVAILABLE },
);
assert.equal(result.sourceRef.hash.match(HASH) !== null, true);
assert.deepEqual(
result.timeline.filter(({ type }) => type === 'transform').map(({ adapter, outcome, code }) => ({
adapter, outcome, code,
})),
[
{ adapter: 'builtin', outcome: ATTEMPT_KIND.INADEQUATE, code: ATTEMPT_CODE.EMPTY },
{ adapter: 'python-parser', outcome: ATTEMPT_KIND.SKIP, code: ATTEMPT_CODE.UNAVAILABLE },
],
);
assert.equal(poisonCalls, 0);
assert.deepEqual(
fixture.calls.requestPinned.map(({ url }) => url),
[`${P0_ORIGIN}/empty`],
);
});
test('P0 rejects an invalid extract schema before storage, DNS, transport or helper startup', async (t) => {
const { workspace } = await withStorage(t, 'lynceuz-p0-schema-first-');
const schemaPath = join(workspace, 'hostile-schema.json');
await writeFile(schemaPath, JSON.stringify({
schema_version: 1,
fields: {
title: {
source: 'css',
selector: 'h1',
take: 'text',
required: true,
expression: 'process.exit()',
},
},
}));
const fixture = createP0SiteFixture();
let storageCalls = 0;
let helperCalls = 0;
const executeJob = createProductionExecutor({
gateway: fixture.gateway,
storage: async () => {
storageCalls += 1;
throw new Error('invalid schema must stop before storage initialization');
},
pythonAdapter: async () => {
helperCalls += 1;
throw new Error('invalid schema must stop before helper startup');
},
clock: fixture.clock,
sleep: fixture.sleep,
});
const job = compileJobSpec(parseArgv([
'extract', `${P0_ORIGIN}/extract`, '--schema', schemaPath, '--cache', 'off',
]));
const result = await executeJob(job, { registry: REGISTRY });
assert.equal(result.status, 'invalid_input');
assert.equal(result.code, 'invalid_input');
assert.equal(storageCalls, 0);
assert.equal(helperCalls, 0);
assert.equal(fixture.calls.lookupAll.length, 0);
assert.equal(fixture.calls.requestPinned.length, 0);
});
test('P0 extract publishes only schema-valid JSON and required-field failure keeps raw evidence only', {
skip: OPTIONAL_PARSER_SKIP,
}, async (t) => {
const { storage } = await withStorage(t, 'lynceuz-p0-extract-');
const fixture = createP0SiteFixture({
graph: {
...DEFAULT_GRAPH,
'/extract-alt': {
statusCode: 200,
headers: { 'content-type': 'text/html' },
body: Buffer.from(`<!doctype html><html><head>
<link rel="canonical" href="/products/sku-1">
<link rel="alternate" type="application/rss+xml" href="/feed.xml">
<script type="application/ld+json">{"sku":"sku-1"}</script>
</head><body><main><span class="price">19.5</span></main></body></html>`),
},
},
});
const parser = createPythonTransformAdapter({ pythonPath: PYTHON, storage });
const schema = {
schema_version: 1,
fields: {
price: { source: 'css', selector: '.price', take: 'text', required: true, type: 'number' },
sku: { source: 'jsonld', path: ['sku'], required: true, type: 'string' },
},
};
const success = await runExtractJob(
extractJob(`${P0_ORIGIN}/extract-alt`, 'success.json', schema),
{ gateway: fixture.gateway, storage, pythonAdapter: parser, clock: fixture.clock, sleep: fixture.sleep },
);
const successManifest = await storedJson(storage, success.manifest_path);
const successArtifact = await storedJson(storage, success.artifact_path);
const selected = successManifest.artifacts.find(({ hash }) => hash === successManifest.artifact_hash);
assert.equal(success.status, 'ok');
assert.deepEqual(successArtifact, { price: 19.5, sku: 'sku-1' });
assert.equal(successManifest.requested_url, `${P0_ORIGIN}/extract-alt`);
assert.equal(successManifest.effective_url, `${P0_ORIGIN}/extract-alt`);
assert.deepEqual(successManifest.alternatives, [
{ type: 'canonical', url: `${P0_ORIGIN}/products/sku-1` },
{ type: 'application/rss+xml', url: `${P0_ORIGIN}/feed.xml` },
]);
assert.match(successManifest.source_hash, HASH);
assert.match(successManifest.artifact_hash, HASH);
assert.equal(selected.derived_from, successManifest.source_hash);
assert.equal(successManifest.evidence[0].hash, successManifest.source_hash);
assert.equal(successManifest.cost_money, 0);
assert.equal(successManifest.credits_used, 0);
const missingSchema = {
schema_version: 1,
fields: {
sku: { source: 'css', selector: '.sku', take: 'text', required: true },
},
};
const missing = await runExtractJob(
extractJob(`${P0_ORIGIN}/extract-missing`, 'missing.json', missingSchema),
{ gateway: fixture.gateway, storage, pythonAdapter: parser, clock: fixture.clock, sleep: fixture.sleep },
);
const missingManifest = await storedJson(storage, missing.manifest_path);
assert.equal(missing.status, 'exhausted');
assert.equal(missingManifest.requested_url, `${P0_ORIGIN}/extract-missing`);
assert.equal(missingManifest.effective_url, `${P0_ORIGIN}/extract-missing`);
assert.match(missingManifest.source_hash, HASH);
assert.equal(missingManifest.artifact_hash, null);
assert.equal(missingManifest.artifact_path, null);
assert.equal(missingManifest.artifacts.length, 1);
assert.equal(missingManifest.artifacts[0].role, 'raw');
assert.equal(missingManifest.evidence[0].hash, missingManifest.source_hash);
});
test('P0 crawl enforces exact origin and scope, records discovery provenance and returns a complete partial ledger', async (t) => {
const { storage } = await withStorage(t, 'lynceuz-p0-crawl-');
const fixture = createP0SiteFixture();
const job = crawlJob(`${P0_ORIGIN}/`,
'--include', '/',
'--include', '/a',
'--include', '/query*',
'--include', '/sitemap.xml',
'--include', '/feed.xml',
'--exclude', '/private/**',
'--discover', 'sitemap,rss',
'--max-pages', '4',
'--max-depth', '3',
'--max-time', '10',
'--max-bytes', '65536',
'--max-frontier', '20',
'--concurrency', '2',
'--delay', '0.001');
const result = await runCrawlJob(job, {
gateway: fixture.gateway,
storage,
clock: fixture.clock,
sleep: fixture.sleep,
});
const manifest = await storedJson(storage, result.manifest_path);
const crawl = await storedJson(storage, result.artifact_path);
const requestedPages = fixture.calls.requestPinned
.filter(({ purpose }) => purpose === 'page')
.map(({ url }) => url);
assert.equal(result.status, 'partial');
assert.equal(manifest.status, 'partial');
assert.equal(crawl.limit, 'max_pages');
assert.equal(manifest.requested_url, `${P0_ORIGIN}/`);
assert.deepEqual(manifest.crawl, crawl);
assert.deepEqual(manifest.attempts, crawl.ledger);
assert.equal(new Set(crawl.accepted.map(({ url }) => url)).size, crawl.accepted.length);
assert.equal(crawl.accepted.some(({ provenance }) => provenance === 'robots_sitemap'), true);
assert.equal(crawl.unvisited.some(({ provenance }) => provenance === 'rss'), true);
assert.equal(crawl.skipped.some(({ reason }) => reason === 'excluded'), true);
assert.equal(crawl.skipped.some(({ reason }) => reason === 'not_included'), true);
assert.equal(crawl.skipped.some(({ reason }) => reason === 'off_origin'), true);
assert.equal(crawl.skipped.some(({ reason }) => reason === 'duplicate'), true);
assert.equal(crawl.accepted.some(({ url }) => url === `${P0_ORIGIN}/query?a=1`), true);
assert.equal(requestedPages.some((url) => url.includes('/private/')), false);
assert.equal(requestedPages.some((url) => url.startsWith('https://off-origin.example.net/')), false);
assert.equal(requestedPages.some((url) => url.endsWith('/b')), false);
assert.equal(fixture.calls.sleeps.some((milliseconds) => milliseconds >= 100), true);
for (const entry of crawl.ledger) {
assert.equal(typeof entry.state, 'string');
assert.equal(typeof entry.url, 'string');
assert.equal(Number.isSafeInteger(entry.depth), true);
assert.equal(typeof entry.reason, 'string');
}
for (const page of crawl.accepted) {
assert.match(page.source_hash, HASH);
assert.equal(manifest.artifacts.some(({ hash }) => hash === page.source_hash), true);
assert.equal(manifest.evidence.some(({ url, hash }) => url === page.url && hash === page.source_hash), true);
}
assert.equal(manifest.cost_money, 0);
assert.equal(manifest.credits_used, 0);
});
test('P0 crawl reports depth, frontier, byte and wall exhaustion as partial', async () => {
const baseLimits = {
maxPages: 10,
maxDepth: 3,
wallMs: 1_000,
maxTotalBytes: 1_000,
maxFrontier: 10,
concurrency: 1,
delayMs: 1,
retriesPerAdapter: 1,
maxRedirects: 1,
};
async function scenario({ links, usage = {}, limits = {}, advanceOnPage = 0 }) {
let now = 0;
return runBoundedCrawl({
job: { kind: 'crawl', target: { url: `${P0_ORIGIN}/` }, goal: 'markdown' },
context: {},
adapters: {},
robotsGate: {
async check() {
return { kind: ATTEMPT_KIND.SUCCESS, code: ATTEMPT_CODE.OK, crawlDelayMs: 0 };
},
},
runUrlPipeline: async ({ job }) => {
now += advanceOnPage;
return {
outcome: { kind: ATTEMPT_KIND.SUCCESS, code: ATTEMPT_CODE.OK },
representation: { links: links[job.target.url] ?? [] },
usage: usage[job.target.url] ?? { totalBytes: 1 },
};
},
limits: { ...baseLimits, ...limits },
include: ['/**'],
exclude: [],
clock: () => now,
sleep: async (milliseconds) => { now += milliseconds; },
});
}
const depth = await scenario({
links: {
[`${P0_ORIGIN}/`]: [`${P0_ORIGIN}/a`],
[`${P0_ORIGIN}/a`]: [`${P0_ORIGIN}/b`],
},
limits: { maxDepth: 1 },
});
assert.equal(depth.status, 'partial');
assert.equal(depth.limit, 'max_depth');
assert.equal(depth.unvisited.some(({ reason }) => reason === 'max_depth'), true);
const frontier = await scenario({
links: { [`${P0_ORIGIN}/`]: [`${P0_ORIGIN}/a`, `${P0_ORIGIN}/b`] },
limits: { maxFrontier: 1 },
});
assert.equal(frontier.status, 'partial');
assert.equal(frontier.limit, 'max_frontier');
assert.equal(frontier.unvisited.some(({ reason }) => reason === 'max_frontier'), true);
const bytes = await scenario({
links: { [`${P0_ORIGIN}/`]: [`${P0_ORIGIN}/a`] },
usage: {
[`${P0_ORIGIN}/`]: { totalBytes: 10 },
[`${P0_ORIGIN}/a`]: { totalBytes: 100 },
},
limits: { maxTotalBytes: 50 },
});
assert.equal(bytes.status, 'partial');
assert.equal(bytes.limit, 'max_total_bytes');
assert.equal(bytes.blocked.some(({ reason }) => reason === ATTEMPT_CODE.HARD_LIMIT), true);
const wall = await scenario({
links: { [`${P0_ORIGIN}/`]: [`${P0_ORIGIN}/a`] },
limits: { wallMs: 10 },
advanceOnPage: 11,
});
assert.equal(wall.status, 'partial');
assert.equal(wall.limit, 'max_time');
assert.equal(wall.unvisited.some(({ reason }) => reason === 'max_time'), true);
});
test('P0 crawl never exceeds its run-level concurrency cap', async () => {
let active = 0;
let maximumActive = 0;
const links = {
[`${P0_ORIGIN}/`]: [`${P0_ORIGIN}/a`, `${P0_ORIGIN}/b`, `${P0_ORIGIN}/c`],
};
const result = await runBoundedCrawl({
job: { kind: 'crawl', target: { url: `${P0_ORIGIN}/` }, goal: 'markdown' },
context: {},
adapters: {},
robotsGate: {
async check() {
return { kind: ATTEMPT_KIND.SUCCESS, code: ATTEMPT_CODE.OK, crawlDelayMs: 0 };
},
},
runUrlPipeline: async ({ job }) => {
active += 1;
maximumActive = Math.max(maximumActive, active);
await Promise.resolve();
active -= 1;
return {
outcome: { kind: ATTEMPT_KIND.SUCCESS, code: ATTEMPT_CODE.OK },
representation: { links: links[job.target.url] ?? [] },
usage: { totalBytes: 1 },
};
},
limits: {
maxPages: 4,
maxDepth: 2,
wallMs: 1_000,
maxTotalBytes: 1_000,
maxFrontier: 10,
concurrency: 2,
delayMs: 1,
retriesPerAdapter: 1,
maxRedirects: 1,
},
include: ['/**'],
exclude: [],
clock: () => 0,
sleep: async () => {},
});
assert.equal(result.accepted.length, 4);
assert.equal(maximumActive >= 1, true);
assert.equal(maximumActive <= 2, true);
});
test('P0 crawl spends retry budget once across the whole frontier', async (t) => {
const { storage } = await withStorage(t, 'lynceuz-p0-shared-retries-');
const calls = new Map();
let now = 0;
const response = (statusCode, body, headers = {}) => ({
statusCode,
headers,
body: Readable.from([Buffer.from(body)]),
peerAddress: P0_ADDRESS,
});
const gateway = createEgressGateway({
lookupAll: async () => [{ address: P0_ADDRESS, family: 4 }],
requestPinned: async ({ permit }) => {
const path = new URL(permit.canonicalUrl).pathname;
calls.set(path, (calls.get(path) ?? 0) + 1);
if (path === '/robots.txt') return response(200, 'User-agent: *\nAllow: /\n');
if (path === '/') {
return response(200, '<html><body><main>Root<a href="/a">A</a><a href="/b">B</a></main></body></html>', {
'content-type': 'text/html',
});
}
if (['/a', '/b'].includes(path) && calls.get(path) === 1) return response(503, 'retry');
return response(200, `<html><body><main>${path}</main></body></html>`, {
'content-type': 'text/html',
});
},
connectPinned: async () => { throw new Error('tunnel disabled'); },
now: () => now,
});
const job = crawlJob(`${P0_ORIGIN}/`,
'--max-pages', '3', '--max-depth', '2', '--max-time', '10', '--max-bytes', '65536',
'--max-frontier', '10', '--concurrency', '1', '--delay', '0.001', '--retries', '1');
const result = await runCrawlJob(job, {
gateway,
storage,
clock: () => now,
sleep: async (milliseconds) => { now += milliseconds; },
});
const manifest = await storedJson(storage, result.manifest_path);
assert.equal(result.status, 'partial');
assert.equal(calls.get('/a'), 2);
assert.equal(calls.get('/b'), 1);
assert.equal(manifest.crawl.accepted.some(({ url }) => url.endsWith('/a')), true);
assert.equal(manifest.crawl.failed.some(({ url }) => url.endsWith('/b')), true);
assert.equal(manifest.crawl.usage.retriesUsed, 1);
});
test('P0 crawl spends redirect budget once across the whole frontier', async (t) => {
const { storage } = await withStorage(t, 'lynceuz-p0-shared-redirects-');
const calls = new Map();
let now = 0;
const response = (statusCode, body, headers = {}) => ({
statusCode,
headers,
body: Readable.from([Buffer.from(body)]),
peerAddress: P0_ADDRESS,
});
const gateway = createEgressGateway({
lookupAll: async () => [{ address: P0_ADDRESS, family: 4 }],
requestPinned: async ({ permit }) => {
const path = new URL(permit.canonicalUrl).pathname;
calls.set(path, (calls.get(path) ?? 0) + 1);
if (path === '/robots.txt') return response(200, 'User-agent: *\nAllow: /\n');
if (path === '/') {
return response(200, '<html><body><main>Root<a href="/a">A</a><a href="/b">B</a></main></body></html>', {
'content-type': 'text/html',
});
}
if (path === '/a') return response(302, '', { location: '/final-a' });
if (path === '/b') return response(302, '', { location: '/final-b' });
return response(200, `<html><body><main>${path}</main></body></html>`, {
'content-type': 'text/html',
});
},
connectPinned: async () => { throw new Error('tunnel disabled'); },
now: () => now,
});
const job = crawlJob(`${P0_ORIGIN}/`,
'--max-pages', '3', '--max-depth', '2', '--max-time', '10', '--max-bytes', '65536',
'--max-frontier', '10', '--concurrency', '1', '--delay', '0.001', '--max-redirects', '1');
const result = await runCrawlJob(job, {
gateway,
storage,
clock: () => now,
sleep: async (milliseconds) => { now += milliseconds; },
});
const manifest = await storedJson(storage, result.manifest_path);
assert.equal(result.status, 'partial');
assert.equal(calls.get('/final-a'), 1);
assert.equal(calls.has('/final-b'), false);
assert.equal(manifest.crawl.accepted.some(({ url }) => url.endsWith('/a')), true);
assert.equal(manifest.crawl.blocked.some(({ url }) => url.endsWith('/b')), true);
assert.equal(manifest.crawl.usage.redirectsUsed, 1);
});
test('P0 manifest failure exposes neither selected output nor cache index', async (t) => {
const workspace = await mkdtemp(join(tmpdir(), 'lynceuz-p0-manifest-failure-'));
t.after(async () => rm(workspace, { recursive: true, force: true }));
const dataRoot = join(workspace, '.lynceuz');
const fixture = createP0SiteFixture();
const storage = createStorage({
dataRoot,
clock: fixture.clock,
faultInjector(label) {
if (label === 'manifest_rename') throw new Error('injected manifest failure');
},
});
const job = compileJobSpec(parseArgv([
'url', `${P0_ORIGIN}/a`,
'--output', 'exports/page.md',
'--cache', 'use',
]));
await assert.rejects(
runUrlJob(job, {
gateway: fixture.gateway,
storage,
clock: fixture.clock,
sleep: fixture.sleep,
}),
/injected manifest failure/u,
);
const files = await walk(dataRoot);
assert.equal(files.some((path) => path.endsWith(`${sep}manifest.json`)), false);
assert.equal(files.some((path) => path.includes(`${sep}cache${sep}requests${sep}`)), false);
await assert.rejects(
readFile(join(dataRoot, 'exports', 'page.md')),
(error) => error?.code === 'ENOENT',
);
});
+450
View File
@@ -0,0 +1,450 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import {
mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile,
} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { evaluateReleaseGate, expectedBrowserFingerprint, runReleaseGate } from '../scripts/p1-release-gate.mjs';
import {
REQUIRED_BROWSER_PROOF_CHANNELS,
REQUIRED_CONTAINMENT_PROOF_CHANNELS,
createBrowserProofIntegrity,
} from '../src/browser-security.mjs';
import { compileJobSpec, parseArgv } from '../src/cli.mjs';
import { runUrlJob } from '../src/core.mjs';
import { createStorage } from '../src/storage.mjs';
import { P0_ORIGIN, createP0SiteFixture } from './fixtures/p0-site.mjs';
const PROJECT_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
const MARKER_RELATIVE = 'release/p1-release-proof-v1.json';
const NOW_MS = Date.parse('2026-08-30T12:00:00.000Z');
const SEALED_REASON = 'sandbox_loopback_scope_unproven';
const HASH = /^sha256:[0-9a-f]{64}$/u;
const P1_FILES = Object.freeze([
['evals/cloud.test.mjs', 'cloud-contract', true],
['evals/fixtures/interruption-worker.mjs', 'recovery-fixture', true],
['evals/p1-release.test.mjs', 'gate-contract', false],
['evals/recovery.test.mjs', 'recovery-contract', true],
['evals/search-budget.test.mjs', 'search-budget-contract', true],
['evals/search-cloud.test.mjs', 'search-contract', true],
]);
const TEST_FINGERPRINT = Object.freeze({
digest: `sha256:${'a'.repeat(64)}`,
runtime: Object.freeze({
platform: 'fixture-platform',
arch: 'fixture-arch',
node: 'fixture-node',
python: 'fixture-python',
playwright: 'fixture-playwright',
chromium: `sha256:${'b'.repeat(64)}`,
containment: `sha256:${'c'.repeat(64)}`,
profile: `sha256:${'d'.repeat(64)}`,
}),
sources: Object.freeze({ gate_contract: `sha256:${'e'.repeat(64)}` }),
});
function stableJson(value) {
if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
if (value && typeof value === 'object') {
return `{${Object.keys(value).sort().map((key) => (
`${JSON.stringify(key)}:${stableJson(value[key])}`
)).join(',')}}`;
}
return JSON.stringify(value);
}
function sha256(value) {
return `sha256:${createHash('sha256').update(value).digest('hex')}`;
}
async function fileHash(relativePath) {
return sha256(await readFile(join(PROJECT_ROOT, relativePath)));
}
async function suiteManifest() {
return {
kind: 'lynceuz_p1_suite_manifest',
schema_version: 1,
baseline_manifest: {
path: 'evals/fixtures/p0-suite-hashes.json',
sha256: await fileHash('evals/fixtures/p0-suite-hashes.json'),
},
files: await Promise.all(P1_FILES.map(async ([path, role, runByReleaseGate]) => ({
path,
sha256: await fileHash(path),
role,
run_by_release_gate: runByReleaseGate,
}))),
};
}
function browserProof(generatedAt = new Date(NOW_MS).toISOString()) {
const suites = [
'evals/browser-hostile.test.mjs',
'evals/router.test.mjs',
'evals/p0-acceptance.test.mjs',
].map((suite) => ({
suite,
passed: true,
skipped: false,
exit_code: 0,
signal: null,
duration_ms: 1,
stdout_hash: `sha256:${'1'.repeat(64)}`,
stderr_hash: `sha256:${'2'.repeat(64)}`,
}));
const draft = {
kind: 'browser_security_proof',
schema_version: 1,
status: 'passed',
reason: 'proof_valid',
fingerprint: TEST_FINGERPRINT.digest,
generated_at: generatedAt,
platform: TEST_FINGERPRINT.runtime.platform,
arch: TEST_FINGERPRINT.runtime.arch,
runtime: TEST_FINGERPRINT.runtime,
source_hashes: TEST_FINGERPRINT.sources,
channels: Object.fromEntries(REQUIRED_BROWSER_PROOF_CHANNELS.map((name) => [name, true])),
suites,
};
return { ...draft, marker_hash: createBrowserProofIntegrity(draft) };
}
async function temporaryDataRoot(t, prefix) {
const workspace = await mkdtemp(join(tmpdir(), prefix));
t.after(() => rm(workspace, { recursive: true, force: true }));
return join(workspace, '.lynceuz');
}
async function writeProof(dataRoot, value) {
const path = join(dataRoot, 'security/browser-proof-v1.json');
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
await writeFile(path, typeof value === 'string' ? value : JSON.stringify(value), { mode: 0o600 });
}
function child(status, output) {
return Object.freeze({
status,
signal: null,
stdout: `${JSON.stringify(output)}\n`,
stderr: '',
});
}
function injectedRunner({ dataRoot, proof = 'valid', failSuite = false, browserReason = null }) {
const calls = [];
const runner = async (executable, argv, options) => {
assert.equal(executable, process.execPath);
assert.equal(options.shell, false);
assert.ok(Number.isSafeInteger(options.timeout) && options.timeout > 0);
assert.ok(Number.isSafeInteger(options.maxBuffer) && options.maxBuffer <= 2 * 1024 * 1024);
calls.push({ executable, argv: [...argv], options: { ...options } });
const isBrowserGate = argv.some((value) => value.endsWith('scripts/p1-browser-gate.mjs'));
if (isBrowserGate) {
if (browserReason) {
return child(1, { kind: 'browser_security_proof', status: 'failed', reason: browserReason });
}
if (proof === 'valid') await writeProof(dataRoot, browserProof());
if (proof === 'stale') await writeProof(dataRoot, browserProof('2020-01-01T00:00:00.000Z'));
if (proof === 'tampered') await writeProof(dataRoot, '{"tampered":');
return child(0, browserProof());
}
assert.equal(argv[0], '--test');
assert.equal(argv.some((value) => value.endsWith('evals/p1-release.test.mjs')), false, 'recursion');
if (failSuite) return child(1, { status: 'failed', reason: 'suite_failed' });
return child(0, { status: 'passed', reason: 'suite_passed' });
};
return { runner, calls };
}
async function evaluate(t, runnerOptions = {}) {
const dataRoot = await temporaryDataRoot(t, 'lynceuz-p1-release-');
const manifest = await suiteManifest();
const injected = injectedRunner({ dataRoot, ...runnerOptions });
const result = await evaluateReleaseGate({
dataRoot,
projectRoot: PROJECT_ROOT,
suiteManifest: manifest,
fingerprint: TEST_FINGERPRINT,
now: () => NOW_MS,
runner: injected.runner,
});
return { dataRoot, manifest, result, calls: injected.calls };
}
async function assertNoMarker(dataRoot) {
await assert.rejects(
readFile(join(dataRoot, MARKER_RELATIVE)),
(error) => error?.code === 'ENOENT',
);
}
test('valid proof and green non-recursive suites atomically seal the P1 release marker', async (t) => {
const { dataRoot, manifest, result, calls } = await evaluate(t);
const markerPath = join(dataRoot, MARKER_RELATIVE);
const markerBytes = await readFile(markerPath);
const marker = JSON.parse(markerBytes);
assert.equal(result.accepted, true);
assert.equal(result.exit_code, 0);
assert.equal(result.status, 'passed');
assert.equal(result.p1_release_state, 'released');
assert.equal(result.kind, 'lynceuz_p1_release_proof');
assert.equal(result.marker_path, MARKER_RELATIVE);
assert.equal(marker.kind, 'lynceuz_p1_release_proof');
assert.equal(marker.cost_money, 0);
assert.deepEqual(marker.suite_hashes, {
p0: manifest.baseline_manifest.sha256,
p1: sha256(stableJson(manifest)),
});
assert.equal(marker.browser_proof_hash, sha256(await readFile(
join(dataRoot, 'security/browser-proof-v1.json'),
)));
assert.match(marker.marker_hash, HASH);
const { marker_hash: markerHash, ...markerPayload } = marker;
assert.equal(markerHash, sha256(stableJson(markerPayload)));
assert.equal((await stat(markerPath)).mode & 0o777, 0o600);
assert.deepEqual(await readdir(dirname(markerPath)), ['p1-release-proof-v1.json']);
const invoked = calls.flatMap(({ argv }) => argv);
assert.equal(invoked.some((value) => value.endsWith('evals/p1-release.test.mjs')), false);
for (const entry of manifest.files.filter((item) => item.run_by_release_gate)) {
assert.equal(invoked.some((value) => value.endsWith(entry.path)), true, entry.path);
}
});
test('missing, stale and tampered proof are exact accepted browser blocks without marker', async (t) => {
for (const [proof, reason] of [
['missing', 'proof_missing'],
['stale', 'proof_stale'],
['tampered', 'proof_corrupt'],
]) {
await t.test(proof, async (subtest) => {
const { dataRoot, result } = await evaluate(subtest, { proof });
assert.equal(result.accepted, true);
assert.notEqual(result.exit_code, 0);
assert.equal(result.status, 'blocked');
assert.equal(result.p1_release_state, 'blocked_browser');
assert.equal(result.reason, reason);
await assertNoMarker(dataRoot);
});
}
});
test('sealed browser reason remains exact and does not create a marker', async (t) => {
const { dataRoot, result } = await evaluate(t, { browserReason: SEALED_REASON });
assert.equal(result.accepted, true);
assert.notEqual(result.exit_code, 0);
assert.equal(result.p1_release_state, 'blocked_browser');
assert.equal(result.reason, SEALED_REASON);
await assertNoMarker(dataRoot);
});
test('suite failure, gate error and arbitrary browser reason are rejected, not browser blocks', async (t) => {
await t.test('suite_failed', async (subtest) => {
const { dataRoot, result, calls } = await evaluate(subtest, { failSuite: true });
assert.equal(result.accepted, false);
assert.notEqual(result.exit_code, 0);
assert.equal(result.p1_release_state, 'rejected');
assert.equal(result.reason, 'suite_failed');
assert.equal(calls.some(({ argv }) => argv.some((value) => (
value.endsWith('scripts/p1-browser-gate.mjs')
))), false);
await assertNoMarker(dataRoot);
});
await t.test('gate_internal_error', async (subtest) => {
const dataRoot = await temporaryDataRoot(subtest, 'lynceuz-p1-error-');
const result = await evaluateReleaseGate({
dataRoot,
projectRoot: PROJECT_ROOT,
suiteManifest: await suiteManifest(),
fingerprint: TEST_FINGERPRINT,
now: () => NOW_MS,
runner: async () => { throw new Error('fixture runner failure'); },
});
assert.equal(result.accepted, false);
assert.notEqual(result.exit_code, 0);
assert.equal(result.p1_release_state, 'rejected');
assert.equal(result.reason, 'gate_internal_error');
await assertNoMarker(dataRoot);
});
await t.test('arbitrary_reason', async (subtest) => {
const { dataRoot, result } = await evaluate(subtest, { browserReason: 'invented_bypass' });
assert.equal(result.accepted, false);
assert.notEqual(result.exit_code, 0);
assert.equal(result.p1_release_state, 'rejected');
assert.equal(result.reason, 'invented_bypass');
await assertNoMarker(dataRoot);
});
});
test('native P0 evidence remains successful when P1 is browser-blocked', async (t) => {
const dataRoot = await temporaryDataRoot(t, 'lynceuz-p0-independent-');
const fixture = createP0SiteFixture();
const storage = createStorage({ dataRoot, clock: fixture.clock });
const job = compileJobSpec(parseArgv([
'url', `${P0_ORIGIN}/`, '--cache', 'off', '--data-root', dataRoot,
]));
const p0 = await runUrlJob(job, {
gateway: fixture.gateway,
storage,
clock: fixture.clock,
sleep: fixture.sleep,
});
const p0Bytes = await readFile(join(dataRoot, p0.manifest_path));
const injected = injectedRunner({ dataRoot, browserReason: SEALED_REASON });
const p1 = await evaluateReleaseGate({
dataRoot,
projectRoot: PROJECT_ROOT,
suiteManifest: await suiteManifest(),
fingerprint: TEST_FINGERPRINT,
now: () => NOW_MS,
runner: injected.runner,
});
assert.equal(p0.status, 'ok');
assert.match(p0.source_hash, HASH);
assert.equal(JSON.parse(p0Bytes).cost_money, 0);
assert.equal(p1.p1_release_state, 'blocked_browser');
assert.equal(p1.reason, SEALED_REASON);
assert.deepEqual(await readFile(join(dataRoot, p0.manifest_path)), p0Bytes);
await assertNoMarker(dataRoot);
});
const READY_SUITES = Object.freeze([
'evals/browser-hostile.test.mjs',
'evals/router.test.mjs',
'evals/p0-acceptance.test.mjs',
'evals/browser-containment.test.mjs',
]);
// A valid macOS containment receipt shape — the independent, root-generated facts the release gate
// fingerprints (never the proof itself). Fields mirror what containmentEvidence maps.
function readyContainmentReceipt() {
return {
backend: 'pf_uid_anchor_guardproxy',
uid: { name: '_lynceuz', uid: 401, gid: 401 },
guard_proxy: { host: '127.0.0.1', port: 48191 },
pf: {
anchor_name: 'com.lynceuz/browser',
anchor_path: '/etc/pf.anchors/com.lynceuz.browser',
anchor_sha256: `sha256:${'a'.repeat(64)}`,
rules_sha256: `sha256:${'b'.repeat(64)}`,
},
boot_session: 'boot-fixture-0001',
reboot_verified: true,
reboot_verified_at: '2026-08-30T11:00:00.000Z',
source_hashes: { macos_containment: `sha256:${'c'.repeat(64)}`, canary: `sha256:${'d'.repeat(64)}` },
suite_hashes: { wave2: `sha256:${'e'.repeat(64)}` },
};
}
// The schema_version-2 (containment-bound) proof a ready browser gate seals, carrying exactly the
// supplied fingerprint. verifyBrowserSecurityProof accepts it only against a matching fingerprint.
function readyBrowserProof(fingerprint, generatedAt = new Date(NOW_MS).toISOString()) {
const suites = READY_SUITES.map((suite) => ({
suite,
passed: true,
skipped: false,
exit_code: 0,
signal: null,
duration_ms: 1,
stdout_hash: `sha256:${'1'.repeat(64)}`,
stderr_hash: `sha256:${'2'.repeat(64)}`,
}));
const draft = {
kind: 'browser_security_proof',
schema_version: 1,
status: 'passed',
reason: 'proof_valid',
fingerprint: fingerprint.digest,
generated_at: generatedAt,
platform: fingerprint.runtime.platform,
arch: fingerprint.runtime.arch,
runtime: fingerprint.runtime,
source_hashes: fingerprint.sources,
channels: Object.fromEntries(REQUIRED_CONTAINMENT_PROOF_CHANNELS.map((name) => [name, true])),
containment_state: 'ready',
containment: fingerprint.containment,
suites,
};
return { ...draft, marker_hash: createBrowserProofIntegrity(draft) };
}
function readyRunner({ dataRoot, proof }) {
return async (executable, argv) => {
if (argv.some((value) => value.endsWith('scripts/p1-browser-gate.mjs'))) {
await writeProof(dataRoot, proof);
return child(0, proof);
}
return child(0, { status: 'passed', reason: 'suite_passed' });
};
}
test('release gate expects the same fingerprint the ready proof carries', async (t) => {
const detectedRuntime = Object.freeze({
platform: 'darwin',
arch: 'arm64',
node: 'v-fixture',
python: '/opt/homebrew/bin/python3@3.13.1',
playwright: '1.55.0',
chromium: `sha256:${'b'.repeat(64)}`,
containment: `sha256:${'c'.repeat(64)}`,
});
const receipt = readyContainmentReceipt();
const receiptHash = sha256(JSON.stringify(receipt));
const detect = async () => ({ runtime: detectedRuntime });
const loadReceipt = async () => ({ receipt, receiptHash });
// MATCH: runReleaseGate rebuilds the expected fingerprint from the SAME machine + receipt the proof
// was sealed against, so its own internal expectation equals the proof's digest → sealed release.
// The proof is derived from expectedBrowserFingerprint only to learn what digest a ready gate emits;
// the gate under test recomputes it — the WIRING, not a hand-fed fingerprint, is what's exercised.
const matchRoot = await temporaryDataRoot(t, 'lynceuz-fp-match-');
const fingerprint = await expectedBrowserFingerprint({ dataRoot: matchRoot, detect, loadReceipt });
const proof = readyBrowserProof(fingerprint);
const released = await runReleaseGate({
dataRoot: matchRoot,
projectRoot: PROJECT_ROOT,
suiteManifest: await suiteManifest(),
now: () => NOW_MS,
runner: readyRunner({ dataRoot: matchRoot, proof }),
detect,
loadReceipt,
});
assert.equal(released.p1_release_state, 'released', released.reason);
assert.equal(released.reason, 'released');
assert.match(released.marker_hash, HASH);
// DRIFT: the proof on disk still carries the original digest, but the gate is driven with a tampered
// receipt, so runReleaseGate's own internal fingerprint diverges → fingerprint_mismatch, no marker.
// The proof cannot certify itself.
const driftRoot = await temporaryDataRoot(t, 'lynceuz-fp-drift-');
const tampered = { ...receipt, boot_session: `${receipt.boot_session}-tampered` };
const tamperedLoad = async () => ({ receipt: tampered, receiptHash: sha256(JSON.stringify(tampered)) });
const driftFingerprint = await expectedBrowserFingerprint({
dataRoot: driftRoot, detect, loadReceipt: tamperedLoad,
});
assert.notEqual(driftFingerprint.digest, fingerprint.digest);
const blocked = await runReleaseGate({
dataRoot: driftRoot,
projectRoot: PROJECT_ROOT,
suiteManifest: await suiteManifest(),
now: () => NOW_MS,
runner: readyRunner({ dataRoot: driftRoot, proof }),
detect,
loadReceipt: tamperedLoad,
});
assert.equal(blocked.p1_release_state, 'blocked_browser');
assert.equal(blocked.reason, 'fingerprint_mismatch');
await assertNoMarker(driftRoot);
});
+348
View File
@@ -0,0 +1,348 @@
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { createEgressGateway } from '../src/network.mjs';
import {
PolicyError,
authorizeCost,
authorizeResolvedTarget,
classifyIpAddress,
classifyTerminalOutcome,
parsePublicUrl,
} from '../src/policy.mjs';
import { createNoNetworkPorts } from './fixtures/no-network.mjs';
const corpus = JSON.parse(await readFile(
new URL('./fixtures/hostile-urls.json', import.meta.url),
'utf8',
));
const intent = (url, redirects = 3) => ({
runId: 'run-test',
purpose: 'page',
url,
method: 'GET',
remaining: { wallMs: 10_000, bytes: 1_000_000, redirects },
});
test('public URL parser canonicalizes allowed targets and strips fragments', () => {
for (const item of corpus.allow) {
const parsed = parsePublicUrl(item.input);
assert.equal(parsed.canonicalUrl, item.canonical);
assert.equal(parsed.canonicalUrl.includes('#'), false);
assert.ok([80, 443].includes(parsed.port));
}
});
test('hostile URL corpus is rejected with sanitized typed errors', () => {
for (const input of corpus.deny) {
assert.throws(
() => parsePublicUrl(input),
(error) => {
assert.ok(error instanceof PolicyError, input);
assert.equal(typeof error.code, 'string');
assert.equal(error.message.includes(input), false);
assert.equal(error.message.includes('secret-value'), false);
return true;
},
);
}
});
test('IP classifier allows global addresses and blocks special-use ranges', () => {
for (const address of ['8.8.8.8', '93.184.216.34', '2606:4700:4700::1111']) {
assert.equal(classifyIpAddress(address).public, true, address);
}
for (const address of [
'0.0.0.0', '10.0.0.1', '100.64.0.1', '127.0.0.1', '169.254.169.254',
'172.16.0.1', '192.0.2.1', '192.168.1.1', '198.18.0.1', '198.51.100.2',
'203.0.113.1', '224.0.0.1', '255.255.255.255', '::', '::1', '::ffff:8.8.8.8',
'64:ff9b::808:808', '100::1', '2001:db8::1', '2002::1', '3fff::1',
'fc00::1', 'fe80::1', 'fec0::1', 'ff00::1',
]) {
assert.equal(classifyIpAddress(address).public, false, address);
}
for (const invalidAddress of ['999.1.1.1', '1.2.3', 'gggg::1', '1::2::3', 'fe80::1%en0']) {
assert.throws(() => classifyIpAddress(invalidAddress), /IP address/);
}
});
test('all DNS answers must be public and deterministic selection is stable', () => {
const parsed = parsePublicUrl('https://example.com/');
const first = authorizeResolvedTarget(parsed, [
{ address: '2606:4700:4700::1111', family: 6 },
{ address: '93.184.216.35', family: 4 },
{ address: '93.184.216.34', family: 4 },
]);
const second = authorizeResolvedTarget(parsed, [
{ address: '93.184.216.34', family: 4 },
{ address: '2606:4700:4700::1111', family: 6 },
{ address: '93.184.216.35', family: 4 },
]);
assert.equal(first.selectedAddress, '93.184.216.34');
assert.deepEqual(first, second);
assert.ok(Object.isFrozen(first));
assert.throws(
() => authorizeResolvedTarget(parsed, [
{ address: '93.184.216.34', family: 4 },
{ address: '127.0.0.1', family: 4 },
]),
/DNS answer is not public/,
);
assert.throws(() => authorizeResolvedTarget(parsed, []), /DNS answer set is empty/);
assert.throws(
() => authorizeResolvedTarget(parsed, [{ address: '93.184.216.34', family: 6 }]),
/DNS address family mismatch/,
);
});
test('only proven local zero cost is eligible', () => {
assert.deepEqual(authorizeCost({ cost: 'local-zero', price: 0 }), {
allowed: true,
state: 'allowed_zero',
reason: 'proven_local_zero',
});
for (const descriptor of [
{ cost: 'local-zero' },
{ cost: 'local-zero', price: 1 },
{ cost: 'paid', price: 1 },
{ cost: 'free-credit', price: 0, balance: 100 },
{ cost: 'free-credit', price: 0 },
{},
]) {
assert.equal(authorizeCost(descriptor).allowed, false);
assert.equal(authorizeCost(descriptor).state, 'unknown_and_blocked');
}
});
test('terminal policy/access outcomes cannot enter fallback', () => {
for (const code of [
'policy_denied', 'robots_denied', 'access_denied', 'auth_required', 'captcha',
'paywall', 'paid_required', 'hard_limit',
]) {
assert.deepEqual(classifyTerminalOutcome({ code }), {
terminal: true,
status: 'blocked',
code,
});
}
for (const code of ['not_found', 'gone']) {
assert.equal(classifyTerminalOutcome({ code }).status, 'exhausted');
}
assert.equal(classifyTerminalOutcome({ code: 'rate_limited', exhausted: false }).terminal, false);
assert.equal(classifyTerminalOutcome({ code: 'rate_limited', exhausted: true }).status, 'blocked');
});
test('gateway denies unsafe input before lookup or request ports', async () => {
const ports = createNoNetworkPorts();
const gateway = createEgressGateway(ports);
await assert.rejects(
gateway.execute(intent('http://169.254.169.254/latest/meta-data/')),
/target IP is not public/,
);
await assert.rejects(
gateway.execute(intent('https://example.com/?token=secret-value')),
/sensitive query key/,
);
assert.deepEqual(ports.counters, {
lookupAll: 0,
connectPinned: 0,
requestPinned: 0,
spawn: 0,
});
});
test('gateway pins deterministic address and verifies request peer', async () => {
let receivedPermit;
const ports = createNoNetworkPorts({
lookupAll: async () => [
{ address: '93.184.216.35', family: 4 },
{ address: '93.184.216.34', family: 4 },
],
requestPinned: async ({ permit }) => {
receivedPermit = permit;
return { statusCode: 200, headers: {}, body: Buffer.from('ok'), peerAddress: '93.184.216.34' };
},
});
const gateway = createEgressGateway(ports);
const response = await gateway.execute(intent('https://example.com/'));
assert.equal(receivedPermit.selectedAddress, '93.184.216.34');
assert.equal(response.permit.selectedAddress, '93.184.216.34');
assert.equal(response.finalUrl, 'https://example.com/');
assert.equal(ports.counters.lookupAll, 1);
assert.equal(ports.counters.requestPinned, 1);
const mismatch = createNoNetworkPorts({
lookupAll: async () => [{ address: '93.184.216.34', family: 4 }],
requestPinned: async () => ({ statusCode: 200, headers: {}, body: null, peerAddress: '93.184.216.35' }),
});
await assert.rejects(
createEgressGateway(mismatch).execute(intent('https://example.com/')),
/peer address mismatch/,
);
const mappedPeer = createNoNetworkPorts({
lookupAll: async () => [{ address: '93.184.216.34', family: 4 }],
requestPinned: async () => ({
statusCode: 200,
headers: {},
body: null,
peerAddress: '::ffff:93.184.216.34',
}),
});
assert.equal(
(await createEgressGateway(mappedPeer).execute(intent('https://example.com/'))).statusCode,
200,
);
});
test('tunnel uses a fresh permit and rejects peer mismatch', async () => {
let receivedPermit;
const ports = createNoNetworkPorts({
lookupAll: async () => [{ address: '2606:4700:4700::1111', family: 6 }],
connectPinned: async ({ permit }) => {
receivedPermit = permit;
return { socket: { id: 1 }, peerAddress: '2606:4700:4700::1111' };
},
});
const opened = await createEgressGateway(ports).openAuthorizedTunnel(intent('https://example.com/'));
assert.equal(opened.socket.id, 1);
assert.equal(receivedPermit.selectedAddress, '2606:4700:4700::1111');
const mismatch = createNoNetworkPorts({
lookupAll: async () => [{ address: '93.184.216.34', family: 4 }],
connectPinned: async () => ({ socket: {}, peerAddress: '8.8.8.8' }),
});
await assert.rejects(
createEgressGateway(mismatch).openAuthorizedTunnel(intent('https://example.com/')),
/peer address mismatch/,
);
});
test('redirects close bodies and cross a new URL, DNS and peer gate', async () => {
const lookups = [];
const permits = [];
let closed = 0;
const ports = createNoNetworkPorts({
lookupAll: async (hostname) => {
lookups.push(hostname);
return [{ address: hostname === 'example.com' ? '93.184.216.34' : '8.8.8.8', family: 4 }];
},
requestPinned: async ({ permit }) => {
permits.push(permit);
if (permit.hostname === 'example.com') {
return {
statusCode: 302,
headers: { Location: 'https://example.net/final#frag' },
body: { destroy: () => { closed += 1; } },
peerAddress: '93.184.216.34',
};
}
return { statusCode: 200, headers: {}, body: Buffer.from('done'), peerAddress: '8.8.8.8' };
},
});
const result = await createEgressGateway(ports).execute(intent('https://example.com/start'));
assert.deepEqual(lookups, ['example.com', 'example.net']);
assert.equal(permits.length, 2);
assert.notEqual(permits[0], permits[1]);
assert.equal(closed, 1);
assert.equal(result.finalUrl, 'https://example.net/final');
assert.deepEqual(result.redirectChain, [{
statusCode: 302,
from: 'https://example.com/start',
to: 'https://example.net/final',
}]);
});
test('unsafe redirect, loop, downgrade and hop exhaustion stop before next request', async () => {
const scenario = async (location, redirects = 3) => {
const ports = createNoNetworkPorts({
lookupAll: async () => [{ address: '93.184.216.34', family: 4 }],
requestPinned: async () => ({
statusCode: 302,
headers: { location },
body: { destroy() {} },
peerAddress: '93.184.216.34',
}),
});
const promise = createEgressGateway(ports).execute(intent('https://example.com/start', redirects));
return { ports, promise };
};
for (const [location, redirects, message] of [
['http://169.254.169.254/latest', 3, /redirect downgrade|target IP is not public/],
['https://127.0.0.1/private', 3, /target IP is not public/],
['https://example.com/start', 3, /redirect loop/],
['https://example.net/next', 0, /redirect limit/],
['http://example.net/next', 3, /redirect downgrade/],
]) {
const { ports, promise } = await scenario(location, redirects);
await assert.rejects(promise, message);
assert.equal(ports.counters.requestPinned, 1, location);
}
});
test('malformed redirect headers fail closed and close the response body', async () => {
for (const headers of [
{},
{ location: [] },
{ location: ['https://example.net/a', 'https://example.net/b'] },
{ location: 42 },
{ location: 'https://example.net/a', Location: 'https://example.net/b' },
{ location: 'https://example.net/a\r\nX-Test: injected' },
]) {
let closed = 0;
const ports = createNoNetworkPorts({
lookupAll: async () => [{ address: '93.184.216.34', family: 4 }],
requestPinned: async () => ({
statusCode: 302,
headers,
body: { destroy: () => { closed += 1; } },
peerAddress: '93.184.216.34',
}),
});
await assert.rejects(
createEgressGateway(ports).execute(intent('https://example.com/')),
/redirect response is invalid/,
);
assert.equal(closed, 1);
assert.equal(ports.counters.requestPinned, 1);
}
});
test('resolver failures and empty DNS fail closed without request port', async () => {
for (const lookupAll of [
async () => [],
async () => { throw new Error('resolver leaked secret'); },
]) {
const ports = createNoNetworkPorts({ lookupAll });
await assert.rejects(
createEgressGateway(ports).execute(intent('https://example.com/')),
(error) => {
assert.ok(error instanceof PolicyError);
assert.equal(error.message.includes('resolver leaked secret'), false);
return true;
},
);
assert.equal(ports.counters.requestPinned, 0);
}
});
test('injected port errors are sanitized at the gateway boundary', async () => {
const ports = createNoNetworkPorts({
lookupAll: async () => [{ address: '93.184.216.34', family: 4 }],
requestPinned: async () => {
throw new PolicyError('leak', 'leaked https://user:secret@example.com/');
},
});
await assert.rejects(
createEgressGateway(ports).execute(intent('https://example.com/')),
(error) => {
assert.equal(error.code, 'request_failed');
assert.equal(error.message.includes('secret'), false);
assert.equal(error.message.includes('example.com'), false);
return true;
},
);
});
+385
View File
@@ -0,0 +1,385 @@
import assert from 'node:assert/strict';
import { fork } from 'node:child_process';
import { EventEmitter } from 'node:events';
import {
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
rm,
symlink,
unlink,
writeFile,
} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import { EXIT_CODE, RUN_STATUS } from '../src/contracts.mjs';
import * as core from '../src/core.mjs';
import { createRequestFingerprint, createStorage } from '../src/storage.mjs';
// Requirement: DATA-05 — interruption + crash recovery contract.
const FIXED_TIME = '2026-08-26T12:15:40.123Z';
const REQUESTED_URL = 'https://example.com/interrupted';
const clock = () => new Date(FIXED_TIME);
const WORKER = fileURLToPath(new URL('./fixtures/interruption-worker.mjs', import.meta.url));
function fingerprint() {
return createRequestFingerprint({
canonicalUrl: REQUESTED_URL,
method: 'GET',
headers: { accept: 'text/html', 'accept-encoding': 'gzip' },
adapter: { id: 'native', version: '1' },
policyVersion: '1',
format: 'markdown',
goal: 'markdown',
decode: { encodings: ['gzip'], maxBytes: 1_048_576 },
});
}
async function withSandbox(fn) {
const sandbox = await mkdtemp(join(tmpdir(), 'lynceuz-recovery-'));
const dataRoot = join(sandbox, '.lynceuz');
try {
await fn({ sandbox, dataRoot });
} finally {
await rm(sandbox, { recursive: true, force: true });
}
}
async function walk(root) {
const found = [];
async function visit(path) {
const info = await lstat(path);
found.push({ path, info });
if (info.isDirectory()) {
for (const name of await readdir(path)) await visit(join(path, name));
}
}
await visit(root);
return found;
}
// Reach the deterministic milestone in a real child, then hand the caller the
// live handle. Resolves on the IPC milestone OR an early exit so a missing guard
// (the RED target) surfaces as a wrong exit code, never a hang.
async function startWorker(config) {
const child = fork(WORKER, [JSON.stringify(config)], {
stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
});
const exited = new Promise((resolve) => {
child.once('exit', (code, signal) => resolve({ code, signal }));
});
const readied = new Promise((resolve) => child.once('message', resolve));
const first = await Promise.race([
readied.then((message) => ({ type: 'ready', message })),
exited.then((exit) => ({ type: 'exit', exit })),
]);
return { child, exited, ready: first.type === 'ready' ? first.message : null };
}
// Build an incomplete run on disk (no manifest) using only shipped storage APIs.
async function seedIncompleteRun(storage, label) {
const run = await storage.beginRun({
schema_version: 1,
command: 'url',
requested_url: REQUESTED_URL,
method: 'GET',
format: 'markdown',
cache: 'use',
});
const source = await storage.putObject(run, Buffer.from(`evidence ${label}`), {
role: 'raw', media_type: 'text/plain', derived_from: null,
});
await storage.appendAttempt(run, {
type: 'attempt_finished', at: FIXED_TIME, outcome: 'ok', source_hash: source.hash,
});
return { run, source };
}
// ---------------------------------------------------------------------------
// Edge 1 — graceful interruption: signal/timeout -> one interrupted commit.
// ---------------------------------------------------------------------------
test('SIGINT interrupts a live run: exit 130, interrupted manifest, signal recorded, no cache hit', async () => {
await withSandbox(async ({ dataRoot }) => {
const worker = await startWorker({ mode: 'signal', dataRoot });
if (worker.ready) worker.child.kill('SIGINT');
const { code } = await worker.exited;
assert.equal(code, EXIT_CODE.SIGINT, 'SIGINT must finalize as interrupted and exit 130');
assert.ok(worker.ready?.runId, 'worker must confirm its milestone before the signal');
const manifest = JSON.parse(
await readFile(join(dataRoot, 'runs', worker.ready.runId, 'manifest.json'), 'utf8'),
);
assert.equal(manifest.status, RUN_STATUS.INTERRUPTED);
assert.deepEqual(manifest.termination, { signal: 'SIGINT' });
assert.equal(manifest.source_hash, worker.ready.sourceHash);
const reopened = createStorage({ dataRoot, clock });
const cached = await reopened.readCache(fingerprint());
assert.equal(cached.hit, false, 'an interrupted run must never publish a cache hit');
});
});
test('SIGTERM interrupts a live run: exit 143 with SIGTERM termination', async () => {
await withSandbox(async ({ dataRoot }) => {
const worker = await startWorker({ mode: 'signal', dataRoot });
if (worker.ready) worker.child.kill('SIGTERM');
const { code } = await worker.exited;
assert.equal(code, EXIT_CODE.SIGTERM, 'SIGTERM must finalize as interrupted and exit 143');
const manifest = JSON.parse(
await readFile(join(dataRoot, 'runs', worker.ready.runId, 'manifest.json'), 'utf8'),
);
assert.equal(manifest.status, RUN_STATUS.INTERRUPTED);
assert.deepEqual(manifest.termination, { signal: 'SIGTERM' });
});
});
test('wall-clock timeout interrupts a live run: exit 124 with reason=timeout', async () => {
await withSandbox(async ({ dataRoot }) => {
const worker = await startWorker({ mode: 'timeout', dataRoot, wallMs: 40 });
const { code } = await worker.exited;
assert.equal(code, EXIT_CODE.TIMEOUT, 'a wall-clock timeout must exit 124');
const manifest = JSON.parse(
await readFile(join(dataRoot, 'runs', worker.ready.runId, 'manifest.json'), 'utf8'),
);
assert.equal(manifest.status, RUN_STATUS.INTERRUPTED);
assert.deepEqual(manifest.termination, { reason: 'timeout' });
});
});
test('a double SIGINT commits exactly one interrupted manifest and detaches its listeners', async () => {
assert.equal(
typeof core.createInterruptionGuard,
'function',
'core must expose createInterruptionGuard',
);
await withSandbox(async ({ dataRoot }) => {
const storage = createStorage({ dataRoot, clock });
const { run, source } = await seedIncompleteRun(storage, 'double');
const emitter = new EventEmitter();
const exits = [];
const guard = core.createInterruptionGuard({
storage,
run,
emitter,
exit: (code) => exits.push(code),
buildInterruptedManifest: (termination) => ({
schema_version: 1,
run_id: run.id,
status: 'interrupted',
requested_url: REQUESTED_URL,
effective_url: REQUESTED_URL,
requested_format: 'markdown',
format: 'markdown',
alternatives: [],
fetched_at: null,
served_at: FIXED_TIME,
revalidated_at: null,
engine: { id: 'native', version: '1' },
policy: { version: '1', network: 'public-only', auth: 'none', money_budget: 0 },
attempts: [],
source_hash: source.hash,
artifact_hash: null,
artifact_path: null,
artifacts: [source],
evidence: [{ url: REQUESTED_URL, hash: source.hash, status: 'source_captured' }],
warnings: [],
cost_money: 0,
credits_used: 0,
termination,
}),
});
guard.install();
emitter.emit('SIGINT');
emitter.emit('SIGINT');
await guard.done;
assert.equal(guard.commitCount, 1, 'redundant signals must not double-commit');
assert.deepEqual(exits, [EXIT_CODE.SIGINT], 'the process must exit exactly once');
assert.equal(emitter.listenerCount('SIGINT'), 0, 'SIGINT listener must be detached');
assert.equal(emitter.listenerCount('SIGTERM'), 0, 'SIGTERM listener must be detached');
const manifest = JSON.parse(
await readFile(join(dataRoot, 'runs', run.id, 'manifest.json'), 'utf8'),
);
assert.equal(manifest.status, RUN_STATUS.INTERRUPTED);
assert.deepEqual(manifest.termination, { signal: 'SIGINT' });
});
});
test('a signal arriving during timeout finalization still yields one interrupted commit', async () => {
assert.equal(
typeof core.createInterruptionGuard,
'function',
'core must expose createInterruptionGuard',
);
await withSandbox(async ({ dataRoot }) => {
const storage = createStorage({ dataRoot, clock });
const { run, source } = await seedIncompleteRun(storage, 'race');
const emitter = new EventEmitter();
const exits = [];
let fireTimeout;
const guard = core.createInterruptionGuard({
storage,
run,
emitter,
wallMs: 25,
exit: (code) => exits.push(code),
scheduler: {
setTimeout: (fn) => { fireTimeout = fn; return { fake: true }; },
clearTimeout: () => { fireTimeout = null; },
},
buildInterruptedManifest: (termination) => ({
schema_version: 1,
run_id: run.id,
status: 'interrupted',
requested_url: REQUESTED_URL,
effective_url: REQUESTED_URL,
requested_format: 'markdown',
format: 'markdown',
alternatives: [],
fetched_at: null,
served_at: FIXED_TIME,
revalidated_at: null,
engine: { id: 'native', version: '1' },
policy: { version: '1', network: 'public-only', auth: 'none', money_budget: 0 },
attempts: [],
source_hash: source.hash,
artifact_hash: null,
artifact_path: null,
artifacts: [source],
evidence: [{ url: REQUESTED_URL, hash: source.hash, status: 'source_captured' }],
warnings: [],
cost_money: 0,
credits_used: 0,
termination,
}),
});
guard.install();
assert.equal(typeof fireTimeout, 'function', 'wallMs must arm a timeout through the scheduler');
fireTimeout(); // deadline fires -> finalize(reason=timeout) starts
emitter.emit('SIGINT'); // signal races in mid-finalization
await guard.done;
assert.equal(guard.commitCount, 1, 'a racing signal must not add a second commit');
assert.deepEqual(exits, [EXIT_CODE.TIMEOUT], 'the timeout outcome must win the race');
const manifest = JSON.parse(
await readFile(join(dataRoot, 'runs', run.id, 'manifest.json'), 'utf8'),
);
assert.deepEqual(manifest.termination, { reason: 'timeout' });
});
});
// ---------------------------------------------------------------------------
// Edge 2 — crash recovery: a real SIGKILL before commit stays recoverable.
// ---------------------------------------------------------------------------
test('a real SIGKILL before commit leaves a recoverable incomplete run', async () => {
await withSandbox(async ({ dataRoot }) => {
const worker = await startWorker({ mode: 'crash', dataRoot });
assert.ok(worker.ready?.runId, 'worker must reach the milestone before the kill');
worker.child.kill('SIGKILL');
const { signal } = await worker.exited;
assert.equal(signal, 'SIGKILL', 'the child must die on the uncatchable kill');
// Killed strictly before commitManifest: no manifest on disk.
await assert.rejects(
lstat(join(dataRoot, 'runs', worker.ready.runId, 'manifest.json')),
{ code: 'ENOENT' },
);
const storage = createStorage({ dataRoot, clock });
assert.equal(
typeof storage.recoverIncompleteRuns,
'function',
'storage must expose recoverIncompleteRuns',
);
const report = await storage.recoverIncompleteRuns();
assert.ok(Array.isArray(report.incomplete));
const entry = report.incomplete.find((item) => item.run_id === worker.ready.runId);
assert.ok(entry, 'the killed run must be reported as incomplete');
assert.equal(entry.manifest_committed, false);
assert.ok(
entry.source_hashes.includes(worker.ready.sourceHash),
'recovery must preserve the captured evidence hashes',
);
// A mode-0600 incomplete.json is persisted under the data root.
const reportPath = join(dataRoot, 'incomplete.json');
const reportInfo = await lstat(reportPath);
assert.equal(reportInfo.mode & 0o777, 0o600, 'incomplete.json must be private');
const persisted = JSON.parse(await readFile(reportPath, 'utf8'));
assert.ok(persisted.incomplete.some((item) => item.run_id === worker.ready.runId));
// Recovery never fabricates a cache hit for an uncommitted run.
const cached = await storage.readCache(fingerprint());
assert.equal(cached.hit, false);
});
});
test('corrupt and symlink-escaping run state surfaces typed corruption, never escapes the data root', async () => {
await withSandbox(async ({ sandbox, dataRoot }) => {
const storage = createStorage({ dataRoot, clock });
const healthy = await seedIncompleteRun(storage, 'healthy');
const corrupt = await seedIncompleteRun(storage, 'corrupt');
const escaping = await seedIncompleteRun(storage, 'escape');
// Corrupt the journal with non-JSON content.
await writeFile(join(dataRoot, corrupt.run.path, 'attempts.ndjson'), '{ not json\n', {
mode: 0o600,
});
// Point the journal at a symlink escaping the data root.
const outside = join(sandbox, 'outside');
await mkdir(outside, { recursive: true, mode: 0o700 });
const stolen = join(outside, 'stolen.ndjson');
const journalPath = join(dataRoot, escaping.run.path, 'attempts.ndjson');
await unlink(journalPath);
await symlink(stolen, journalPath);
assert.equal(
typeof storage.recoverIncompleteRuns,
'function',
'storage must expose recoverIncompleteRuns',
);
const report = await storage.recoverIncompleteRuns();
// Healthy run still recovers; broken runs are quarantined as typed corruption.
assert.ok(report.incomplete.some((item) => item.run_id === healthy.run.id));
assert.ok(Array.isArray(report.corrupt));
for (const runId of [corrupt.run.id, escaping.run.id]) {
const flagged = report.corrupt.find((item) => item.run_id === runId);
assert.ok(flagged, `run ${runId} must be reported as corrupt`);
assert.equal(typeof flagged.corruption?.code, 'string');
assert.ok(flagged.corruption.code.length > 0, 'corruption must carry a typed code');
}
assert.ok(
!report.incomplete.some((item) => item.run_id === corrupt.run.id
|| item.run_id === escaping.run.id),
'corrupt runs must not masquerade as clean incomplete runs',
);
// The symlink was never followed and nothing landed outside the data root.
assert.deepEqual(await readdir(outside), [], 'the escaping symlink must not be written through');
for (const { path } of await walk(sandbox)) {
assert.ok(
path.startsWith(dataRoot) || path === sandbox || path === outside,
`recovery must not create state outside the data root: ${path}`,
);
}
const cached = await storage.readCache(fingerprint());
assert.equal(cached.hit, false);
});
});
+268
View File
@@ -0,0 +1,268 @@
import assert from 'node:assert/strict';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { compileJobSpec, parseArgv } from '../src/cli.mjs';
import {
buildRoutePlan,
createCapabilitySnapshot,
decideTransition,
healthReport,
runModelRoute,
} from '../src/router.mjs';
import { capability, scriptedAdapter } from './fixtures/fake-adapters.mjs';
const job = (argv = ['https://example.com']) => compileJobSpec(parseArgv(argv));
test('capability snapshot and route plan are immutable and deterministic', () => {
const registry = [
capability({ id: 'native' }),
capability({
id: 'playwright',
state: 'unavailable_security_gate',
reason: 'hostile_egress_proof_missing',
networkModel: 'guard-proxy',
}),
capability({
id: 'browser-use',
state: 'disabled',
reason: 'automatic_path_forbidden',
automatic: false,
networkModel: 'guard-proxy',
}),
capability({
id: 'firecrawl',
state: 'disabled',
reason: 'free_cloud_not_allowed',
cost: 'free-credit',
networkModel: 'provider-managed',
}),
];
const snapshot = createCapabilitySnapshot(registry);
const first = buildRoutePlan(job(), snapshot);
const second = buildRoutePlan(job(), snapshot);
assert.equal(JSON.stringify(first), JSON.stringify(second));
assert.ok(Object.isFrozen(snapshot));
assert.ok(Object.isFrozen(snapshot[0]));
assert.ok(Object.isFrozen(first));
assert.deepEqual(first.candidates.map(({ id }) => id), ['native', 'playwright', 'firecrawl']);
assert.equal(first.candidates.find(({ id }) => id === 'playwright').eligible, false);
assert.equal(first.candidates.find(({ id }) => id === 'firecrawl').costState, 'unknown_and_blocked');
const forced = buildRoutePlan(job(['https://example.com', '--engine', 'browser-use']), snapshot);
assert.equal(forced.candidates.length, 1);
assert.equal(forced.candidates[0].id, 'browser-use');
assert.equal(forced.candidates[0].automatic, false);
assert.equal(forced.candidates[0].state, 'disabled');
assert.equal(forced.candidates[0].eligible, false);
const unknown = buildRoutePlan(job(['https://example.com', '--engine', 'unknown']), snapshot);
assert.deepEqual(unknown.candidates, []);
});
test('health report preserves every known state, version and reason', () => {
const snapshot = createCapabilitySnapshot([
capability({ id: 'core', version: 'v24.0.0', state: 'ready' }),
capability({ id: 'parser', version: null, state: 'missing' }),
capability({ id: 'cloud', version: null, state: 'disabled' }),
capability({ id: 'broken', version: null, state: 'misconfigured' }),
capability({ id: 'browser', version: null, state: 'unavailable_security_gate' }),
]);
assert.deepEqual(healthReport(snapshot).map(({ id, state, version, reason }) => ({
id, state, version, reason,
})), snapshot.map(({ id, state, version, reason }) => ({ id, state, version, reason })));
});
test('transition table blocks terminal outcomes and never selects next adapter', () => {
for (const code of [
'policy_denied', 'robots_denied', 'access_denied', 'auth_required', 'captcha',
'paywall', 'paid_required', 'hard_limit',
]) {
const decision = decideTransition(
{ kind: 'terminal', code },
{ hasNext: true, retriesUsed: 0, retriesLimit: 2, maxRetryAfterMs: 15_000 },
);
assert.equal(decision.action, 'stop');
assert.equal(decision.status, 'blocked');
assert.equal(decision.code, code);
}
for (const code of ['not_found', 'gone']) {
const decision = decideTransition({ kind: 'terminal', code }, { hasNext: true });
assert.equal(decision.action, 'stop');
assert.equal(decision.status, 'exhausted');
}
});
test('rate limit retries only the same adapter with capped delay, then blocks', () => {
assert.deepEqual(
decideTransition(
{ kind: 'retryable', code: 'rate_limited', retryAfterMs: 60_000 },
{ hasNext: true, retriesUsed: 0, retriesLimit: 1, maxRetryAfterMs: 15_000 },
),
{ action: 'retry_same', delayMs: 15_000, status: null, code: 'rate_limited' },
);
assert.deepEqual(
decideTransition(
{ kind: 'retryable', code: 'rate_limited', retryAfterMs: 1 },
{ hasNext: true, retriesUsed: 1, retriesLimit: 1, maxRetryAfterMs: 15_000 },
),
{ action: 'stop', delayMs: 0, status: 'blocked', code: 'rate_limited' },
);
});
test('unknown or kind-mismatched outcomes stop as internal errors', () => {
for (const outcome of [
{ kind: 'skip', code: 'invented' },
{ kind: 'success', code: 'unavailable' },
null,
]) {
const decision = decideTransition(outcome, { hasNext: true });
assert.equal(decision.action, 'stop');
assert.equal(decision.status, 'internal_error');
assert.equal(decision.code, 'unknown_attempt_code');
}
});
test('model route skips only typed unavailable adapter and can reach success', async () => {
const snapshot = createCapabilitySnapshot([
capability({ id: 'first' }),
capability({ id: 'second' }),
]);
const first = scriptedAdapter([{ kind: 'skip', code: 'unavailable' }]);
const second = scriptedAdapter([{ kind: 'success', code: 'ok' }]);
const result = await runModelRoute(job(), snapshot, {
adapters: new Map([['first', first], ['second', second]]),
});
assert.equal(result.status, 'ok');
assert.equal(first.calls.length, 1);
assert.equal(second.calls.length, 1);
});
test('model route never calls fallback after terminal outcome', async () => {
for (const terminal of [
{ kind: 'terminal', code: 'access_denied' },
{ kind: 'terminal', code: 'not_found' },
{ kind: 'retryable', code: 'rate_limited', retryAfterMs: 0 },
]) {
const snapshot = createCapabilitySnapshot([
capability({ id: 'first' }),
capability({ id: 'second' }),
]);
const first = scriptedAdapter([terminal, terminal, terminal]);
const second = scriptedAdapter([{ kind: 'success', code: 'ok' }]);
const result = await runModelRoute(job(), snapshot, {
adapters: new Map([['first', first], ['second', second]]),
sleep: async () => {},
});
assert.notEqual(result.status, 'ok');
assert.equal(second.calls.length, 0, terminal.code);
}
});
async function runBlackBox(args) {
const cwd = await mkdtemp(join(tmpdir(), 'lynceuz-empty-'));
try {
const executable = fileURLToPath(new URL('../src/lynceuz.mjs', import.meta.url));
const tripwire = fileURLToPath(new URL('./fixtures/no-network.mjs', import.meta.url));
return spawnSync(process.execPath, [
'--import', tripwire,
executable,
...args,
], {
cwd,
encoding: 'utf8',
env: { ...process.env, LYNCEUZ_FORBID_NETWORK: '1' },
timeout: 10_000,
});
} finally {
await rm(cwd, { recursive: true, force: true });
}
}
test('health and explain are zero-call black-box commands under tripwire', async () => {
const health = await runBlackBox(['health', '--json']);
assert.equal(health.status, 0, health.stderr);
assert.equal(health.signal, null);
assert.equal(health.stdout.match(/\n/g)?.length, 1);
const healthResult = JSON.parse(health.stdout);
assert.equal(healthResult.status, 'ok');
const byId = Object.fromEntries(healthResult.capabilities.map((entry) => [entry.id, entry]));
assert.equal(byId.core.state, 'ready');
assert.equal(byId.playwright.state, 'unavailable_security_gate');
assert.equal(byId.crawl4ai.state, 'unavailable_security_gate');
assert.equal(byId['browser-use'].automatic, false);
assert.equal(byId.firecrawl.state, 'disabled');
assert.equal(byId.scrapegraphai.state, 'disabled');
const explain = await runBlackBox(['https://example.com', '--explain', '--json']);
assert.equal(explain.status, 0, explain.stderr);
const explainResult = JSON.parse(explain.stdout);
assert.equal(explainResult.status, 'ok');
assert.equal(explainResult.code, 'route_explained');
assert.equal(explainResult.route.some(({ id }) => id === 'browser-use'), false);
const humanHealth = await runBlackBox(['health']);
assert.equal(humanHealth.status, 0, humanHealth.stderr);
assert.match(humanHealth.stdout, /playwright\tunavailable_security_gate/);
assert.match(humanHealth.stdout, /browser-use\tdisabled/);
const humanExplain = await runBlackBox(['https://example.com', '--explain']);
assert.equal(humanExplain.status, 0, humanExplain.stderr);
assert.match(humanExplain.stdout, /native\teligible\teligible/);
assert.match(humanExplain.stdout, /playwright\tblocked\thostile_egress_proof_missing/);
assert.match(humanExplain.stdout, /firecrawl\tblocked\tfree_cloud_not_allowed/);
const unknownEngine = await runBlackBox([
'https://example.com', '--engine', 'unknown', '--explain', '--json',
]);
assert.equal(unknownEngine.status, 2, unknownEngine.stderr);
assert.equal(JSON.parse(unknownEngine.stdout).status, 'invalid_input');
const forcedDisabled = await runBlackBox([
'https://example.com', '--engine', 'browser-use', '--explain', '--json',
]);
assert.equal(forcedDisabled.status, 0, forcedDisabled.stderr);
const forcedRoute = JSON.parse(forcedDisabled.stdout).route;
assert.equal(forcedRoute.length, 1);
assert.equal(forcedRoute[0].id, 'browser-use');
assert.equal(forcedRoute[0].state, 'disabled');
assert.equal(forcedRoute[0].eligible, false);
const forcedRun = await runBlackBox([
'https://example.com', '--engine', 'browser-use', '--json',
]);
assert.equal(forcedRun.status, 4, forcedRun.stderr);
assert.equal(JSON.parse(forcedRun.stdout).status, 'exhausted');
});
test('black-box commands report exhausted, blocked and invalid input honestly', async () => {
for (const args of [
['https://example.com', '--json'],
['search', 'public records', '--json'],
]) {
const child = await runBlackBox(args);
assert.equal(child.status, 4, `${args[0]}: ${child.stderr}`);
assert.equal(child.stdout.match(/\n/g)?.length, 1);
assert.equal(JSON.parse(child.stdout).status, 'exhausted');
}
const crawl = await runBlackBox(['crawl', 'https://example.com', '--json']);
assert.equal(crawl.status, 5, crawl.stderr);
assert.equal(crawl.stdout.match(/\n/g)?.length, 1);
const crawlResult = JSON.parse(crawl.stdout);
assert.equal(crawlResult.status, 'blocked');
assert.equal(crawlResult.code, 'robots_denied');
const extract = await runBlackBox([
'extract', 'https://example.com', '--schema', 'schema.json', '--json',
]);
assert.equal(extract.status, 2, extract.stderr);
assert.equal(extract.stdout.match(/\n/g)?.length, 1);
const extractResult = JSON.parse(extract.stdout);
assert.equal(extractResult.status, 'invalid_input');
assert.equal(extractResult.code, 'invalid_input');
});
+383
View File
@@ -0,0 +1,383 @@
// RED contract for the shared search budget (CAP-05 CLI authority, CAP-06 shared budget).
//
// Part 1 — CAP-05 tests use only the already-shipped CLI + contract surface
// (compileJobSpec/parseArgv/createResultEnvelope). They pin the default search
// as a zero-network, no-provider job that can only end in honest exhaustion.
//
// Part 2 — CAP-06 tests dynamic-import the future src/search.mjs *inside* each
// test body. Until that model exists they fail with ERR_MODULE_NOT_FOUND, which
// is the intended red state; they green once search.mjs threads one shared
// budget + AbortSignal through every scraped child.
import assert from 'node:assert/strict';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { compileJobSpec, parseArgv } from '../src/cli.mjs';
import { EXIT_CODE, RUN_STATUS, createResultEnvelope, exitCodeForStatus } from '../src/contracts.mjs';
import { createStorage } from '../src/storage.mjs';
const NOW = '2026-08-26T17:00:00.000Z';
const NOW_MS = Date.parse(NOW);
const SEARCH_MODEL = '../src/search.mjs';
function searchJob(argv) {
return compileJobSpec(parseArgv(argv));
}
async function sandbox(t) {
const root = await mkdtemp(join(tmpdir(), 'lynceuz-budget-'));
t.after(async () => rm(root, { recursive: true, force: true }));
return { storage: createStorage({ dataRoot: join(root, '.lynceuz'), clock: () => new Date(NOW) }) };
}
// A shared run budget the runtime carries across an entire search: counters that
// accumulate (never reset per scrape) plus a wall-clock deadline. Optional caps
// are absent by default (unbounded), matching the frozen search-cloud fixtures.
function freshBudget(overrides = {}) {
return {
pagesUsed: 0,
bytesUsed: 0,
attemptsUsed: 0,
creditsUsed: 0,
deadline: NOW_MS + 3_600_000,
...overrides,
};
}
function makeContext({ signal, budget, gateway } = {}) {
return {
gateway: gateway ?? { execute: async () => { throw new Error('gateway must not run in the budget model'); } },
signal: signal ?? new AbortController().signal,
budget: budget ?? freshBudget(),
};
}
function validResults(count) {
return Array.from({ length: count }, (_, index) => ({
url: `https://example.com/r${index}`,
title: `Result ${index}`,
snippet: `Snippet ${index}`,
}));
}
function provider(overrides = {}) {
return {
id: 'fixture-search',
version: '1',
state: 'ready',
reason: 'fixture_ready',
automatic: true,
commands: ['search'],
cost: 'local-zero',
price: 0,
networkModel: 'core-http',
async search() {
return {
requestUrl: 'https://search.example.test/v1?q=q',
evidenceUrl: 'https://search.example.test/evidence',
accessedAt: NOW,
results: validResults(2),
};
},
...overrides,
};
}
function providerWithResults(results, overrides = {}) {
return provider({
async search() {
return {
requestUrl: 'https://search.example.test/v1?q=q',
evidenceUrl: 'https://search.example.test/evidence',
accessedAt: NOW,
results,
};
},
...overrides,
});
}
// Records every runUrlJob invocation: the child job, the run context handed to
// it, and a snapshot of the shared budget as observed at call time.
function scrapeSpy({ onCall } = {}) {
const calls = [];
const contexts = [];
const observed = [];
const runUrlJob = async (childJob, context) => {
calls.push(childJob);
contexts.push(context);
observed.push({
budget: context.budget,
signal: context.signal,
pagesUsed: context.budget.pagesUsed,
bytesUsed: context.budget.bytesUsed,
attemptsUsed: context.budget.attemptsUsed,
creditsUsed: context.budget.creditsUsed,
});
if (onCall) await onCall(childJob, context, calls.length);
return createResultEnvelope({
command: 'url',
status: RUN_STATUS.OK,
code: 'ok',
message: 'scraped',
route: [],
capabilities: [],
warnings: [],
source_hash: `sha256:${'a'.repeat(64)}`,
cache_status: 'off',
});
};
return { runUrlJob, calls, contexts, observed };
}
// --- CAP-05: CLI authority (proved by the shipped CLI + contract surface) ---
test('CAP-05 CLI authority compiles a default search that authorizes no paid or cloud backend', () => {
const job = searchJob(['search', 'public records']);
assert.deepEqual(job.target, { query: 'public records' });
assert.equal(job.goal, 'search-results');
assert.equal(job.policy.moneyBudget, 0);
assert.equal(job.policy.allowFreeCloud, false);
assert.equal(job.policy.network, 'public-only');
assert.equal(job.policy.auth, 'none');
assert.ok(Object.isFrozen(job));
});
test('CAP-05 CLI authority freezes bounded search and scrape-results flags', () => {
const job = searchJob(['search', 'public records', '--limit', '7', '--scrape-results', '2', '--json']);
assert.deepEqual(job.search, { limit: 7, scrapeResults: 2 });
assert.ok(Object.isFrozen(job.search));
for (const argv of [
['search', 'q', '--limit', '0'],
['search', 'q', '--limit', '1.5'],
['search', 'q', '--scrape-results', '0'],
['search', 'q', '--scrape-results', '1.5'],
['search', 'q', '--scrape-results', '101'],
['search', ''],
['search', ' '],
['https://example.com', '--scrape-results', '1'],
['crawl', 'https://example.com', '--limit', '1'],
]) {
assert.throws(() => searchJob(argv), /invalid input/, `expected invalid input for ${JSON.stringify(argv)}`);
}
});
test('CAP-05 CLI authority bounds the search query itself', () => {
assert.throws(() => searchJob(['search', 'x'.repeat(100_001)]), /invalid input/);
});
test('CAP-05 CLI authority pins the honest no-provider exhaustion to a zero-network exit', () => {
const envelope = createResultEnvelope({
command: 'search',
status: RUN_STATUS.EXHAUSTED,
code: 'unavailable_no_free_search_provider',
message: 'no free search provider is configured',
route: [],
capabilities: [],
warnings: [],
});
assert.equal(envelope.status, RUN_STATUS.EXHAUSTED);
assert.equal(envelope.code, 'unavailable_no_free_search_provider');
assert.equal(envelope.manifest_path, undefined);
assert.equal(exitCodeForStatus(envelope.status), EXIT_CODE.EXHAUSTED);
assert.equal(EXIT_CODE.EXHAUSTED, 4);
});
// --- CAP-06: shared budget (proved by the future src/search.mjs model) ---
test('CAP-06 shared budget threads one context, budget and AbortSignal into every scrape without reset', async (t) => {
const { createSearchRegistry, runSearchJob } = await import(SEARCH_MODEL);
const { storage } = await sandbox(t);
const controller = new AbortController();
const budget = freshBudget();
const context = makeContext({ signal: controller.signal, budget });
const spy = scrapeSpy({
onCall: (job, ctx) => {
ctx.budget.pagesUsed += 1;
ctx.budget.bytesUsed += 512;
ctx.budget.attemptsUsed += 1;
},
});
const result = await runSearchJob(
searchJob(['search', 'public records', '--limit', '10', '--scrape-results', '3', '--json']),
{
registry: createSearchRegistry([providerWithResults(validResults(3))]),
storage,
clock: () => new Date(NOW),
runUrlJob: spy.runUrlJob,
sharedRunContext: context,
},
);
assert.equal(spy.calls.length, 3);
// One and the same context object is handed to every child.
assert.equal(spy.contexts[0], spy.contexts[1]);
assert.equal(spy.contexts[1], spy.contexts[2]);
// The shared budget and signal are passed by identity, not copied per child.
assert.equal(spy.observed.every((o) => o.budget === budget), true);
assert.equal(spy.observed.every((o) => o.signal === controller.signal), true);
assert.ok(spy.contexts[0].signal instanceof AbortSignal);
// Counters accumulate across scrapes — never reset to zero per attempt.
assert.deepEqual(spy.observed.map((o) => o.pagesUsed), [0, 1, 2]);
assert.deepEqual(spy.observed.map((o) => o.bytesUsed), [0, 512, 1024]);
assert.deepEqual(spy.observed.map((o) => o.attemptsUsed), [0, 1, 2]);
assert.deepEqual(spy.observed.map((o) => o.creditsUsed), [0, 0, 0]);
assert.equal(budget.pagesUsed, 3);
assert.equal(budget.deadline, freshBudget().deadline);
// Children run under the shared run id but carry their own per-attempt limits.
assert.equal(spy.contexts[0].run.id, spy.contexts[0].runId);
assert.equal(spy.calls.every((job) => job.runId === spy.contexts[0].runId), true);
assert.equal(spy.calls.every((job) => job.limits === result.search_limits), false);
});
test('CAP-06 shared budget stops before starting the next child once the deadline is spent', async (t) => {
const { createSearchRegistry, runSearchJob } = await import(SEARCH_MODEL);
const { storage } = await sandbox(t);
let nowMs = NOW_MS;
const budget = freshBudget({ deadline: NOW_MS + 1_000 });
const context = makeContext({ budget });
// The first scrape consumes the entire deadline; the second must never start.
const spy = scrapeSpy({ onCall: () => { nowMs += 60_000; } });
await runSearchJob(
searchJob(['search', 'q', '--limit', '10', '--scrape-results', '3']),
{
registry: createSearchRegistry([providerWithResults(validResults(3))]),
storage,
clock: () => new Date(nowMs),
runUrlJob: spy.runUrlJob,
sharedRunContext: context,
},
);
assert.equal(spy.calls.length, 1);
});
test('CAP-06 shared budget halts planning the moment the shared AbortSignal fires', async (t) => {
const { createSearchRegistry, runSearchJob } = await import(SEARCH_MODEL);
const { storage } = await sandbox(t);
const controller = new AbortController();
const context = makeContext({ signal: controller.signal });
const spy = scrapeSpy({ onCall: () => controller.abort() });
await runSearchJob(
searchJob(['search', 'q', '--limit', '10', '--scrape-results', '3']),
{
registry: createSearchRegistry([providerWithResults(validResults(3))]),
storage,
clock: () => new Date(NOW),
runUrlJob: spy.runUrlJob,
sharedRunContext: context,
},
);
assert.equal(spy.calls.length, 1);
assert.ok(controller.signal.aborted);
});
test('CAP-06 shared budget starts no child and no provider call when the signal is already aborted', async (t) => {
const { createSearchRegistry, runSearchJob } = await import(SEARCH_MODEL);
const { storage } = await sandbox(t);
const controller = new AbortController();
controller.abort();
let searched = 0;
const eager = provider({
async search() {
searched += 1;
return {
requestUrl: 'https://search.example.test/v1?q=q',
evidenceUrl: 'https://search.example.test/evidence',
accessedAt: NOW,
results: validResults(3),
};
},
});
const spy = scrapeSpy();
await runSearchJob(
searchJob(['search', 'q', '--limit', '10', '--scrape-results', '3']),
{
registry: createSearchRegistry([eager]),
storage,
clock: () => new Date(NOW),
runUrlJob: spy.runUrlJob,
sharedRunContext: makeContext({ signal: controller.signal }),
},
);
assert.equal(spy.calls.length, 0);
assert.equal(searched, 0);
});
test('CAP-06 shared budget refuses paid and ineligible providers despite present credentials or binaries', async (t) => {
const { createSearchRegistry, runSearchJob } = await import(SEARCH_MODEL);
const { storage } = await sandbox(t);
let searched = 0;
const counting = () => async () => {
searched += 1;
return {
requestUrl: 'https://search.example.test/v1?q=q',
evidenceUrl: 'https://search.example.test/evidence',
accessedAt: NOW,
results: validResults(3),
};
};
const paid = provider({ id: 'paid-serp', cost: 'cloud-paid', price: 5, credentials: 'present', search: counting() });
const disabled = provider({ id: 'disabled-cli', state: 'disabled', reason: 'disabled_by_policy', binary: '/opt/bin/foo', search: counting() });
const spy = scrapeSpy();
const result = await runSearchJob(
searchJob(['search', 'q', '--limit', '10', '--scrape-results', '3']),
{
registry: createSearchRegistry([paid, disabled]),
storage,
clock: () => new Date(NOW),
runUrlJob: spy.runUrlJob,
sharedRunContext: makeContext(),
},
);
assert.equal(spy.calls.length, 0);
assert.equal(searched, 0);
assert.equal(result.status, RUN_STATUS.EXHAUSTED);
assert.equal(result.code, 'unavailable_no_free_search_provider');
});
test('CAP-06 shared budget rejects an out-of-bounds provider response before touching a child', async (t) => {
const { createSearchRegistry, runSearchJob } = await import(SEARCH_MODEL);
const { storage } = await sandbox(t);
const base = {
requestUrl: 'https://search.example.test/v1?q=q',
evidenceUrl: 'https://search.example.test/evidence',
accessedAt: NOW,
};
const invalidResponses = [
{ ...base, results: [] }, // empty
{ ...base, results: validResults(101) }, // more than 100
{ ...base, results: [{ url: 'https://example.com', title: 'x', snippet: 'x', extra: true }] }, // unexpected field
{ ...base, results: [{ url: 'https://example.com', title: 'x'.repeat(100_001), snippet: 'x' }] }, // unbounded title
{ ...base, results: [{ url: 'https://example.com', title: 'x', snippet: 'x'.repeat(100_001) }] }, // unbounded snippet
];
for (const response of invalidResponses) {
const spy = scrapeSpy();
const result = await runSearchJob(
searchJob(['search', 'q', '--limit', '10', '--scrape-results', '3']),
{
registry: createSearchRegistry([provider({ search: async () => response })]),
storage,
clock: () => new Date(NOW),
runUrlJob: spy.runUrlJob,
sharedRunContext: makeContext(),
},
);
assert.equal(result.status, RUN_STATUS.INTERNAL_ERROR);
assert.equal(result.code, 'adapter_protocol_error');
assert.equal(spy.calls.length, 0);
}
});
+201
View File
@@ -0,0 +1,201 @@
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { compileJobSpec, parseArgv } from '../src/cli.mjs';
import { RUN_STATUS, createResultEnvelope } from '../src/contracts.mjs';
import { createSearchRegistry, runSearchJob } from '../src/search.mjs';
import { createStorage } from '../src/storage.mjs';
const NOW = '2026-08-26T17:00:00.000Z';
function searchJob(argv = ['search', 'public records']) {
return compileJobSpec(parseArgv(argv));
}
function provider(overrides = {}) {
return {
id: 'fixture-search',
version: '1',
state: 'ready',
reason: 'fixture_ready',
automatic: true,
commands: ['search'],
cost: 'local-zero',
price: 0,
networkModel: 'core-http',
async search() {
return {
requestUrl: 'https://search.example.test/v1?q=public%20records',
evidenceUrl: 'https://search.example.test/evidence/fixture',
accessedAt: NOW,
results: [
{ url: 'https://example.com/a#one', title: 'A', snippet: 'first' },
{ url: 'http://127.0.0.1/private', title: 'private', snippet: 'reject' },
{ url: 'https://example.com/a#two', title: 'duplicate', snippet: 'reject' },
{ url: 'javascript:alert(1)', title: 'invalid', snippet: 'reject' },
{ url: 'https://example.org/b', title: 'B', snippet: 'second' },
],
};
},
...overrides,
};
}
async function sandbox(t) {
const root = await mkdtemp(join(tmpdir(), 'lynceuz-search-'));
t.after(async () => rm(root, { recursive: true, force: true }));
const dataRoot = join(root, '.lynceuz');
return {
dataRoot,
storage: createStorage({ dataRoot, clock: () => new Date(NOW) }),
};
}
async function manifestFor(dataRoot, result) {
return JSON.parse(await readFile(join(dataRoot, result.manifest_path), 'utf8'));
}
test('search and scrape-results flags compile into one immutable bounded JobSpec', () => {
const job = searchJob([
'search', 'public records', '--limit', '7', '--scrape-results', '2', '--json',
]);
assert.deepEqual(job.target, { query: 'public records' });
assert.deepEqual(job.search, { limit: 7, scrapeResults: 2 });
assert.equal(job.policy.moneyBudget, 0);
assert.equal(job.policy.allowFreeCloud, false);
assert.ok(Object.isFrozen(job.search));
for (const argv of [
['search', 'q', '--limit', '0'],
['search', 'q', '--limit', '1.5'],
['search', 'q', '--scrape-results', '0'],
['search', 'q', '--scrape-results', '101'],
['https://example.com', '--scrape-results', '1'],
['crawl', 'https://example.com', '--limit', '1'],
]) {
assert.throws(() => searchJob(argv), /invalid input/);
}
});
test('default search has no provider or SERP fallback and exits with exact honest reason', () => {
const cwd = fileURLToPath(new URL('../', import.meta.url));
const executable = fileURLToPath(new URL('../src/lynceuz.mjs', import.meta.url));
const tripwire = fileURLToPath(new URL('./fixtures/no-network.mjs', import.meta.url));
const child = spawnSync(process.execPath, [
'--import', tripwire, executable, 'search', 'public records', '--json',
], {
cwd,
encoding: 'utf8',
env: { ...process.env, LYNCEUZ_FORBID_NETWORK: '1' },
timeout: 10_000,
});
assert.equal(child.status, 4, child.stderr);
assert.equal(child.signal, null);
const result = JSON.parse(child.stdout);
assert.equal(result.status, RUN_STATUS.EXHAUSTED);
assert.equal(result.code, 'unavailable_no_free_search_provider');
assert.equal(result.manifest_path, undefined);
});
test('search normalizes strict provider evidence and scrapes only permitted unique candidates', async (t) => {
const { dataRoot, storage } = await sandbox(t);
const registry = createSearchRegistry([provider()]);
const calls = [];
const sharedContexts = [];
const runUrlJob = async (childJob, sharedRunContext) => {
calls.push(childJob);
sharedContexts.push(sharedRunContext);
return createResultEnvelope({
command: 'url',
status: calls.length === 1 ? RUN_STATUS.OK : RUN_STATUS.EXHAUSTED,
code: calls.length === 1 ? 'ok' : 'exhausted',
message: 'fixture result',
route: [],
capabilities: [],
warnings: [],
...(calls.length === 1
? { source_hash: `sha256:${'a'.repeat(64)}`, cache_status: 'off' }
: {}),
});
};
const result = await runSearchJob(searchJob([
'search', 'public records', '--limit', '5', '--scrape-results', '2', '--json',
]), {
registry,
storage,
clock: () => new Date(NOW),
runUrlJob,
sharedRunContext: {
gateway: { execute: async () => { throw new Error('not used by fixture'); } },
signal: new AbortController().signal,
budget: { pagesUsed: 0, bytesUsed: 0, attemptsUsed: 0 },
},
});
assert.equal(result.status, RUN_STATUS.PARTIAL);
assert.equal(result.code, 'partial');
assert.equal(calls.length, 2);
assert.deepEqual(calls.map((job) => job.target.url), [
'https://example.com/a',
'https://example.org/b',
]);
assert.equal(sharedContexts[0], sharedContexts[1]);
assert.equal(sharedContexts[0].run.id, sharedContexts[0].runId);
assert.equal(calls.every((job) => job.runId === sharedContexts[0].runId), true);
assert.equal(calls.every((job) => job.limits === result.search_limits), false);
assert.deepEqual(result.warnings, [
'search_candidate_private_or_invalid:2',
'search_candidate_duplicate:1',
]);
const manifest = await manifestFor(dataRoot, result);
assert.equal(manifest.provider.id, 'fixture-search');
assert.equal(manifest.provider.version, '1');
assert.equal(manifest.provider.request_url, 'https://search.example.test/v1?q=public%20records');
assert.equal(manifest.provider.evidence_url, 'https://search.example.test/evidence/fixture');
assert.equal(manifest.provider.accessed_at, NOW);
assert.equal(manifest.cost_money, 0);
assert.equal(manifest.search.results.length, 2);
assert.equal(manifest.search.results.every((entry) => (
entry.snippet_kind === 'discovery_metadata'
)), true);
assert.equal(manifest.evidence.some((entry) => entry.status === 'destination_source_captured'
&& entry.url === 'https://example.com/a'), true);
assert.equal(manifest.evidence.some((entry) => entry.snippet), false);
assert.deepEqual(manifest.search.scraped.map(({ status }) => status), ['ok', 'exhausted']);
});
test('search provider response schema is strict and bounded before normalization', async (t) => {
const { storage } = await sandbox(t);
const invalidProviders = [
provider({ search: async () => ({ results: [] }) }),
provider({ search: async () => ({
requestUrl: 'https://search.example.test/',
evidenceUrl: 'https://search.example.test/evidence',
accessedAt: NOW,
results: [{ url: 'https://example.com', title: 'x', snippet: 'x', extra: true }],
}) }),
provider({ search: async () => ({
requestUrl: 'https://search.example.test/',
evidenceUrl: 'https://search.example.test/evidence',
accessedAt: NOW,
results: Array.from({ length: 101 }, (_, index) => ({
url: `https://example.com/${index}`, title: 'x', snippet: 'x',
})),
}) }),
];
for (const invalidProvider of invalidProviders) {
const result = await runSearchJob(searchJob(), {
registry: createSearchRegistry([invalidProvider]),
storage,
clock: () => new Date(NOW),
});
assert.equal(result.status, RUN_STATUS.INTERNAL_ERROR);
assert.equal(result.code, 'adapter_protocol_error');
}
});
+525
View File
@@ -0,0 +1,525 @@
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import {
lstat,
mkdir,
mkdtemp,
readFile,
readdir,
rm,
stat,
symlink,
writeFile,
} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, relative, resolve } from 'node:path';
import test from 'node:test';
import { createRequestFingerprint, createStorage } from '../src/storage.mjs';
const FIXED_TIME = '2026-08-26T12:15:40.123Z';
const clock = () => new Date(FIXED_TIME);
function sha256(bytes) {
return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
}
function hashHex(hash) {
assert.match(hash, /^sha256:[0-9a-f]{64}$/);
return hash.slice('sha256:'.length);
}
function makeJob(overrides = {}) {
return {
schema_version: 1,
command: 'url',
requested_url: 'https://example.com/',
method: 'GET',
format: 'markdown',
cache: 'use',
...overrides,
};
}
function makeFingerprint(overrides = {}) {
return createRequestFingerprint({
canonicalUrl: 'https://example.com/',
method: 'GET',
headers: {
accept: 'text/html,application/xhtml+xml',
'accept-encoding': 'gzip, br',
},
adapter: { id: 'native', version: '1' },
policyVersion: '1',
format: 'markdown',
goal: 'markdown',
decode: { encodings: ['gzip', 'br'], maxBytes: 1_048_576 },
...overrides,
});
}
function makeManifest(run, source, overrides = {}) {
return {
schema_version: 1,
run_id: run.id,
status: 'ok',
requested_url: 'https://example.com/',
effective_url: 'https://example.com/',
alternatives: [],
fetched_at: FIXED_TIME,
served_at: FIXED_TIME,
revalidated_at: null,
engine: { id: 'native', version: '1' },
requested_format: 'markdown',
format: 'raw',
policy: {
version: '1',
network: 'public-only',
auth: 'none',
money_budget: 0,
},
attempts: [],
source_hash: source.hash,
artifact_hash: source.hash,
artifact_path: source.path,
artifacts: [source],
evidence: [{
url: 'https://example.com/',
hash: source.hash,
status: 'source_captured',
}],
warnings: [],
cost_money: 0,
credits_used: 0,
...overrides,
};
}
function makeCacheRecord(run, manifest, source) {
return {
schema_version: 1,
request_fingerprint: makeFingerprint(),
canonical_url: 'https://example.com/',
requested_format: 'markdown',
format: 'raw',
run_id: run.id,
manifest_path: manifest.path,
manifest_hash: manifest.hash,
source_hash: source.hash,
source_path: source.path,
artifact_hash: source.hash,
artifact_path: source.path,
fetched_at: FIXED_TIME,
expires_at: '2026-08-26T13:15:40.123Z',
};
}
async function withSandbox(fn, options = {}) {
const sandbox = await mkdtemp(join(tmpdir(), 'lynceuz-storage-'));
const dataRoot = join(sandbox, '.lynceuz');
const storage = createStorage({ dataRoot, clock, ...options });
try {
await fn({ sandbox, dataRoot, storage });
} finally {
await rm(sandbox, { recursive: true, force: true });
}
}
async function walk(root) {
const entries = [];
async function visit(path) {
const info = await lstat(path);
entries.push({ path, info });
if (!info.isDirectory()) return;
for (const name of await readdir(path)) await visit(join(path, name));
}
await visit(root);
return entries;
}
async function assertCacheMiss(storage, fingerprint) {
const result = await storage.readCache(fingerprint);
assert.equal(result.hit, false);
assert.equal(result.record, undefined);
assert.ok(Array.isArray(result.warnings));
return result;
}
async function assertRejected(call, pattern) {
await assert.rejects(async () => call(), pattern);
}
test('request fingerprint is canonical, secret-free and sensitive to acquisition semantics', () => {
const first = makeFingerprint({ canonicalUrl: 'https://example.com/#first' });
const reordered = createRequestFingerprint({
goal: 'markdown',
decode: { maxBytes: 1_048_576, encodings: ['gzip', 'br'] },
format: 'markdown',
policyVersion: '1',
adapter: { version: '1', id: 'native' },
headers: {
'accept-encoding': 'gzip, br',
accept: 'text/html,application/xhtml+xml',
},
method: 'get',
canonicalUrl: 'https://example.com/#second',
});
assert.match(first, /^[0-9a-f]{64}$/);
assert.equal(reordered, first, 'key order, method case and fragments cannot split the cache');
assert.notEqual(makeFingerprint({ format: 'raw', goal: 'raw' }), first);
assert.notEqual(makeFingerprint({ policyVersion: '2' }), first);
assert.notEqual(makeFingerprint({ adapter: { id: 'native', version: '2' } }), first);
assert.notEqual(
makeFingerprint({ decode: { encodings: ['gzip', 'br'], maxBytes: 2_048_576 } }),
first,
);
for (const headers of [
{ authorization: 'Bearer secret' },
{ cookie: 'session=secret' },
{ 'proxy-authorization': 'Basic secret' },
]) {
assert.throws(
() => makeFingerprint({ headers }),
/authorization|cookie|secret|unsafe header/i,
);
}
});
test('data root is a private .lynceuz tree and never edits the caller gitignore', async () => {
const sandbox = await mkdtemp(join(tmpdir(), 'lynceuz-root-'));
try {
assert.throws(
() => createStorage({ dataRoot: join(sandbox, 'state'), clock }),
/\.lynceuz/i,
);
assert.throws(
() => createStorage({ dataRoot: join(sandbox, '.lynceuz', 'nested'), clock }),
/\.lynceuz/i,
);
} finally {
await rm(sandbox, { recursive: true, force: true });
}
await withSandbox(async ({ sandbox: callerRoot, dataRoot, storage }) => {
const run = await storage.beginRun(makeJob());
const source = await storage.putObject(run, Buffer.from('private evidence'), {
role: 'raw',
media_type: 'text/plain',
derived_from: null,
});
await storage.appendAttempt(run, {
type: 'attempt_finished',
at: FIXED_TIME,
outcome: 'ok',
source_hash: source.hash,
});
const manifest = await storage.commitManifest(run, makeManifest(run, source));
const fingerprint = makeFingerprint();
await storage.commitCache(fingerprint, makeCacheRecord(run, manifest, source));
await storage.publishPrivateJson('security/proof.json', { status: 'passed' });
await storage.publishOutput('exports/result.txt', Buffer.from('result'));
assert.equal(await readFile(join(dataRoot, '.gitignore'), 'utf8'), '*\n!.gitignore\n');
await assert.rejects(lstat(join(callerRoot, '.gitignore')), { code: 'ENOENT' });
const gitignores = (await walk(dataRoot))
.filter(({ path }) => path.endsWith('/.gitignore'))
.map(({ path }) => relative(dataRoot, path));
assert.deepEqual(gitignores, ['.gitignore']);
for (const { path, info } of await walk(dataRoot)) {
if (info.isSymbolicLink()) continue;
const mode = info.mode & 0o777;
if (info.isDirectory()) assert.equal(mode, 0o700, path);
if (info.isFile()) assert.equal(mode, 0o600, path);
}
});
});
test('objects are content-addressed, deduplicated without rewriting and reverified before reuse', async () => {
await withSandbox(async ({ dataRoot, storage }) => {
const run = await storage.beginRun(makeJob());
const rawBytes = Buffer.from('<h1>source</h1>');
const derivedBytes = Buffer.from('# source\n');
const raw = await storage.putObject(run, rawBytes, {
role: 'raw',
media_type: 'text/html',
derived_from: null,
});
const derived = await storage.putObject(run, derivedBytes, {
role: 'markdown',
media_type: 'text/markdown',
derived_from: raw.hash,
transform: { id: 'native-html-markdown', version: '1', options_hash: sha256('{}') },
});
assert.equal(raw.hash, sha256(rawBytes));
assert.equal(derived.hash, sha256(derivedBytes));
assert.notEqual(raw.hash, derived.hash);
assert.equal(raw.bytes, rawBytes.length);
assert.equal(derived.derived_from, raw.hash);
const rawHex = hashHex(raw.hash);
const derivedHex = hashHex(derived.hash);
assert.equal(raw.path, `objects/sha256/${rawHex.slice(0, 2)}/${rawHex}`);
assert.equal(derived.path, `objects/sha256/${derivedHex.slice(0, 2)}/${derivedHex}`);
assert.deepEqual(await readFile(join(dataRoot, raw.path)), rawBytes);
assert.deepEqual(await readFile(join(dataRoot, derived.path)), derivedBytes);
await assertRejected(
() => storage.readObject(raw, { maxBytes: rawBytes.length - 1 }),
/large|limit|bytes|integrity/i,
);
assert.deepEqual(await storage.readObject(raw, { maxBytes: rawBytes.length }), rawBytes);
const before = await stat(join(dataRoot, raw.path), { bigint: true });
const duplicate = await storage.putObject(run, rawBytes, {
role: 'raw',
media_type: 'text/html',
derived_from: null,
});
const after = await stat(join(dataRoot, raw.path), { bigint: true });
assert.equal(duplicate.hash, raw.hash);
assert.equal(duplicate.path, raw.path);
assert.equal(after.ino, before.ino);
assert.equal(after.mtimeNs, before.mtimeNs, 'dedupe must not rewrite an immutable object');
await writeFile(join(dataRoot, raw.path), Buffer.from('tampered'), { mode: 0o600 });
await assertRejected(
() => storage.putObject(run, rawBytes, {
role: 'raw',
media_type: 'text/html',
derived_from: null,
}),
/hash|integrity|corrupt|mismatch/i,
);
assert.deepEqual(await readFile(join(dataRoot, raw.path)), Buffer.from('tampered'));
});
});
test('cache becomes visible only after a hash-bound committed manifest', async () => {
const events = [];
await withSandbox(async ({ dataRoot, storage }) => {
const fingerprint = makeFingerprint();
const run = await storage.beginRun(makeJob());
assert.match(run.id, /^[A-Za-z0-9._-]+$/);
assert.equal(run.path, `runs/${run.id}`);
const source = await storage.putObject(run, Buffer.from('verified source'), {
role: 'raw',
media_type: 'text/plain',
derived_from: null,
});
const alternate = await storage.putObject(run, Buffer.from('other valid artifact'), {
role: 'raw',
media_type: 'text/plain',
derived_from: null,
});
await storage.appendAttempt(run, {
type: 'attempt_finished',
at: FIXED_TIME,
outcome: 'ok',
source_hash: source.hash,
});
await assertCacheMiss(storage, fingerprint);
const manifest = await storage.commitManifest(run, makeManifest(run, source, {
artifacts: [source, alternate],
}));
assert.equal(manifest.path, `runs/${run.id}/manifest.json`);
assert.equal(manifest.hash, sha256(await readFile(join(dataRoot, manifest.path))));
await assertCacheMiss(storage, fingerprint);
const record = makeCacheRecord(run, manifest, source);
await storage.commitCache(fingerprint, record);
const cached = await storage.readCache(fingerprint);
assert.equal(cached.hit, true);
assert.deepEqual(cached.record, record);
assert.deepEqual(cached.warnings, []);
const indexPath = join(
dataRoot,
'cache',
'requests',
fingerprint.slice(0, 2),
`${fingerprint}.json`,
);
assert.deepEqual(JSON.parse(await readFile(indexPath, 'utf8')), record);
assert.equal(record.manifest_hash, sha256(await readFile(join(dataRoot, record.manifest_path))));
assert.equal(record.source_hash, sha256(await readFile(join(dataRoot, source.path))));
await assertRejected(
() => storage.commitCache(fingerprint, {
...record,
artifact_hash: alternate.hash,
artifact_path: alternate.path,
}),
/artifact|binding|manifest|integrity|mismatch/i,
);
assert.deepEqual((await storage.readCache(fingerprint)).record, record);
const invalidFingerprint = makeFingerprint({ format: 'raw', goal: 'raw' });
await assertRejected(
() => storage.commitCache(invalidFingerprint, record),
/fingerprint|request|cache/i,
);
await assertCacheMiss(storage, invalidFingerprint);
await assertRejected(
() => storage.commitCache(invalidFingerprint, {
...record,
request_fingerprint: invalidFingerprint,
manifest_hash: `sha256:${'0'.repeat(64)}`,
}),
/manifest|hash|integrity|mismatch/i,
);
await assertCacheMiss(storage, invalidFingerprint);
}, {
faultInjector(label, context) {
events.push({ label, context });
},
});
const labels = events.map(({ label }) => label);
assert.ok(labels.includes('object_rename'));
assert.ok(labels.includes('journal_flush'));
assert.ok(labels.includes('manifest_rename'));
assert.ok(labels.includes('cache_index_rename'));
assert.ok(
labels.lastIndexOf('manifest_rename') < labels.lastIndexOf('cache_index_rename'),
'cache index must be renamed only after the manifest is durable',
);
});
test('missing, malformed and hash-mismatched cache records are safe misses', async () => {
await withSandbox(async ({ dataRoot, storage }) => {
const fingerprint = makeFingerprint();
await assertCacheMiss(storage, fingerprint);
const run = await storage.beginRun(makeJob());
const source = await storage.putObject(run, Buffer.from('cache source'), {
role: 'raw',
media_type: 'text/plain',
derived_from: null,
});
await storage.appendAttempt(run, {
type: 'attempt_finished',
at: FIXED_TIME,
outcome: 'ok',
source_hash: source.hash,
});
const manifest = await storage.commitManifest(run, makeManifest(run, source));
await storage.commitCache(fingerprint, makeCacheRecord(run, manifest, source));
const indexPath = join(
dataRoot,
'cache',
'requests',
fingerprint.slice(0, 2),
`${fingerprint}.json`,
);
await writeFile(indexPath, '{truncated', { mode: 0o600 });
const malformed = await assertCacheMiss(storage, fingerprint);
assert.ok(malformed.warnings.length > 0);
await writeFile(indexPath, JSON.stringify({
...makeCacheRecord(run, manifest, source),
source_hash: `sha256:${'f'.repeat(64)}`,
}), { mode: 0o600 });
const mismatched = await assertCacheMiss(storage, fingerprint);
assert.ok(mismatched.warnings.length > 0);
});
});
test('every durability fault leaves no false cache hit before a valid index', async (t) => {
for (const failureLabel of [
'temp_flush',
'object_rename',
'journal_flush',
'manifest_rename',
'cache_index_rename',
]) {
await t.test(failureLabel, async () => {
const seen = [];
const injected = new Error(`injected:${failureLabel}`);
await withSandbox(async ({ dataRoot, storage }) => {
const fingerprint = makeFingerprint();
let failure;
try {
const run = await storage.beginRun(makeJob());
const source = await storage.putObject(run, Buffer.from('fault source'), {
role: 'raw',
media_type: 'text/plain',
derived_from: null,
});
await storage.appendAttempt(run, {
type: 'attempt_finished',
at: FIXED_TIME,
outcome: 'ok',
source_hash: source.hash,
});
const manifest = await storage.commitManifest(run, makeManifest(run, source));
await storage.commitCache(fingerprint, makeCacheRecord(run, manifest, source));
} catch (error) {
failure = error;
}
assert.equal(failure, injected, `fault ${failureLabel} must escape its publication step`);
assert.ok(seen.includes(failureLabel), `fault hook ${failureLabel} was not reached`);
const reopened = createStorage({ dataRoot, clock });
await assertCacheMiss(reopened, fingerprint);
}, {
faultInjector(label) {
seen.push(label);
if (label === failureLabel) throw injected;
},
});
});
}
});
test('private and user output paths reject traversal, absolute paths and symlink components', async () => {
await withSandbox(async ({ sandbox, dataRoot, storage }) => {
const output = await storage.publishOutput('exports/result.md', Buffer.from('# result\n'));
assert.equal(output.path, 'exports/result.md');
assert.equal(await storage.resolve(output.path), join(dataRoot, output.path));
assert.equal(await readFile(join(dataRoot, output.path), 'utf8'), '# result\n');
const absoluteEscape = join(sandbox, 'absolute-escape.txt');
for (const unsafePath of [
'../escape.txt',
'exports/../../escape.txt',
absoluteEscape,
]) {
await assertRejected(
() => storage.publishOutput(unsafePath, Buffer.from('escape')),
/absolute|contain|escape|path|traversal/i,
);
await assertRejected(
() => storage.publishPrivateJson(unsafePath, { escape: true }),
/absolute|contain|escape|path|traversal/i,
);
await assertRejected(
() => storage.resolve(unsafePath),
/absolute|contain|escape|path|traversal/i,
);
}
const outside = join(sandbox, 'outside');
await mkdir(outside, { recursive: true, mode: 0o700 });
await mkdir(join(dataRoot, 'exports'), { recursive: true, mode: 0o700 });
await symlink(outside, join(dataRoot, 'exports', 'linked'));
await assertRejected(
() => storage.publishOutput('exports/linked/pwned.txt', Buffer.from('escape')),
/symlink|contain|escape|path/i,
);
await assertRejected(
() => storage.resolve('exports/linked/pwned.txt'),
/symlink|contain|escape|path/i,
);
assert.deepEqual(await readdir(outside), []);
await assert.rejects(lstat(resolve(dataRoot, '..', 'escape.txt')), { code: 'ENOENT' });
await assert.rejects(lstat(absoluteEscape), { code: 'ENOENT' });
});
});