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
+366
View File
@@ -0,0 +1,366 @@
#!/usr/bin/env node
// Owner-run generator for `.lynceuz/security/macos-containment-receipt-v1.json`.
//
// The probe (`probe-macos-browser-containment.mjs`) only READS that receipt; nothing wrote it.
// PF facts (`pfctl -s info/-sr`) need root and the canary client must run under the contained uid,
// so this must be launched by the owner with root. It never mutates the system: it only READS PF
// facts and drives a canary stand on local addresses.
//
// Default mode (root parent):
// sudo node scripts/emit-macos-containment-receipt.mjs
// It stands up `createContainmentCanaryHarness` (proxy pinned to the guard port so a contained uid
// can reach it), stages a self-contained canary client under /private/tmp and runs it as `_lynceuz`
// to probe the four channels from inside containment,
// reads PF/uid/boot facts, then writes a `ready` receipt ONLY when the canary proves proxy TCP
// answers while direct TCP, UDP and QUIC stay silent. Any missing/unreadable fact -> non-zero exit
// with a typed reason and NOTHING is written (fail-closed).
//
// `reboot_verified: true` means the PF anchor is active AND `boot_session` (kern.boottime) is the
// live one — it confirms containment is active in the CURRENT boot, not that a reboot cycle was
// survived. The receipt goes stale with the boot session, which is the point.
//
// The canary client is emitted by `renderCanaryClientSource()` as a fully self-contained ESM module
// (only `node:` builtins, no repo imports, no home-dir paths). The parent stages it in a temp dir
// under /private/tmp — reachable by the contained uid, which cannot traverse the owner's home — runs
// it as `_lynceuz` with the endpoints as argv, then deletes the temp dir in any outcome.
import { execFile } from 'node:child_process';
import { createHash } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { chmod, chown, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import { inspectMacosContainment, verifyMacosContainmentReceipt } from '../src/macos-containment.mjs';
import {
createContainmentCanaryHarness,
evaluateCanaryObservations,
} from '../evals/fixtures/pf-containment-canary.mjs';
const execFileAsync = promisify(execFile);
const SELF = fileURLToPath(import.meta.url);
const PROJECT_ROOT = resolve(dirname(SELF), '..');
const SECURITY_DIR = resolve(PROJECT_ROOT, '.lynceuz/security');
const RECEIPT_PATH = resolve(SECURITY_DIR, 'macos-containment-receipt-v1.json');
const CHANNELS = Object.freeze(['proxy_tcp', 'direct_tcp', 'udp', 'quic']);
const CLIENT_TIMEOUT_MS = 20_000;
const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
const ZERO_HASH = `sha256:${'0'.repeat(64)}`;
const BASE_EXPECTED = 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',
});
function emit(status, reason, extra = {}) {
process.stdout.write(`${JSON.stringify({
kind: 'lynceuz_macos_containment_receipt',
schema_version: 1,
status,
reason,
generated_at: new Date().toISOString(),
...extra,
})}\n`);
}
function impossible(reason, extra = {}) {
emit('impossible', reason, extra);
return 1;
}
async function fileHash(relativePath) {
const bytes = await readFile(resolve(PROJECT_ROOT, relativePath));
if (bytes.length > MAX_SOURCE_BYTES) throw new Error('source_file_too_large');
return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
}
async function buildProvisionalExpected() {
const [macosContainment, canary, wave2] = await Promise.all([
fileHash('src/macos-containment.mjs'),
fileHash('evals/fixtures/pf-containment-canary.mjs'),
fileHash('evals/fixtures/wave2-suite-manifest.json'),
]);
return {
...BASE_EXPECTED,
anchor_sha256: ZERO_HASH,
rules_sha256: ZERO_HASH,
source_hashes: { macos_containment: macosContainment, canary },
suite_hashes: { wave2 },
};
}
// A fully self-contained ESM canary client: only `node:` builtins, no repo imports, no home-dir
// paths. The parent stages this string in a temp dir the contained uid can reach (it cannot traverse
// the owner's home). The client reads endpoints from argv, runs the four exchanges, and prints
// observations as JSON. Confirmation is by RESPONSE, never by a successful send — PF `block drop`
// gives no RST, so only a confirmed reply proves a leak.
export function renderCanaryClientSource() {
return `import { connect } from 'node:net';
import { createSocket } from 'node:dgram';
const MAX_MESSAGE_BYTES = 256;
const TIMEOUT_MS = 2000;
const CHANNELS = ['proxy_tcp', 'direct_tcp', 'udp', 'quic'];
const PROTOCOLS = {
proxy_tcp: { request: 'LYNCEUZ_PROXY_TCP?', response: 'LYNCEUZ_PROXY_TCP_OK' },
direct_tcp: { request: 'LYNCEUZ_DIRECT_TCP?', response: 'LYNCEUZ_DIRECT_TCP_LEAK' },
udp: { request: 'LYNCEUZ_UDP?', response: 'LYNCEUZ_UDP_LEAK' },
quic: { request: 'LYNCEUZ_QUIC_INITIAL?', response: 'LYNCEUZ_QUIC_RETRY_LEAK' },
};
function observation(channel, operationSucceeded, response) {
return {
channel,
operation_succeeded: operationSucceeded,
response,
response_confirmed: response === PROTOCOLS[channel].response,
};
}
function exchangeTcp(channel, endpoint) {
const protocol = 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(), TIMEOUT_MS);
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());
});
}
function exchangeUdp(channel, endpoint) {
const protocol = 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(), TIMEOUT_MS);
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();
});
});
}
function validEndpoint(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value)
&& typeof value.host === 'string' && value.host.length > 0
&& Number.isInteger(value.port) && value.port > 0 && value.port <= 65535;
}
async function main() {
let endpoints;
try {
endpoints = JSON.parse(process.argv[2] ?? '');
} catch {
process.stdout.write(JSON.stringify({ error: 'invalid_input' }) + '\\n');
return 2;
}
if (!endpoints || CHANNELS.some((channel) => !validEndpoint(endpoints[channel]))) {
process.stdout.write(JSON.stringify({ error: 'invalid_input' }) + '\\n');
return 2;
}
const [proxyTcp, directTcp, udp, quic] = await Promise.all([
exchangeTcp('proxy_tcp', endpoints.proxy_tcp),
exchangeTcp('direct_tcp', endpoints.direct_tcp),
exchangeUdp('udp', endpoints.udp),
exchangeUdp('quic', endpoints.quic),
]);
process.stdout.write(JSON.stringify({
proxy_tcp: proxyTcp, direct_tcp: directTcp, udp, quic,
}) + '\\n');
return 0;
}
process.exitCode = await main();
`;
}
// Trim a client's stderr for the failure receipt: keep printable bytes only, cap length. Endpoints
// are the only data the client ever sees and they are not secret, so this leaks nothing sensitive.
function excerptStderr(value) {
if (typeof value !== 'string' || value.trim().length === 0) return null;
const printable = Array.from(value, (ch) => {
const code = ch.codePointAt(0);
return code >= 0x20 && code !== 0x7f ? ch : ' ';
}).join('');
return printable.trim().slice(0, 400);
}
// Stage the self-contained client outside the owner's home (the contained uid cannot traverse it),
// run it as that uid, and collect its observations. Async spawn is required: a blocking spawn would
// freeze this event loop and starve the canary responders. The temp dir is removed in any outcome.
async function probeFromContainment(uidName, endpoints) {
const dir = await mkdtemp('/private/tmp/lynceuz-canary-');
try {
await chmod(dir, 0o755);
const clientPath = resolve(dir, 'canary-client.mjs');
await writeFile(clientPath, renderCanaryClientSource(), { mode: 0o644 });
await chmod(clientPath, 0o644);
let stdout;
try {
({ stdout } = await execFileAsync(
'/usr/bin/sudo',
['-n', '-u', uidName, process.execPath, clientPath, JSON.stringify(endpoints)],
{ shell: false, timeout: CLIENT_TIMEOUT_MS, maxBuffer: 256 * 1024, encoding: 'utf8' },
));
} catch (error) {
throw Object.assign(new Error('containment_canary_client_failed'), {
details: { stderr: excerptStderr(error?.stderr) },
});
}
const line = stdout.trim().split('\n').filter(Boolean).at(-1);
let observations;
try {
observations = JSON.parse(line ?? '');
} catch {
throw new Error('containment_canary_client_unreadable');
}
if (!observations || CHANNELS.some((channel) => typeof observations[channel] !== 'object')) {
throw new Error('containment_canary_client_unreadable');
}
return observations;
} finally {
await rm(dir, { recursive: true, force: true }).catch(() => {});
}
}
async function writeReceipt(receipt) {
await mkdir(SECURITY_DIR, { recursive: true });
await writeFile(RECEIPT_PATH, `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 });
await chmod(RECEIPT_PATH, 0o600);
// Root wrote it; hand ownership back so the owner's verify can read it (dir traversal + file read).
const uid = Number(process.env.SUDO_UID);
const gid = Number(process.env.SUDO_GID);
if (Number.isInteger(uid) && Number.isInteger(gid)) {
for (const target of [SECURITY_DIR, RECEIPT_PATH]) {
await chown(target, uid, gid).catch(() => {});
}
}
}
async function runParentMode() {
if (typeof process.geteuid !== 'function' || process.geteuid() !== 0) {
return impossible('containment_requires_root');
}
const provisional = await buildProvisionalExpected();
const system = await inspectMacosContainment({ expected: provisional });
if (system.state === 'unavailable_security_gate') {
return impossible(system.reason, system.details ? { details: system.details } : {});
}
const expected = {
...provisional,
anchor_sha256: system.pf.anchor_sha256,
rules_sha256: system.pf.rules_sha256,
};
let harness;
let canary;
try {
harness = await createContainmentCanaryHarness({ proxyPort: expected.guard_proxy_port });
} catch {
return impossible('containment_canary_harness_unavailable');
}
try {
canary = evaluateCanaryObservations(await probeFromContainment(expected.uid_name, harness.endpoints));
} catch (error) {
return impossible(error.message, error.details ? { details: error.details } : {});
} finally {
await harness.close().catch(() => {});
}
const now = new Date();
const nowIso = now.toISOString();
const receipt = {
kind: 'lynceuz_macos_containment_receipt',
schema_version: 1,
status: 'ready',
backend: expected.backend,
generated_at: nowIso,
uid: { name: system.uid.name, uid: system.uid.uid, gid: system.uid.gid },
guard_proxy: { host: expected.guard_proxy_host, port: expected.guard_proxy_port },
pf: {
anchor_name: system.pf.anchor_name,
anchor_path: system.pf.anchor_path,
anchor_sha256: system.pf.anchor_sha256,
rules_sha256: system.pf.rules_sha256,
},
source_hashes: expected.source_hashes,
suite_hashes: expected.suite_hashes,
boot_session: system.boot_session,
reboot_verified: system.pf.active === true,
reboot_verified_at: nowIso,
canary,
};
// Never emit a receipt we cannot honestly stand behind: run it through the real verifier first.
const verdict = await verifyMacosContainmentReceipt({
receipt, expected, system, canary, now: () => now.getTime(),
});
if (verdict.state !== 'ready') return impossible(verdict.reason, verdict.details ? { details: verdict.details } : {});
try {
await writeReceipt(receipt);
} catch {
return impossible('containment_receipt_write_failed');
}
emit('ready', 'containment_ready', { receipt_path: RECEIPT_PATH });
return 0;
}
async function main() {
if (process.argv.slice(2).length !== 0) return impossible('invalid_input');
return runParentMode();
}
// Only auto-run when invoked directly; importing this module (e.g. from the eval suite) must be
// side-effect free so `renderCanaryClientSource` can be exercised without a root parent run.
function invokedDirectly() {
try {
return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(SELF);
} catch {
return false;
}
}
if (invokedDirectly()) {
process.exitCode = await main();
}
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env node
// Lynceuz onboarding probe — stdlib only, zero dependencies.
//
// Prints a verifiable readiness snapshot and exits non-zero when a mandatory
// check is red. Modes:
// (no flag) human-readable report
// --json machine snapshot, kind: "lynceuz_onboarding"
// --selftest run this script's own assertions, exit 0 when sound
//
// Every path is resolved from this file, so a fresh clone works in any directory.
import { spawnSync } from 'node:child_process';
import { readdirSync, readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = dirname(SCRIPT_DIR);
const MIN_NODE_MAJOR = 20;
function majorOf(version) {
const match = /^v?(\d+)\./.exec(String(version));
return match ? Number(match[1]) : NaN;
}
function countRuntimeDependencies(pkg) {
return Object.keys(pkg?.dependencies ?? {}).length;
}
function listSourceModules() {
return readdirSync(join(REPO_ROOT, 'src'))
.filter((name) => name.endsWith('.mjs'))
.sort();
}
// node --check every source module. A parse failure means a broken or
// incompatible clone, which is a mandatory red.
function checkSources(files) {
return files.map((file) => {
const run = spawnSync(process.execPath, ['--check', join(REPO_ROOT, 'src', file)], {
encoding: 'utf8',
timeout: 20_000,
});
if (run.status === 0) return { file, ok: true };
const firstLine = (run.stderr || '').split('\n').find((line) => line.trim() !== '');
return { file, ok: false, error: firstLine ?? 'node --check failed' };
});
}
async function capabilitySnapshot() {
const routerUrl = pathToFileURL(join(REPO_ROOT, 'src', 'router.mjs')).href;
const { createDefaultRegistry } = await import(routerUrl);
return createDefaultRegistry(process.version).map((cap) => {
// Mirror src/lynceuz.mjs: the shipped CLI promotes native to a ready HTTP path.
const native = cap.id === 'native';
return {
id: cap.id,
state: native ? 'ready' : cap.state,
reason: native ? 'native_http_ready' : cap.reason,
automatic: cap.automatic,
commands: cap.commands ?? [],
};
});
}
function browserPathRequirements(platform) {
const supported = platform === 'darwin';
return {
supported_platform: supported,
gated_engines: ['playwright', 'crawl4ai'],
requirements: [
'macOS host — containment is only built for darwin',
'owner runs ops/macos/install-containment.sh --apply from a root shell',
'system PF anchor, launchd job and sudoers drop-in installed by that script',
'hostile egress proof stays green: evals/browser-hostile.test.mjs',
],
note: supported
? 'Browser path is closed until the owner installs containment and the hostile proof passes.'
: 'No supported browser containment on this platform. Use the native HTTP path instead.',
};
}
// The three checks that decide readiness. Pure, so --selftest can exercise it.
function mandatoryChecks({ nodeMajor, runtimeDeps, sourcesParse }) {
return {
node_supported: Number.isFinite(nodeMajor) && nodeMajor >= MIN_NODE_MAJOR,
zero_runtime_dependencies: runtimeDeps === 0,
sources_parse: sourcesParse,
};
}
function isReady(checks) {
return Object.values(checks).every(Boolean);
}
async function buildReport() {
const pkg = JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8'));
const sources = checkSources(listSourceModules());
const runtimeDeps = countRuntimeDependencies(pkg);
const nodeMajor = majorOf(process.version);
const sourcesParse = sources.every((entry) => entry.ok);
const checks = mandatoryChecks({ nodeMajor, runtimeDeps, sourcesParse });
return {
kind: 'lynceuz_onboarding',
ready: isReady(checks),
node_version: process.version,
node_required: `>=${MIN_NODE_MAJOR}`,
platform: `${process.platform}/${process.arch}`,
runtime_dependencies: runtimeDeps,
source_check: {
command: 'node --check src/*.mjs',
total: sources.length,
failed: sources.filter((entry) => !entry.ok),
},
capabilities: await capabilitySnapshot(),
browser_path: browserPathRequirements(process.platform),
mandatory_checks: checks,
};
}
function renderHuman(report) {
const mark = (ok) => (ok ? 'ok' : 'RED');
const lines = [
'Lynceuz onboarding snapshot',
'',
` node ${report.node_version} (need ${report.node_required}) — ${mark(report.mandatory_checks.node_supported)}`,
` platform ${report.platform}`,
` deps ${report.runtime_dependencies} runtime dependencies — ${mark(report.mandatory_checks.zero_runtime_dependencies)}`,
` sources ${report.source_check.total} modules parsed — ${mark(report.mandatory_checks.sources_parse)}`,
'',
' capabilities:',
...report.capabilities.map((cap) => ` ${cap.id.padEnd(14)}${cap.state}\t${cap.reason}`),
'',
` browser path: ${report.browser_path.note}`,
...report.browser_path.requirements.map((line) => ` - ${line}`),
];
if (report.source_check.failed.length) {
lines.push('', ' source failures:');
for (const entry of report.source_check.failed) lines.push(` ${entry.file}: ${entry.error}`);
}
lines.push('', report.ready ? 'Ready: mandatory checks are green.' : 'Not ready: a mandatory check is red (see above).');
return lines.join('\n');
}
function selftest() {
const failures = [];
const assert = (cond, label) => { if (!cond) failures.push(label); };
assert(majorOf('v20.11.1') === 20, 'majorOf parses v20');
assert(majorOf('v18.9.0') === 18, 'majorOf parses v18');
assert(Number.isNaN(majorOf('nonsense')), 'majorOf rejects garbage');
assert(countRuntimeDependencies({ dependencies: { a: '1', b: '2' } }) === 2, 'counts two deps');
assert(countRuntimeDependencies({ dependencies: {} }) === 0, 'empty dependency map is zero');
assert(countRuntimeDependencies({}) === 0, 'missing dependency map is zero');
const darwin = browserPathRequirements('darwin');
assert(darwin.supported_platform === true, 'darwin browser path supported');
assert(browserPathRequirements('linux').supported_platform === false, 'linux browser path unsupported');
assert(darwin.requirements.length >= 3, 'browser requirements are listed');
assert(isReady(mandatoryChecks({ nodeMajor: 20, runtimeDeps: 0, sourcesParse: true })) === true, 'green when all pass');
assert(isReady(mandatoryChecks({ nodeMajor: 20, runtimeDeps: 1, sourcesParse: true })) === false, 'red when a dependency appears');
assert(isReady(mandatoryChecks({ nodeMajor: 18, runtimeDeps: 0, sourcesParse: true })) === false, 'red on old node');
assert(isReady(mandatoryChecks({ nodeMajor: 20, runtimeDeps: 0, sourcesParse: false })) === false, 'red on a syntax failure');
return failures;
}
const mode = process.argv[2] ?? '--human';
if (process.argv.length > 3 || !['--human', '--json', '--selftest', '-h', '--help'].includes(mode)) {
process.stderr.write('usage: node scripts/onboard.mjs [--json|--selftest]\n');
process.exit(2);
}
if (mode === '-h' || mode === '--help') {
process.stdout.write('usage: node scripts/onboard.mjs [--json|--selftest]\n');
} else if (mode === '--selftest') {
const failures = selftest();
if (failures.length) {
process.stderr.write(`onboard selftest: FAILED\n${failures.map((f) => ` - ${f}`).join('\n')}\n`);
process.exit(1);
}
process.stdout.write('onboard selftest: ok\n');
} else {
const report = await buildReport();
process.stdout.write(mode === '--json' ? `${JSON.stringify(report, null, 2)}\n` : `${renderHuman(report)}\n`);
process.exitCode = report.ready ? 0 : 1;
}
+392
View File
@@ -0,0 +1,392 @@
#!/usr/bin/env node
import { execFile, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { access, chmod, lstat, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { arch, platform } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import {
REQUIRED_CONTAINMENT_PROOF_CHANNELS,
computeBrowserFingerprint,
createPfContainmentBackend,
createChildEgressSandbox,
createBrowserProofIntegrity,
} from '../src/browser-security.mjs';
import { createStorage } from '../src/storage.mjs';
import {
createContainmentCanaryHarness,
evaluateCanaryObservations,
} from '../evals/fixtures/pf-containment-canary.mjs';
import { renderCanaryClientSource } from './emit-macos-containment-receipt.mjs';
const execFileAsync = promisify(execFile);
const SELF = fileURLToPath(import.meta.url);
const PROJECT_ROOT = resolve(dirname(SELF), '..');
const PYTHON_CANDIDATES = Object.freeze([
'/opt/homebrew/bin/python3',
'/usr/local/bin/python3',
'/Library/Frameworks/Python.framework/Versions/3.13/bin/python3',
'/Library/Frameworks/Python.framework/Versions/3.12/bin/python3',
'/Library/Frameworks/Python.framework/Versions/3.11/bin/python3',
'/usr/bin/python3',
]);
const SUITES = Object.freeze([
'evals/browser-hostile.test.mjs',
'evals/router.test.mjs',
'evals/p0-acceptance.test.mjs',
'evals/browser-containment.test.mjs',
]);
const MAX_RECEIPT_BYTES = 64 * 1024;
const RECEIPT_RELATIVE = 'security/macos-containment-receipt-v1.json';
const BASE_EXPECTED = 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',
});
const PYTHON_METADATA = [
'import hashlib,importlib.metadata,json,pathlib,sys',
'result={"python_version":sys.version.split()[0],"playwright_version":importlib.metadata.version("playwright"),"chromium_path":None}',
'from playwright.sync_api import sync_playwright',
'manager=sync_playwright().start()',
'result["chromium_path"]=manager.chromium.executable_path',
'manager.stop()',
'path=pathlib.Path(result["chromium_path"])',
'result["chromium_sha256"]="sha256:"+hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else "missing"',
'print(json.dumps(result,separators=(",",":")))',
].join(';');
function parseArgs(argv) {
let dataRoot = resolve(PROJECT_ROOT, '.lynceuz');
let json = false;
const seen = new Set();
for (let index = 0; index < argv.length; index += 1) {
const flag = argv[index];
if (seen.has(flag)) throw new TypeError('duplicate option');
seen.add(flag);
if (flag === '--json') {
json = true;
continue;
}
if (flag === '--data-root') {
const value = argv[index + 1];
if (!value || value.startsWith('--') || /[\0\r\n]/u.test(value)) throw new TypeError('invalid data root');
dataRoot = resolve(PROJECT_ROOT, value);
index += 1;
continue;
}
throw new TypeError('unknown option');
}
if (basename(dataRoot) !== '.lynceuz') {
dataRoot = join(dataRoot, '.lynceuz');
}
return Object.freeze({ dataRoot, json });
}
function sha256(bytes) {
return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
}
async function fileHash(path) {
try { return sha256(await readFile(path)); } catch { return 'missing'; }
}
export async function readReceipt(dataRoot) {
const receiptPath = join(resolve(dataRoot), RECEIPT_RELATIVE);
try {
const info = await lstat(receiptPath);
if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_RECEIPT_BYTES) {
return { error: 'containment_receipt_invalid' };
}
const [root, file] = await Promise.all([realpath(resolve(dataRoot)), realpath(receiptPath)]);
if (!file.startsWith(`${root}/`)) return { error: 'containment_receipt_invalid' };
const bytes = await readFile(file);
return { receipt: JSON.parse(bytes), receiptHash: sha256(bytes) };
} catch (error) {
if (error?.code === 'ENOENT') return { missing: true };
if (error?.code === 'EACCES' || error?.code === 'EPERM') {
return { error: 'containment_receipt_permission_denied' };
}
return { error: 'containment_receipt_invalid' };
}
}
async function expectedContainment(receipt) {
const [macosContainment, canary, wave2] = await Promise.all([
fileHash(resolve(PROJECT_ROOT, 'src/macos-containment.mjs')),
fileHash(resolve(PROJECT_ROOT, 'evals/fixtures/pf-containment-canary.mjs')),
fileHash(resolve(PROJECT_ROOT, 'evals/fixtures/wave2-suite-manifest.json')),
]);
return {
...BASE_EXPECTED,
anchor_sha256: receipt?.pf?.anchor_sha256 ?? `sha256:${'0'.repeat(64)}`,
rules_sha256: receipt?.pf?.rules_sha256 ?? `sha256:${'0'.repeat(64)}`,
source_hashes: { macos_containment: macosContainment, canary },
suite_hashes: { wave2 },
};
}
export async function positiveCanary({ uidName, proxyPort, runner = execFileAsync } = {}) {
let harness;
let temporaryDirectory;
try {
if (typeof uidName !== 'string' || uidName.length === 0 || !Number.isInteger(proxyPort)) {
throw new TypeError('invalid containment canary facts');
}
harness = await createContainmentCanaryHarness({ proxyPort });
temporaryDirectory = await mkdtemp('/private/tmp/lynceuz-gate-canary-');
await chmod(temporaryDirectory, 0o755);
const clientPath = resolve(temporaryDirectory, 'canary-client.mjs');
await writeFile(clientPath, renderCanaryClientSource(), { mode: 0o644 });
const { stdout } = await runner(
'/usr/bin/sudo',
['-n', '-u', uidName, process.execPath, clientPath, JSON.stringify(harness.endpoints)],
{ shell: false, timeout: 20_000, maxBuffer: 256 * 1024, encoding: 'utf8' },
);
const observations = JSON.parse(stdout.trim().split('\n').filter(Boolean).at(-1) ?? '');
return evaluateCanaryObservations(observations);
} catch {
throw Object.assign(new Error('containment_canary_failed'), {
reason: 'containment_canary_failed',
containment_state: 'unavailable_security_gate',
});
} finally {
await harness?.close().catch(() => {});
if (temporaryDirectory) await rm(temporaryDirectory, { recursive: true, force: true }).catch(() => {});
}
}
export function containmentEvidence(receipt, receiptHash) {
return Object.freeze({
backend: receipt.backend,
system_receipt_hash: receiptHash,
uid: Object.freeze({ ...receipt.uid }),
guard_proxy: Object.freeze({ ...receipt.guard_proxy }),
anchor: Object.freeze({ ...receipt.pf }),
boot_session: receipt.boot_session,
reboot_verified: receipt.reboot_verified,
reboot_verified_at: receipt.reboot_verified_at,
source_hashes: Object.freeze({ ...receipt.source_hashes }),
wave2_suite_hash: receipt.suite_hashes.wave2,
negative_control_required: true,
});
}
// The runtime the gate fingerprints once containment is proven ready: the detected machine
// runtime with the live sandbox executable hash replaced by the containment backend and the
// receipt hash pinned as the profile. Shared so the release gate rebuilds the same fingerprint.
export function readyRuntime(detectedRuntime, evidence) {
return { ...detectedRuntime, containment: evidence.backend, profile: evidence.system_receipt_hash };
}
export async function detectRuntime() {
let pythonPath = null;
let metadata = null;
for (const candidate of PYTHON_CANDIDATES) {
try {
await access(candidate);
} catch {
continue;
}
const child = spawnSync(candidate, ['-I', '-c', PYTHON_METADATA], {
cwd: PROJECT_ROOT,
encoding: 'utf8',
env: { LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', PYTHONNOUSERSITE: '1' },
shell: false,
timeout: 10_000,
maxBuffer: 128 * 1024,
});
if (child.status === 0 && child.signal === null) {
try {
metadata = JSON.parse(child.stdout);
pythonPath = candidate;
break;
} catch {}
}
}
const containmentPath = '/usr/bin/sandbox-exec';
return Object.freeze({
installed: Boolean(metadata?.playwright_version && metadata?.chromium_path),
pythonPath,
runtime: {
platform: platform(),
arch: arch(),
node: process.version,
python: pythonPath && metadata?.python_version
? `${pythonPath}@${metadata.python_version}`
: 'missing',
playwright: metadata?.playwright_version ?? 'missing',
chromium: metadata?.chromium_sha256 ?? 'missing',
containment: await fileHash(containmentPath),
},
});
}
function runSuite(relativePath) {
const started = Date.now();
const child = spawnSync(process.execPath, ['--test', relativePath], {
cwd: PROJECT_ROOT,
encoding: 'utf8',
env: { ...process.env, LYNCEUZ_GATE_SUITE: '1' },
shell: false,
timeout: 55_000,
maxBuffer: 2 * 1024 * 1024,
});
return Object.freeze({
suite: relativePath,
passed: child.status === 0 && child.signal === null && !/ℹ skipped [1-9]/u.test(child.stdout),
skipped: /ℹ skipped [1-9]/u.test(child.stdout),
exit_code: child.status,
signal: child.signal,
duration_ms: Date.now() - started,
stdout_hash: sha256(child.stdout ?? ''),
stderr_hash: sha256(child.stderr ?? ''),
});
}
function channels(value) {
return Object.fromEntries(REQUIRED_CONTAINMENT_PROOF_CHANNELS.map((name) => [name, value]));
}
export async function main() {
let options;
try { options = parseArgs(process.argv.slice(2)); } catch {
process.stdout.write(`${JSON.stringify({
kind: 'browser_security_proof', status: 'failed', reason: 'invalid_input',
containment_state: 'unavailable_security_gate',
})}\n`);
return 2;
}
const storage = createStorage({ dataRoot: options.dataRoot, clock: Date.now });
try {
const detected = await detectRuntime();
const loaded = await readReceipt(options.dataRoot);
let reason = loaded.error ?? null;
let evidence;
let canary;
let backend;
if (loaded.missing) {
backend = await createChildEgressSandbox({ proxyPort: 1 });
reason = backend.reason;
} else if (!reason) {
const expected = await expectedContainment(loaded.receipt);
backend = await createPfContainmentBackend({
receipt: loaded.receipt,
expected,
canary: null,
pythonPath: detected.pythonPath,
});
if (backend.reason !== 'containment_canary_missing') reason = backend.reason;
else try {
canary = await positiveCanary({
uidName: expected.uid_name,
proxyPort: expected.guard_proxy_port,
});
} catch (error) {
reason = error?.reason ?? 'containment_canary_failed';
}
if (!reason) {
backend = await createPfContainmentBackend({
receipt: loaded.receipt,
expected,
canary,
pythonPath: detected.pythonPath,
});
if (backend.state !== 'ready') {
reason = !detected.installed && backend.reason === 'containment_launch_unavailable'
? 'playwright_missing'
: backend.reason;
}
else evidence = containmentEvidence(loaded.receipt, loaded.receiptHash);
}
}
const runtime = evidence
? readyRuntime(detected.runtime, evidence)
: { ...detected.runtime, profile: backend?.profileHash ?? 'sandbox_loopback_scope_unproven' };
const fingerprint = await computeBrowserFingerprint({ runtime, ...(evidence ? { containment: evidence } : {}) });
const generatedAt = new Date().toISOString();
const base = {
kind: 'browser_security_proof',
schema_version: 1,
fingerprint: fingerprint.digest,
generated_at: generatedAt,
platform: runtime.platform,
arch: runtime.arch,
runtime,
source_hashes: fingerprint.sources,
channels: channels(false),
containment_state: 'unavailable_security_gate',
...(evidence ? { containment: evidence } : {}),
};
await storage.publishPrivateJson('security/browser-proof-v1.json', {
...base,
status: 'in_progress',
reason: 'gate_running',
suites: [],
});
const suites = SUITES.map(runSuite);
if (!reason && !suites.every((suite) => suite.passed)) reason = 'suite_failed';
if (!reason && !detected.installed) reason = 'playwright_missing';
if (!reason && backend?.state !== 'ready') reason = backend?.reason ?? 'sandbox_loopback_scope_unproven';
const verifiedFingerprint = await computeBrowserFingerprint({
runtime, ...(evidence ? { containment: evidence } : {}),
});
if (!reason && verifiedFingerprint.digest !== fingerprint.digest) {
reason = 'fingerprint_drift_during_gate';
}
if (reason) {
const failed = { ...base, status: 'failed', reason, suites };
await storage.publishPrivateJson('security/browser-proof-v1.json', failed);
process.stdout.write(`${JSON.stringify(failed)}\n`);
return 1;
}
const passedDraft = {
...base,
fingerprint: verifiedFingerprint.digest,
source_hashes: verifiedFingerprint.sources,
status: 'passed',
reason: 'proof_valid',
channels: channels(true),
containment_state: 'ready',
suites,
};
const passed = { ...passedDraft, marker_hash: createBrowserProofIntegrity(passedDraft) };
await storage.publishPrivateJson('security/browser-proof-v1.json', passed);
process.stdout.write(`${JSON.stringify(passed)}\n`);
return 0;
} catch {
const failed = {
kind: 'browser_security_proof',
schema_version: 1,
status: 'failed',
reason: 'gate_internal_error',
fingerprint: null,
generated_at: new Date().toISOString(),
channels: channels(false),
containment_state: 'unavailable_security_gate',
suites: [],
};
await storage.publishPrivateJson('security/browser-proof-v1.json', failed).catch(() => {});
process.stdout.write(`${JSON.stringify(failed)}\n`);
return 1;
}
}
if (process.argv[1] && resolve(process.argv[1]) === SELF) {
process.exitCode = await main().catch(async () => {
process.stdout.write(`${JSON.stringify({
kind: 'browser_security_proof', status: 'failed', reason: 'gate_internal_error',
containment_state: 'unavailable_security_gate',
})}\n`);
return 1;
});
}
+346
View File
@@ -0,0 +1,346 @@
#!/usr/bin/env node
// Honest, non-recursive P1 release gate. Confirms the P0/P1 suite set has not drifted,
// runs ONLY the manifest-designated release suites via a fixed `node --test` argv, then
// requires a CURRENT valid browser-security proof before sealing an atomic release marker.
// It never re-runs itself (no recursion) and never deletes P0 evidence.
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { arch, platform } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import {
computeBrowserFingerprint,
verifyBrowserSecurityProof,
browserCapabilityState,
} from '../src/browser-security.mjs';
import {
containmentEvidence,
detectRuntime,
readReceipt,
readyRuntime,
} from './p1-browser-gate.mjs';
import { createStorage } from '../src/storage.mjs';
const PROJECT_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const MARKER_RELATIVE = 'release/p1-release-proof-v1.json';
const BROWSER_GATE = 'scripts/p1-browser-gate.mjs';
const BROWSER_PROOF_RELATIVE = 'security/browser-proof-v1.json';
const SUITE_MANIFEST_RELATIVE = 'evals/fixtures/p1-suite-manifest.json';
const MAX_BUFFER = 2 * 1024 * 1024;
const SUITE_TIMEOUT_MS = 120_000;
const BROWSER_GATE_TIMEOUT_MS = 240_000;
const EXIT_RELEASED = 0;
const EXIT_REJECTED = 10;
const EXIT_BLOCKED_BROWSER = 20;
const EXIT_INVALID_INPUT = 2;
// Fail-closed fingerprint used only when the independent facts cannot be read (no/invalid
// receipt): a digest that can never match a real proof, so verify blocks, never releases.
const UNPROVABLE_FINGERPRINT = Object.freeze({ digest: `sha256:${'0'.repeat(64)}` });
// Closed list of browser reasons that are an HONEST block (accepted, no marker) rather than
// a rejected verdict. Either the browser gate reports a proven containment/availability limit,
// or verifyBrowserSecurityProof reports there is no current valid proof. Anything else — a
// suite failure, an internal error, an unknown/forged reason — is rejected, never accepted.
const ACCEPTED_BROWSER_REASONS = Object.freeze(new Set([
'sandbox_loopback_scope_unproven',
'sandbox_platform_unsupported',
'sandbox_executable_missing',
'playwright_missing',
'proof_missing',
'proof_stale',
'proof_corrupt',
'fingerprint_mismatch',
'proof_failed_or_incomplete',
]));
// Minimal allowlisted environment for spawned children: no inherited secrets, only what
// node/python need to locate a runtime, plus a deterministic locale.
function suiteEnv() {
return {
PATH: process.env.PATH ?? '',
HOME: process.env.HOME ?? '',
TMPDIR: process.env.TMPDIR ?? '',
LANG: 'C.UTF-8',
LC_ALL: 'C.UTF-8',
LYNCEUZ_GATE_SUITE: '1',
};
}
function sha256(bytes) {
return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
}
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);
}
async function hashFile(path) {
try { return sha256(await readFile(path)); } catch { return null; }
}
function firstJsonLine(stdout) {
if (typeof stdout !== 'string') return null;
const line = stdout.split('\n', 1)[0];
try { return JSON.parse(line); } catch { return null; }
}
function verdict(fields) {
return Object.freeze({ kind: 'lynceuz_p1_release_proof', cost_money: 0, marker_path: MARKER_RELATIVE, ...fields });
}
function rejected(reason, exitCode = EXIT_REJECTED) {
return verdict({ accepted: false, exit_code: exitCode, status: 'rejected', p1_release_state: 'rejected', reason });
}
function blockedBrowser(reason) {
return verdict({ accepted: true, exit_code: EXIT_BLOCKED_BROWSER, status: 'blocked', p1_release_state: 'blocked_browser', reason });
}
function validManifest(manifest) {
return manifest && typeof manifest === 'object' && !Array.isArray(manifest)
&& manifest.baseline_manifest && typeof manifest.baseline_manifest.sha256 === 'string'
&& typeof manifest.baseline_manifest.path === 'string'
&& Array.isArray(manifest.files)
&& manifest.files.every((file) => file && typeof file.path === 'string' && typeof file.sha256 === 'string');
}
// Detects whether the release-suite set on disk still matches the pinned manifest. A drift is a
// rejected verdict, never an accepted block: the gate cannot certify a suite set it did not run.
async function detectDrift(projectRoot, manifest) {
const targets = [
{ path: manifest.baseline_manifest.path, sha256: manifest.baseline_manifest.sha256 },
...manifest.files.map((file) => ({ path: file.path, sha256: file.sha256 })),
];
for (const target of targets) {
const actual = await hashFile(join(projectRoot, target.path));
if (actual !== target.sha256) return target.path;
}
return null;
}
async function sealMarker({ dataRoot, now, p0Hash, p1Hash, verification }) {
const browserProofHash = await hashFile(join(dataRoot, BROWSER_PROOF_RELATIVE));
if (browserProofHash === null) return rejected('gate_internal_error');
const capability = browserCapabilityState({
id: 'playwright',
installed: true,
version: verification.proof?.runtime?.playwright ?? null,
allowRendered: true,
proof: verification,
});
const payload = {
kind: 'lynceuz_p1_release_proof',
schema_version: 1,
cost_money: 0,
generated_at: new Date(Number(now())).toISOString(),
node: process.version,
platform: process.platform,
arch: process.arch,
suite_hashes: { p0: p0Hash, p1: p1Hash },
browser_proof_hash: browserProofHash,
browser_proof_fingerprint: verification.fingerprint,
capability_state: capability.state,
};
const marker = { ...payload, marker_hash: sha256(stableJson(payload)) };
const storage = createStorage({ dataRoot, clock: now });
await storage.publishPrivateJson(MARKER_RELATIVE, marker);
return verdict({
accepted: true,
exit_code: EXIT_RELEASED,
status: 'passed',
p1_release_state: 'released',
reason: 'released',
marker_hash: marker.marker_hash,
});
}
// Pure, injectable gate evaluation. `runner(executable, argv, options)` returns a spawn-style
// result ({ status, signal, stdout, stderr }); tests inject a stub so no real process is spawned.
export async function evaluateReleaseGate({
dataRoot,
projectRoot = PROJECT_ROOT,
suiteManifest,
fingerprint,
now = Date.now,
runner,
} = {}) {
try {
if (typeof dataRoot !== 'string' || basename(resolve(dataRoot)) !== '.lynceuz'
|| typeof runner !== 'function' || !validManifest(suiteManifest)
|| !fingerprint || typeof fingerprint.digest !== 'string') {
return rejected('invalid_input', EXIT_INVALID_INPUT);
}
const drifted = await detectDrift(projectRoot, suiteManifest);
if (drifted) return rejected('hash_drift');
const p0Hash = suiteManifest.baseline_manifest.sha256;
const p1Hash = sha256(stableJson(suiteManifest));
// Fixed `node --test` argv over ONLY the release-gate suites. p1-release.test.mjs carries
// run_by_release_gate=false, so the gate never runs its own contract test: no recursion.
const suitePaths = suiteManifest.files
.filter((file) => file.run_by_release_gate === true)
.map((file) => join(projectRoot, file.path));
const suiteRun = await runner(process.execPath, ['--test', ...suitePaths], {
cwd: projectRoot,
env: suiteEnv(),
shell: false,
timeout: SUITE_TIMEOUT_MS,
maxBuffer: MAX_BUFFER,
encoding: 'utf8',
});
if (!(suiteRun && suiteRun.status === 0 && !suiteRun.signal)) {
return rejected('suite_failed');
}
// Only now, with suites green, run the independent browser gate against the same data root.
const gateRun = await runner(process.execPath, [
join(projectRoot, BROWSER_GATE), '--json', '--data-root', dataRoot,
], {
cwd: projectRoot,
env: suiteEnv(),
shell: false,
timeout: BROWSER_GATE_TIMEOUT_MS,
maxBuffer: MAX_BUFFER,
encoding: 'utf8',
});
let browserReason;
if (gateRun && gateRun.status === 0 && !gateRun.signal) {
// Do NOT reinvent fingerprint rules: verifyBrowserSecurityProof owns them.
const verification = await verifyBrowserSecurityProof({ dataRoot, fingerprint, now });
if (verification.valid) {
return await sealMarker({ dataRoot, now, p0Hash, p1Hash, verification });
}
browserReason = verification.reason;
} else {
const parsed = firstJsonLine(gateRun?.stdout);
if (!parsed || typeof parsed.reason !== 'string') return rejected('malformed_gate_output');
browserReason = parsed.reason;
}
return ACCEPTED_BROWSER_REASONS.has(browserReason)
? blockedBrowser(browserReason)
: rejected(browserReason);
} catch {
return rejected('gate_internal_error');
}
}
// Build the fingerprint we EXPECT a ready proof to carry, from independent facts only — the
// machine's runtime detection plus the root-generated containment receipt — never from the proof
// under test. Reuses the browser gate's own detectRuntime/containmentEvidence/readyRuntime so both
// sides fingerprint identically; verifyBrowserSecurityProof still owns the comparison rules.
export async function expectedBrowserFingerprint({
dataRoot,
detect = detectRuntime,
loadReceipt = readReceipt,
} = {}) {
try {
const loaded = await loadReceipt(dataRoot);
if (!loaded?.receipt) return UNPROVABLE_FINGERPRINT;
const detected = await detect();
const evidence = containmentEvidence(loaded.receipt, loaded.receiptHash);
return await computeBrowserFingerprint({ runtime: readyRuntime(detected.runtime, evidence), containment: evidence });
} catch {
return UNPROVABLE_FINGERPRINT;
}
}
// The single wiring seam: rebuild the expected fingerprint from independent facts and hand it to the
// pure evaluator. main() and the contract test both drive THIS, so the wiring — not just the pieces —
// is exercised. Injection points are inputs only (roots, runner, runtime/receipt readers); a ready
// fingerprint is never accepted here, so a test can't skip past the code that computes it.
export async function runReleaseGate({
dataRoot,
projectRoot = PROJECT_ROOT,
suiteManifest,
now = Date.now,
runner,
detect = detectRuntime,
loadReceipt = readReceipt,
} = {}) {
const fingerprint = await expectedBrowserFingerprint({ dataRoot, detect, loadReceipt });
return evaluateReleaseGate({ dataRoot, projectRoot, suiteManifest, fingerprint, now, runner });
}
function parseArgs(argv) {
let dataRoot = resolve(PROJECT_ROOT, '.lynceuz');
let json = false;
const seen = new Set();
for (let index = 0; index < argv.length; index += 1) {
const flag = argv[index];
if (seen.has(flag)) throw new TypeError('duplicate option');
seen.add(flag);
if (flag === '--json') { json = true; continue; }
if (flag === '--data-root') {
const value = argv[index + 1];
if (!value || value.startsWith('--') || /[\0\r\n]/u.test(value)) throw new TypeError('invalid data root');
dataRoot = resolve(PROJECT_ROOT, value);
index += 1;
continue;
}
throw new TypeError('unknown option');
}
if (basename(dataRoot) !== '.lynceuz') dataRoot = join(dataRoot, '.lynceuz');
return { dataRoot, json };
}
function spawnRunner(executable, argv, options) {
return spawnSync(executable, argv, options);
}
async function main(argv) {
let options;
try { options = parseArgs(argv); } catch {
const result = rejected('invalid_input', EXIT_INVALID_INPUT);
process.stdout.write(`${JSON.stringify(result)}\n`);
return result.exit_code;
}
let suiteManifest;
try {
suiteManifest = JSON.parse(await readFile(join(PROJECT_ROOT, SUITE_MANIFEST_RELATIVE)));
} catch {
const result = rejected('gate_internal_error');
if (options.json) process.stdout.write(`${JSON.stringify(result)}\n`);
return result.exit_code;
}
// Containment is unsealed: runReleaseGate rebuilds the expected fingerprint from the same
// independent facts the browser gate fingerprints (detected runtime + containment receipt), so a
// proven-ready proof matches and releases, while any source/receipt drift still mismatches and
// blocks. main() owns no fingerprint logic — the one computation lives inside runReleaseGate.
const result = await runReleaseGate({
dataRoot: options.dataRoot,
projectRoot: PROJECT_ROOT,
suiteManifest,
now: Date.now,
runner: spawnRunner,
});
if (options.json) process.stdout.write(`${JSON.stringify(result)}\n`);
return result.exit_code;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
process.exitCode = await main(process.argv.slice(2));
}
export {
MARKER_RELATIVE,
ACCEPTED_BROWSER_REASONS,
parseArgs,
stableJson,
};
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env node
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
inspectMacosContainment,
verifyMacosContainmentReceipt,
} from '../src/macos-containment.mjs';
import {
createContainmentCanaryHarness,
probeContainmentCanary,
} from '../evals/fixtures/pf-containment-canary.mjs';
const PROJECT_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const RECEIPT_PATH = resolve(PROJECT_ROOT, '.lynceuz/security/macos-containment-receipt-v1.json');
const MAX_RECEIPT_BYTES = 64 * 1024;
const BASE_EXPECTED = 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: `sha256:${'0'.repeat(64)}`,
rules_sha256: `sha256:${'0'.repeat(64)}`,
});
function output(mode, verdict, canary = undefined) {
process.stdout.write(`${JSON.stringify({
kind: 'lynceuz_macos_containment_probe',
schema_version: 1,
mode,
...verdict,
...(canary ? { canary } : {}),
})}\n`);
}
function parseArgs(argv) {
const allowed = new Set(['--json', '--negative-control']);
if (argv.some((arg) => !allowed.has(arg)) || new Set(argv).size !== argv.length) {
throw new TypeError('invalid_input');
}
return argv.includes('--negative-control') ? 'negative-control' : 'positive';
}
async function readReceipt() {
try {
const bytes = await readFile(RECEIPT_PATH);
if (bytes.length > MAX_RECEIPT_BYTES) return { error: 'containment_receipt_invalid' };
return { receipt: JSON.parse(bytes.toString('utf8')) };
} catch (error) {
if (error?.code === 'ENOENT') return { error: 'containment_receipt_missing' };
if (error?.code === 'EACCES' || error?.code === 'EPERM') {
return { error: 'containment_receipt_permission_denied' };
}
return { error: 'containment_receipt_invalid' };
}
}
async function fileHash(relativePath) {
const bytes = await readFile(resolve(PROJECT_ROOT, relativePath));
if (bytes.length > 2 * 1024 * 1024) throw new Error('source_file_too_large');
return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
}
async function expectedFacts() {
const [macosContainment, canary, wave2] = await Promise.all([
fileHash('src/macos-containment.mjs'),
fileHash('evals/fixtures/pf-containment-canary.mjs'),
fileHash('evals/fixtures/wave2-suite-manifest.json'),
]);
return {
...BASE_EXPECTED,
anchor_sha256: `sha256:${'0'.repeat(64)}`,
rules_sha256: `sha256:${'0'.repeat(64)}`,
source_hashes: { macos_containment: macosContainment, canary },
suite_hashes: { wave2 },
};
}
async function main() {
let mode;
try {
mode = parseArgs(process.argv.slice(2));
} catch {
output('invalid', { state: 'unavailable_security_gate', reason: 'invalid_input' });
return 2;
}
let harness;
try {
if (mode === 'negative-control') {
harness = await createContainmentCanaryHarness();
const canary = await probeContainmentCanary({
endpoints: harness.endpoints,
negativeControl: true,
timeoutMs: 1_000,
});
output(mode, {
state: 'unavailable_security_gate',
reason: canary.reason,
}, canary);
return canary.exit_code || 1;
}
const loaded = await readReceipt();
if (loaded.error) {
output(mode, { state: 'unavailable_security_gate', reason: loaded.error });
return 1;
}
const provisionalExpected = await expectedFacts();
const system = await inspectMacosContainment({ expected: provisionalExpected });
if (system.state === 'unavailable_security_gate') {
output(mode, system);
return 1;
}
const expected = {
...provisionalExpected,
anchor_sha256: system.pf.anchor_sha256,
rules_sha256: system.pf.rules_sha256,
};
harness = await createContainmentCanaryHarness();
const canary = await probeContainmentCanary({
endpoints: harness.endpoints,
timeoutMs: 1_000,
});
const verdict = await verifyMacosContainmentReceipt({
receipt: loaded.receipt,
expected,
system,
canary,
});
output(mode, verdict, canary);
return verdict.state === 'ready' ? 0 : 1;
} catch {
output(mode ?? 'invalid', {
state: 'unavailable_security_gate',
reason: 'containment_probe_unavailable',
});
return 1;
} finally {
await harness?.close().catch(() => {});
}
}
process.exitCode = await main();