release: Lynceuz v0.1 — public web evidence at zero cost, or an honest stop
This commit is contained in:
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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())
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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]/"
|
||||
]
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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();
|
||||
@@ -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 };
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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()));
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user