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

This commit is contained in:
public-repo-gate
2026-08-31 22:21:33 +03:00
parent b4431b420c
commit 61a7f0d116
97 changed files with 22291 additions and 1 deletions
View File
+215
View File
@@ -0,0 +1,215 @@
import { Readable } from 'node:stream';
import {
createBrotliDecompress,
createGunzip,
createInflate,
} from 'node:zlib';
import { ATTEMPT_CODE, ATTEMPT_KIND } from '../contracts.mjs';
const TRANSIENT_HTTP = new Set([408, 425, 500, 502, 503, 504]);
const POLICY_STOP = new Set([
'invalid_intent',
'invalid_url',
'ambiguous_url',
'scheme_denied',
'userinfo_denied',
'special_hostname',
'non_public_ip',
'dns_non_public',
'peer_mismatch',
'invalid_redirect',
'redirect_downgrade',
'redirect_loop',
]);
class BodyLimitError extends Error {}
function normalizeHeaders(headers) {
const normalized = {};
for (const [name, value] of Object.entries(headers ?? {})) {
normalized[name.toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value);
}
return normalized;
}
function safeConditionalHeaders(headers) {
const safe = {};
for (const [name, value] of Object.entries(headers ?? {})) {
const lower = name.toLowerCase();
if (!['if-none-match', 'if-modified-since'].includes(lower)) {
throw new TypeError('unsafe conditional header');
}
if (typeof value !== 'string' || value.length === 0 || value.length > 1024
|| /[\r\n\0]/u.test(value)) {
throw new TypeError('invalid conditional header');
}
safe[lower === 'if-none-match' ? 'If-None-Match' : 'If-Modified-Since'] = value;
}
return safe;
}
function requestHeaders(conditionalHeaders) {
return {
'User-Agent': 'Lynceuz/0.1',
Accept: 'text/html,application/xhtml+xml,application/json,application/xml,text/xml,text/plain;q=0.9,*/*;q=0.1',
'Accept-Encoding': 'gzip, deflate, br',
...safeConditionalHeaders(conditionalHeaders),
};
}
async function discard(body) {
try {
body?.destroy?.();
} catch {
// Outcome remains fail-closed even when cleanup itself fails.
}
}
async function collectBounded(body, maximum, signal) {
if (!Number.isSafeInteger(maximum) || maximum <= 0) throw new TypeError('body limit is invalid');
const chunks = [];
let size = 0;
try {
for await (const value of body) {
if (signal?.aborted) throw signal.reason ?? new Error('aborted');
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value);
size += chunk.length;
if (size > maximum) throw new BodyLimitError('body limit exceeded');
chunks.push(chunk);
}
} catch (error) {
body?.destroy?.();
throw error;
}
return Buffer.concat(chunks, size);
}
function decoderFor(encoding) {
switch (encoding) {
case 'gzip':
case 'x-gzip': return createGunzip();
case 'deflate': return createInflate();
case 'br': return createBrotliDecompress();
default: return null;
}
}
async function decodeBounded(wire, encoding, maximum, signal) {
if (encoding === '' || encoding === 'identity') {
if (wire.length > maximum) throw new BodyLimitError('decoded body limit exceeded');
return wire;
}
if (encoding.includes(',')) throw new TypeError('stacked content encoding is unsupported');
const decoder = decoderFor(encoding);
if (!decoder) throw new TypeError('content encoding is unsupported');
Readable.from([wire]).pipe(decoder);
return collectBounded(decoder, maximum, signal);
}
function retryAfterMs(value) {
if (typeof value !== 'string') return 0;
const seconds = Number(value.trim());
if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);
const date = Date.parse(value);
return Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
}
function statusOutcome(statusCode, headers) {
if ((statusCode >= 200 && statusCode < 300) || statusCode === 304) return null;
if (statusCode === 403) return { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.ACCESS_DENIED };
if (statusCode === 401) return { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.AUTH_REQUIRED };
if (statusCode === 402) return { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.PAID_REQUIRED };
if (statusCode === 404) return { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.NOT_FOUND };
if (statusCode === 410) return { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.GONE };
if (statusCode === 429) {
return {
kind: ATTEMPT_KIND.RETRYABLE,
code: ATTEMPT_CODE.RATE_LIMITED,
retryAfterMs: retryAfterMs(headers['retry-after']),
};
}
if (TRANSIENT_HTTP.has(statusCode)) {
return { kind: ATTEMPT_KIND.RETRYABLE, code: ATTEMPT_CODE.HTTP_5XX };
}
return { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.ACCESS_DENIED };
}
function errorOutcome(error, signal) {
if (signal?.aborted) return { kind: ATTEMPT_KIND.RETRYABLE, code: ATTEMPT_CODE.TIMEOUT };
if (error instanceof BodyLimitError) {
return { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.HARD_LIMIT };
}
if (POLICY_STOP.has(error?.code) || error?.code === 'redirect_limit') {
return {
kind: ATTEMPT_KIND.TERMINAL,
code: error?.code === 'redirect_limit' ? ATTEMPT_CODE.HARD_LIMIT : ATTEMPT_CODE.POLICY_DENIED,
};
}
if (['request_failed', 'dns_resolution_failed', 'connect_failed'].includes(error?.code)) {
return { kind: ATTEMPT_KIND.RETRYABLE, code: ATTEMPT_CODE.NETWORK };
}
return { kind: ATTEMPT_KIND.BROKEN, code: ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR };
}
export function createNativeHttpAdapter({ gateway }) {
if (!gateway || typeof gateway.execute !== 'function') {
throw new TypeError('native adapter requires an egress gateway');
}
return Object.freeze({
id: 'native',
version: '1',
async run(input) {
const maxWireBytes = input?.limits?.maxWireBytes;
const maxDecodedBytes = input?.limits?.maxDecodedBytes;
try {
const response = await gateway.execute({
runId: input.runId,
purpose: 'page',
url: input.url,
method: input.method ?? 'GET',
headers: requestHeaders(input.conditionalHeaders),
remaining: input.remaining,
}, { signal: input.signal });
const headers = normalizeHeaders(response.headers);
const classified = statusOutcome(response.statusCode, headers);
if (classified) {
await discard(response.body);
return {
...classified,
evidence: {
statusCode: response.statusCode,
headers,
finalUrl: response.finalUrl,
redirectChain: response.redirectChain,
permit: response.permit,
},
};
}
const wire = await collectBounded(response.body, maxWireBytes, input.signal);
const body = await decodeBounded(
wire,
(headers['content-encoding'] ?? 'identity').trim().toLowerCase(),
maxDecodedBytes,
input.signal,
);
return {
kind: ATTEMPT_KIND.SUCCESS,
code: ATTEMPT_CODE.OK,
response: {
statusCode: response.statusCode,
headers,
body,
wireBytes: wire.length,
decodedBytes: body.length,
finalUrl: response.finalUrl,
redirectChain: response.redirectChain,
permit: response.permit,
},
};
} catch (error) {
return errorOutcome(error, input?.signal);
}
},
});
}
+84
View File
@@ -0,0 +1,84 @@
import { ATTEMPT_CODE, ATTEMPT_KIND, CAPABILITY_STATE, deepFreeze } from '../contracts.mjs';
import { validContainedBrowserLaunchPlan } from '../process.mjs';
const CONTAINED_LAUNCH = Object.freeze({ shell: false });
function outcome(kind, code, details) {
return deepFreeze({ kind, code, ...(details ? { details } : {}) });
}
export function createPlaywrightAdapter({ capability, sandbox, supervisor } = {}) {
const current = deepFreeze({ ...(capability ?? {
state: CAPABILITY_STATE.UNAVAILABLE_SECURITY_GATE,
reason: 'proof_missing',
}) });
return Object.freeze({
id: 'playwright',
version: current.version ?? null,
async probe() { return current; },
async run({ job, request } = {}) {
if (current.state !== CAPABILITY_STATE.READY) {
return outcome(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.POLICY_UNENFORCEABLE, {
reason: current.reason ?? 'proof_missing',
});
}
if (!sandbox?.proofEligible || typeof sandbox.launch !== 'function') {
return outcome(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.POLICY_UNENFORCEABLE, {
reason: sandbox?.reason ?? 'sandbox_unavailable',
});
}
if (!supervisor || typeof supervisor.run !== 'function') {
return outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'browser_supervisor_unavailable',
});
}
if (!job || job.policy?.allowRendered !== true || typeof job.target?.url !== 'string') {
return outcome(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.POLICY_UNENFORCEABLE, {
reason: 'rendered_not_allowed',
});
}
let launchPlan;
try {
launchPlan = sandbox.launch();
} catch {}
if (!validContainedBrowserLaunchPlan(launchPlan)
|| launchPlan.shell !== CONTAINED_LAUNCH.shell) {
return outcome(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.POLICY_UNENFORCEABLE, {
reason: 'containment_launch_plan_invalid',
});
}
const result = await supervisor.run('python-browser', {
launchPlan,
request: {
version: 1,
id: request?.id ?? 'render',
operation: 'render',
url: job.target.url,
output_path: request?.outputPath,
wait_ms: request?.waitMs ?? 0,
scroll_steps: request?.scrollSteps ?? 0,
scroll_y: request?.scrollY ?? 0,
proxy: request?.proxy,
},
signal: request?.signal,
});
if (result?.kind !== ATTEMPT_KIND.SUCCESS) {
return result ?? outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'browser_protocol_failed',
});
}
if (result.response?.ok !== true) {
return result.response?.code === 'render_failed'
? outcome(ATTEMPT_KIND.RETRYABLE, ATTEMPT_CODE.NETWORK, { reason: 'render_failed' })
: outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'browser_protocol_failed',
});
}
return outcome(ATTEMPT_KIND.SUCCESS, ATTEMPT_CODE.OK, {
...result.response.payload,
proofFingerprint: current.proofFingerprint,
});
},
});
}
+676
View File
@@ -0,0 +1,676 @@
import { createHash, randomUUID } from 'node:crypto';
import { constants as FS_CONSTANTS } from 'node:fs';
import { mkdir, open, realpath, rm } from 'node:fs/promises';
import { dirname, isAbsolute, join, relative } from 'node:path';
import {
ATTEMPT_CODE,
ATTEMPT_KIND,
CAPABILITY_STATE,
deepFreeze,
} from '../contracts.mjs';
import { parsePublicUrl } from '../policy.mjs';
import { PYTHON_HELPER_PATH, createProcessSupervisor } from '../process.mjs';
const MAX_SCHEMA_FIELDS = 64;
const MAX_SELECTOR_LENGTH = 256;
const MAX_PATH_SEGMENTS = 16;
const DEFAULT_INPUT_BYTES = 16 * 1024 * 1024;
const DEFAULT_OUTPUT_BYTES = 2 * 1024 * 1024;
const FIELD_NAME = /^(?!__proto__$|prototype$|constructor$)[A-Za-z_][A-Za-z0-9_.-]{0,63}$/u;
const PATH_KEY = /^(?!__proto__$|prototype$|constructor$)[@A-Za-z_][@A-Za-z0-9_.:-]{0,63}$/u;
const SAFE_SELECTOR = /^[A-Za-z0-9_.*#\-[\]="'\s>+~,]+$/u;
const SAFE_ATTR = /^(?:href|src|content|datetime|value|title|alt|name|id|class|role|itemprop|property|type|data-[A-Za-z0-9_.:-]+|aria-[A-Za-z0-9_.:-]+)$/u;
const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean', 'null']);
const TOP_LEVEL_SCHEMA_KEYS = new Set(['schema_version', 'fields']);
const FIELD_KEYS = new Set(['source', 'selector', 'take', 'path', 'required', 'many', 'type']);
const PARSE_KEYS = new Set([
'title',
'canonical_candidate',
'text',
'markdown',
'links',
'metadata',
'alternate_candidates',
'jsonld',
]);
function plainObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function schemaError(message) {
throw new TypeError(`extract schema ${message}`);
}
function setOwn(target, key, value) {
Object.defineProperty(target, key, {
value,
enumerable: true,
configurable: true,
writable: true,
});
}
function jsonCopy(value, label, seen = new WeakSet()) {
if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
if (typeof value === 'number' && Number.isFinite(value)) return value;
if (!value || typeof value !== 'object' || seen.has(value)) {
throw new TypeError(`${label} is not bounded JSON`);
}
seen.add(value);
try {
if (Array.isArray(value)) return value.map((item) => jsonCopy(item, label, seen));
if (!plainObject(value)) throw new TypeError(`${label} must be a plain object`);
const copy = {};
for (const key of Object.keys(value).sort()) setOwn(copy, key, jsonCopy(value[key], label, seen));
return copy;
} finally {
seen.delete(value);
}
}
function stableBytes(value) {
return Buffer.from(`${JSON.stringify(jsonCopy(value, 'output'))}\n`);
}
function validateSelector(value) {
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_SELECTOR_LENGTH
|| !SAFE_SELECTOR.test(value) || /(?:^|\W):|[(){};\\]/u.test(value)) {
schemaError('selector is invalid or unbounded');
}
return value.trim();
}
function validateTake(value) {
if (value === 'text') return value;
if (typeof value !== 'string' || !value.startsWith('@') || !SAFE_ATTR.test(value.slice(1))
|| /^@(?:on|style|srcdoc|formaction)/iu.test(value)) {
schemaError('attr is invalid or unsafe');
}
return value;
}
function validatePath(value) {
if (!Array.isArray(value) || value.length === 0 || value.length > MAX_PATH_SEGMENTS) {
schemaError('JSON-LD path is invalid or unbounded');
}
return value.map((segment) => {
if (Number.isSafeInteger(segment) && segment >= 0 && segment <= 10_000) return segment;
if (typeof segment === 'string' && PATH_KEY.test(segment)) return segment;
schemaError('JSON-LD path segment is unsafe');
return null;
});
}
export function validateExtractSchema(schema) {
if (!plainObject(schema)) schemaError('must be an object');
if (Object.keys(schema).some((key) => !TOP_LEVEL_SCHEMA_KEYS.has(key))) {
schemaError('contains unknown top-level keys');
}
if (schema.schema_version !== 1) schemaError('schema_version must be 1');
if (!plainObject(schema.fields)) schemaError('fields must be an object');
const names = Object.keys(schema.fields).sort();
if (names.length === 0 || names.length > MAX_SCHEMA_FIELDS) schemaError('field count is invalid');
const fields = {};
for (const name of names) {
if (!FIELD_NAME.test(name)) schemaError(`field name is unsafe: ${name}`);
const field = schema.fields[name];
if (!plainObject(field) || Object.keys(field).some((key) => !FIELD_KEYS.has(key))) {
schemaError(`field ${name} contains unknown keys`);
}
if (!['css', 'jsonld'].includes(field.source)) schemaError(`field ${name} source is invalid`);
if (field.required !== undefined && typeof field.required !== 'boolean') {
schemaError(`field ${name} required flag is invalid`);
}
if (field.many !== undefined && typeof field.many !== 'boolean') {
schemaError(`field ${name} many flag is invalid`);
}
if (field.type !== undefined && !PRIMITIVE_TYPES.has(field.type)) {
schemaError(`field ${name} primitive type is invalid`);
}
const common = {
source: field.source,
required: field.required ?? false,
many: field.many ?? false,
...(field.type === undefined ? {} : { type: field.type }),
};
if (field.source === 'css') {
if (field.path !== undefined) schemaError(`field ${name} mixes CSS and JSON-LD`);
fields[name] = {
...common,
selector: validateSelector(field.selector),
take: validateTake(field.take),
};
} else {
if (field.selector !== undefined || field.take !== undefined) {
schemaError(`field ${name} mixes JSON-LD and CSS`);
}
fields[name] = { ...common, path: validatePath(field.path) };
}
}
const normalized = { schema_version: 1, fields };
if (Buffer.byteLength(JSON.stringify(normalized)) > 64 * 1024) schemaError('is too large');
return deepFreeze(normalized);
}
function positiveInteger(value, fallback, label) {
const selected = value ?? fallback;
if (!Number.isSafeInteger(selected) || selected <= 0) throw new TypeError(`${label} is invalid`);
return selected;
}
function sha256(bytes) {
return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
}
function candidateUrl(value) {
if (value === null) return null;
if (typeof value !== 'string' || value.length > 8192) throw new TypeError('candidate URL is invalid');
const url = new URL(value);
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
throw new TypeError('candidate URL is invalid');
}
url.hash = '';
return url.href;
}
function boundedString(value, limit, label) {
if (typeof value !== 'string' || Buffer.byteLength(value) > limit) {
throw new TypeError(`${label} is invalid`);
}
return value;
}
function validateParseResult(value) {
if (!plainObject(value) || Object.keys(value).some((key) => !PARSE_KEYS.has(key))) {
throw new TypeError('parse result has unknown fields');
}
if (!Array.isArray(value.links) || value.links.length > 4096) {
throw new TypeError('parse links are invalid');
}
const links = value.links.map(candidateUrl);
if (!plainObject(value.metadata) || Object.keys(value.metadata).length > 128) {
throw new TypeError('parse metadata is invalid');
}
const metadata = {};
for (const key of Object.keys(value.metadata).sort()) {
if (key.length > 128 || ['__proto__', 'prototype', 'constructor'].includes(key)) {
throw new TypeError('metadata key is invalid');
}
setOwn(metadata, key, boundedString(value.metadata[key], 4096, 'metadata value'));
}
if (!Array.isArray(value.alternate_candidates) || value.alternate_candidates.length > 128) {
throw new TypeError('alternate candidates are invalid');
}
const alternateCandidates = value.alternate_candidates.map((candidate) => {
if (!plainObject(candidate)
|| Object.keys(candidate).some((key) => !['type', 'url'].includes(key))) {
throw new TypeError('alternate candidate is invalid');
}
return {
type: boundedString(candidate.type, 256, 'alternate type'),
url: candidateUrl(candidate.url),
};
});
if (!Array.isArray(value.jsonld) || value.jsonld.length > 128) {
throw new TypeError('JSON-LD output is invalid');
}
return {
title: boundedString(value.title, 16 * 1024, 'title'),
canonicalCandidate: candidateUrl(value.canonical_candidate),
text: boundedString(value.text, DEFAULT_OUTPUT_BYTES, 'text'),
markdown: boundedString(value.markdown, DEFAULT_OUTPUT_BYTES, 'markdown'),
links: [...new Set(links)].sort(),
metadata,
alternateCandidates,
jsonld: jsonCopy(value.jsonld, 'JSON-LD output'),
};
}
function primitiveMatches(value, expected) {
if (expected === undefined) {
return value === null || ['string', 'number', 'boolean'].includes(typeof value);
}
if (expected === 'null') return value === null;
if (expected === 'number') return typeof value === 'number' && Number.isFinite(value);
return typeof value === expected;
}
function validateSchemaResult(value, schema) {
if (!plainObject(value) || Object.keys(value).some((name) => !Object.hasOwn(schema.fields, name))) {
throw new TypeError('schema result contains unknown fields');
}
const missing = [];
const normalized = {};
for (const [name, field] of Object.entries(schema.fields)) {
if (!Object.hasOwn(value, name)) {
if (field.required) missing.push(name);
continue;
}
const selected = value[name];
const values = field.many ? selected : [selected];
if ((field.many && !Array.isArray(selected))
|| !Array.isArray(values)
|| values.some((item) => !primitiveMatches(item, field.type))) {
missing.push(name);
continue;
}
setOwn(normalized, name, jsonCopy(selected, `schema field ${name}`));
}
return { missing: missing.sort(), value: normalized };
}
function outcome(kind, code, details = undefined) {
return deepFreeze({ kind, code, ...(details === undefined ? {} : { details }) });
}
function mapSupervisorFailure(result) {
if (Object.values(ATTEMPT_KIND).includes(result?.kind) && typeof result?.code === 'string') {
return result;
}
if (result.failure === 'spawn_failed' && result.error?.code === 'ENOENT') {
return outcome(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.UNAVAILABLE, { reason: 'python_missing' });
}
if (result.failure === 'timeout' || result.failure === 'aborted') {
return outcome(ATTEMPT_KIND.RETRYABLE, ATTEMPT_CODE.TIMEOUT, { reason: result.failure });
}
if (result.failure === 'non_zero_exit') {
return outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_CRASH, { reason: 'helper_non_zero_exit' });
}
return outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: result.failure ?? 'helper_protocol_error',
});
}
function mapHelperFailure(response) {
if (response.code === 'dependency_unavailable') {
return outcome(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.UNAVAILABLE, response.details);
}
if (response.code === 'unsupported') {
return outcome(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.UNSUPPORTED, response.details);
}
if (response.code === 'required_fields_missing') {
return outcome(ATTEMPT_KIND.INADEQUATE, ATTEMPT_CODE.PARSE_FAILED, {
reason: 'required_fields_missing',
missing: Array.isArray(response.details?.missing) ? response.details.missing : [],
});
}
if (response.code === 'parse_failed') {
return outcome(ATTEMPT_KIND.INADEQUATE, ATTEMPT_CODE.PARSE_FAILED, {
reason: response.details?.reason ?? 'parse_failed',
});
}
if (response.code === 'hash_mismatch') {
return outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.HASH_MISMATCH, {
reason: 'helper_input_hash_mismatch',
});
}
if (response.code === 'adapter_error') {
return outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'helper_boundary_failure',
});
}
return outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'helper_rejected_request',
});
}
async function readBoundedFile(path, root, maximum, expectedBytes) {
if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 1 || expectedBytes > maximum) {
throw new TypeError('helper output size is invalid');
}
const [realRoot, realPath] = await Promise.all([realpath(root), realpath(path)]);
const fromRoot = relative(realRoot, realPath);
if (fromRoot === '..' || fromRoot.startsWith('../') || isAbsolute(fromRoot)) {
throw new TypeError('helper output escaped scratch');
}
const flags = FS_CONSTANTS.O_RDONLY | (FS_CONSTANTS.O_NOFOLLOW ?? 0);
const handle = await open(realPath, flags);
try {
const info = await handle.stat();
if (!info.isFile() || info.size !== expectedBytes) throw new TypeError('helper output size mismatch');
const bytes = Buffer.allocUnsafe(expectedBytes);
let offset = 0;
while (offset < expectedBytes) {
const { bytesRead } = await handle.read(bytes, offset, expectedBytes - offset, offset);
if (bytesRead === 0) throw new TypeError('helper output ended early');
offset += bytesRead;
}
return bytes;
} finally {
await handle.close();
}
}
function profile(pythonPath, helperPath, cwd) {
return new Map([[
'python-parser',
{
command: pythonPath,
args: ['-I', helperPath],
cwd,
env: {
LANG: 'C.UTF-8',
LC_ALL: 'C.UTF-8',
PYTHONHASHSEED: '0',
PYTHONIOENCODING: 'utf-8',
PYTHONNOUSERSITE: '1',
},
maxInputBytes: 128 * 1024,
maxStdoutBytes: 64 * 1024,
maxStderrBytes: 64 * 1024,
timeoutMs: 5_000,
},
]]);
}
export function createPythonTransformAdapter({
pythonPath,
helperPath = PYTHON_HELPER_PATH,
storage,
supervisor,
runHandle = null,
scratchDir = null,
maxInputBytes,
maxOutputBytes,
} = {}) {
if (typeof pythonPath !== 'string' || !isAbsolute(pythonPath)) {
throw new TypeError('pythonPath must be an absolute path');
}
if (helperPath !== PYTHON_HELPER_PATH) {
throw new TypeError('helperPath must be the built-in Lynceuz helper');
}
if (!storage || typeof storage.readObject !== 'function' || typeof storage.resolve !== 'function'
|| typeof storage.putObject !== 'function') {
throw new TypeError('storage is required');
}
const inputLimit = positiveInteger(maxInputBytes, DEFAULT_INPUT_BYTES, 'maxInputBytes');
const outputLimit = positiveInteger(maxOutputBytes, DEFAULT_OUTPUT_BYTES, 'maxOutputBytes');
function buildSupervisor(cwd) {
return supervisor ?? createProcessSupervisor({ profiles: profile(pythonPath, helperPath, cwd) });
}
async function probe() {
try {
await realpath(helperPath);
} catch (error) {
if (error?.code === 'ENOENT') {
return { state: CAPABILITY_STATE.MISSING, reason: 'helper_missing', version: null };
}
return { state: CAPABILITY_STATE.MISCONFIGURED, reason: 'helper_unreadable', version: null };
}
const result = await buildSupervisor(dirname(helperPath)).run('python-parser', {
version: 1,
id: 'self-check',
operation: 'self_check',
});
if (result.kind !== ATTEMPT_KIND.SUCCESS) {
const mapped = mapSupervisorFailure(result);
return {
state: mapped.kind === ATTEMPT_KIND.SKIP
? CAPABILITY_STATE.MISSING
: CAPABILITY_STATE.MISCONFIGURED,
reason: mapped.details?.reason ?? mapped.code,
version: null,
};
}
if (!result.response.ok) {
const mapped = mapHelperFailure(result.response);
return {
state: mapped.kind === ATTEMPT_KIND.SKIP
? CAPABILITY_STATE.MISSING
: CAPABILITY_STATE.MISCONFIGURED,
reason: mapped.details?.reason ?? mapped.code,
version: null,
};
}
return {
state: CAPABILITY_STATE.READY,
reason: 'python_helper_ready',
version: result.response.payload?.helper_version ?? null,
details: result.response.payload ?? {},
};
}
async function runHelper({ operation, run, sourceRef, baseUrl, schema, signal }) {
let canonicalBase;
try {
canonicalBase = parsePublicUrl(baseUrl).canonicalUrl;
await storage.readObject(sourceRef, {
maxBytes: Math.min(inputLimit, sourceRef?.bytes ?? inputLimit),
});
} catch (error) {
return {
outcome: outcome(ATTEMPT_KIND.BROKEN,
error?.code === 'INTEGRITY_MISMATCH'
? ATTEMPT_CODE.HASH_MISMATCH
: ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR,
{ reason: 'stored_input_invalid' }),
};
}
const activeRun = run ?? runHandle;
if (!activeRun?.id) {
return {
outcome: outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'run_missing',
}),
};
}
let inputPath;
let scratchRoot;
try {
await realpath(helperPath);
inputPath = await storage.resolve(sourceRef.path);
scratchRoot = scratchDir ?? await storage.resolve(`tmp/${activeRun.id}`);
await mkdir(scratchRoot, { recursive: true });
} catch (error) {
return {
outcome: error?.code === 'ENOENT'
? outcome(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.UNAVAILABLE, { reason: 'helper_missing' })
: outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'path_setup_failed',
}),
};
}
const outputPath = join(scratchRoot, `${operation}-${randomUUID()}.json`);
const runner = buildSupervisor(scratchRoot);
const result = await runner.run('python-parser', {
request: {
version: 1,
id: `${operation}-${randomUUID()}`,
operation,
input_path: inputPath,
input_hash: sourceRef.hash,
base_url: canonicalBase,
output_path: outputPath,
...(schema === undefined ? {} : { schema }),
},
scratchDir: scratchRoot,
signal,
inputRoot: storage.dataRoot,
scratchRoot,
});
if (result.kind !== ATTEMPT_KIND.SUCCESS) return { outcome: mapSupervisorFailure(result), outputPath, scratchRoot };
if (!result.response.ok) return { outcome: mapHelperFailure(result.response), outputPath, scratchRoot };
if (result.response.payload?.output_path !== outputPath) {
return {
outcome: outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'helper_output_path_mismatch',
}),
outputPath,
scratchRoot,
};
}
try {
const bytes = await readBoundedFile(
outputPath,
scratchRoot,
outputLimit,
result.response.payload?.bytes,
);
return { bytes, outputPath, scratchRoot };
} catch {
return {
outcome: outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'invalid_helper_output',
}),
outputPath,
scratchRoot,
};
}
}
async function parseHtml({ run, sourceRef, input, baseUrl, signal } = {}) {
const reference = sourceRef ?? input;
const execution = await runHelper({
operation: 'parse_html',
run,
sourceRef: reference,
baseUrl,
signal,
});
try {
if (execution.outcome) return execution.outcome;
const parsed = validateParseResult(JSON.parse(execution.bytes));
const activeRun = run ?? runHandle;
const artifacts = {
markdown: await storage.putObject(activeRun, Buffer.from(parsed.markdown), {
role: 'derived', media_type: 'text/markdown; charset=utf-8', derived_from: reference.hash,
}),
text: await storage.putObject(activeRun, Buffer.from(parsed.text), {
role: 'derived', media_type: 'text/plain; charset=utf-8', derived_from: reference.hash,
}),
metadata: await storage.putObject(activeRun, stableBytes(parsed.metadata), {
role: 'derived', media_type: 'application/json', derived_from: reference.hash,
}),
links: await storage.putObject(activeRun, stableBytes(parsed.links), {
role: 'derived', media_type: 'application/json', derived_from: reference.hash,
}),
jsonld: await storage.putObject(activeRun, stableBytes(parsed.jsonld), {
role: 'derived', media_type: 'application/json', derived_from: reference.hash,
}),
};
return deepFreeze({
kind: ATTEMPT_KIND.SUCCESS,
code: ATTEMPT_CODE.OK,
value: { ...parsed, artifacts },
});
} catch {
return outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'invalid_parse_result',
});
} finally {
if (execution.outputPath) await rm(execution.outputPath, { force: true }).catch(() => {});
}
}
async function extractSchema({ run, sourceRef, input, baseUrl, schema, signal } = {}) {
let normalizedSchema;
try {
normalizedSchema = validateExtractSchema(schema);
} catch {
return outcome(ATTEMPT_KIND.INADEQUATE, ATTEMPT_CODE.PARSE_FAILED, {
reason: 'invalid_schema',
});
}
const reference = sourceRef ?? input;
const execution = await runHelper({
operation: 'extract_schema',
run,
sourceRef: reference,
baseUrl,
schema: normalizedSchema,
signal,
});
try {
if (execution.outcome) return execution.outcome;
const checked = validateSchemaResult(JSON.parse(execution.bytes), normalizedSchema);
if (checked.missing.length > 0) {
return outcome(ATTEMPT_KIND.INADEQUATE, ATTEMPT_CODE.PARSE_FAILED, {
reason: 'required_fields_missing',
missing: checked.missing,
});
}
const bytes = stableBytes(checked.value);
if (bytes.length > outputLimit) {
return outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'schema_output_too_large',
});
}
const activeRun = run ?? runHandle;
const artifact = await storage.putObject(activeRun, bytes, {
role: 'derived',
media_type: 'application/json',
derived_from: reference.hash,
transform: {
id: 'python-schema-v1',
version: '1',
options_hash: sha256(stableBytes(normalizedSchema)),
},
});
return deepFreeze({
kind: ATTEMPT_KIND.SUCCESS,
code: ATTEMPT_CODE.OK,
value: { artifact, data: checked.value },
});
} catch {
return outcome(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, {
reason: 'invalid_schema_result',
});
} finally {
if (execution.outputPath) await rm(execution.outputPath, { force: true }).catch(() => {});
}
}
async function transform({ operation, ...input } = {}) {
if (operation === 'parse_html') {
const result = await parseHtml(input);
if (result.kind !== ATTEMPT_KIND.SUCCESS) return result;
return deepFreeze({
kind: result.kind,
code: result.code,
artifact: result.value.artifacts.metadata,
representation: result.value,
});
}
if (operation === 'extract_schema') {
const result = await extractSchema(input);
if (result.kind !== ATTEMPT_KIND.SUCCESS) return result;
return deepFreeze({
kind: result.kind,
code: result.code,
artifact: result.value.artifact,
representation: result.value.data,
});
}
return outcome(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.UNSUPPORTED, { reason: operation ?? null });
}
async function health() {
const state = await probe();
return deepFreeze({
id: 'python-parser',
state: state.state,
reason: state.reason,
version: state.version,
networkModel: 'none',
details: state.details ?? {},
});
}
return Object.freeze({
id: 'python-parser',
version: '1',
networkModel: 'none',
deterministic: true,
probe,
health,
parseHtml,
extractSchema,
transform,
});
}
+647
View File
@@ -0,0 +1,647 @@
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { once } from 'node:events';
import { createServer } from 'node:http';
import { access, lstat, readFile, realpath } from 'node:fs/promises';
import { arch, platform } from 'node:os';
import { basename, isAbsolute, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { CAPABILITY_STATE, deepFreeze } from './contracts.mjs';
import { verifyMacosContainmentReceipt } from './macos-containment.mjs';
const LOOPBACK = '127.0.0.1';
const MAX_HEADER_BYTES = 16 * 1024;
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
const MAX_TUNNELS = 8;
const DEADLINE_MS = 15_000;
const MAX_PROOF_BYTES = 128 * 1024;
const MAX_PROOF_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
const HOSTILE_CHANNELS = Object.freeze([
'navigation', 'redirect', 'iframe', 'popup', 'worker', 'service_worker',
'websocket', 'webrtc_udp', 'webtransport', 'quic',
]);
const CONTAINMENT_CHANNELS = Object.freeze(['TCP', 'UDP', 'QUIC']);
const REQUIRED_CHANNELS = Object.freeze([...HOSTILE_CHANNELS, ...CONTAINMENT_CHANNELS]);
const HOSTILE_SUITES = Object.freeze([
'evals/browser-hostile.test.mjs',
'evals/router.test.mjs',
'evals/p0-acceptance.test.mjs',
]);
const REQUIRED_SUITES = Object.freeze([
...HOSTILE_SUITES,
'evals/browser-containment.test.mjs',
]);
const SHA256 = /^sha256:[0-9a-f]{64}$/u;
const LEGACY_PASSED_PROOF_KEYS = Object.freeze([
'arch', 'channels', 'fingerprint', 'generated_at', 'kind', 'marker_hash',
'platform', 'reason', 'runtime', 'schema_version', 'source_hashes', 'status', 'suites',
]);
const PASSED_PROOF_KEYS = Object.freeze([
...LEGACY_PASSED_PROOF_KEYS, 'containment', 'containment_state',
]);
const CONTAINMENT_KEYS = Object.freeze([
'anchor', 'backend', 'boot_session', 'guard_proxy', 'negative_control_required',
'reboot_verified', 'reboot_verified_at', 'source_hashes', 'system_receipt_hash', 'uid',
'wave2_suite_hash',
]);
const SAFE_RESPONSE_HEADERS = new Set([
'cache-control', 'content-encoding', 'content-language', 'content-length',
'content-type', 'etag', 'last-modified',
]);
const SAFE_REQUEST_HEADERS = new Set([
'accept', 'accept-encoding', 'if-modified-since', 'if-none-match', 'user-agent',
]);
const SOURCE_PATHS = Object.freeze({
guard_proxy: fileURLToPath(new URL('./browser-security.mjs', import.meta.url)),
network: fileURLToPath(new URL('./network.mjs', import.meta.url)),
adapter: fileURLToPath(new URL('./adapters/playwright.mjs', import.meta.url)),
helper: fileURLToPath(new URL('./lynceuz-browser.py', import.meta.url)),
cli: fileURLToPath(new URL('./cli.mjs', import.meta.url)),
core: fileURLToPath(new URL('./core.mjs', import.meta.url)),
router: fileURLToPath(new URL('./router.mjs', import.meta.url)),
gate: fileURLToPath(new URL('../scripts/p1-browser-gate.mjs', import.meta.url)),
hostile_suite: fileURLToPath(new URL('../evals/browser-hostile.test.mjs', import.meta.url)),
router_suite: fileURLToPath(new URL('../evals/router.test.mjs', import.meta.url)),
p0_suite: fileURLToPath(new URL('../evals/p0-acceptance.test.mjs', import.meta.url)),
direct_probe: fileURLToPath(new URL('../evals/fixtures/direct-egress-probe.py', import.meta.url)),
macos_containment: fileURLToPath(new URL('./macos-containment.mjs', import.meta.url)),
containment_canary: fileURLToPath(new URL('../evals/fixtures/pf-containment-canary.mjs', import.meta.url)),
wave2_manifest: fileURLToPath(new URL('../evals/fixtures/wave2-suite-manifest.json', import.meta.url)),
});
function frozen(value) {
return deepFreeze(value);
}
function sha256(value) {
return `sha256:${createHash('sha256').update(value).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);
}
function proofIntegrityPayload(proof) {
const payload = {
kind: proof.kind,
schema_version: proof.schema_version,
status: proof.status,
reason: proof.reason,
fingerprint: proof.fingerprint,
generated_at: proof.generated_at,
platform: proof.platform,
arch: proof.arch,
runtime: proof.runtime,
source_hashes: proof.source_hashes,
channels: proof.channels,
suites: proof.suites,
};
if (Object.hasOwn(proof, 'containment')) payload.containment = proof.containment;
if (Object.hasOwn(proof, 'containment_state')) payload.containment_state = proof.containment_state;
return payload;
}
export function createBrowserProofIntegrity(proof) {
if (!proof || typeof proof !== 'object' || Array.isArray(proof)) {
throw new TypeError('browser proof is invalid');
}
return sha256(stableJson(proofIntegrityPayload(proof)));
}
function equalToken(actual, expected) {
if (typeof actual !== 'string') return false;
const left = Buffer.from(actual);
const right = Buffer.from(expected);
return left.length === right.length && timingSafeEqual(left, right);
}
function plainObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function exactKeys(value, keys) {
return plainObject(value)
&& stableJson(Object.keys(value).sort()) === stableJson([...keys].sort());
}
function validContainmentEvidence(value) {
return exactKeys(value, CONTAINMENT_KEYS)
&& value.backend === 'pf_uid_anchor_guardproxy'
&& SHA256.test(value.system_receipt_hash)
&& exactKeys(value.uid, ['gid', 'name', 'uid'])
&& typeof value.uid.name === 'string' && value.uid.name.length > 0
&& Number.isSafeInteger(value.uid.uid) && value.uid.uid > 0
&& Number.isSafeInteger(value.uid.gid) && value.uid.gid > 0
&& exactKeys(value.guard_proxy, ['host', 'port'])
&& value.guard_proxy.host === LOOPBACK
&& Number.isSafeInteger(value.guard_proxy.port)
&& value.guard_proxy.port > 0 && value.guard_proxy.port <= 65_535
&& exactKeys(value.anchor, ['anchor_name', 'anchor_path', 'anchor_sha256', 'rules_sha256'])
&& typeof value.anchor.anchor_name === 'string' && value.anchor.anchor_name.length > 0
&& typeof value.anchor.anchor_path === 'string' && isAbsolute(value.anchor.anchor_path)
&& SHA256.test(value.anchor.anchor_sha256) && SHA256.test(value.anchor.rules_sha256)
&& typeof value.boot_session === 'string' && value.boot_session.length > 0
&& value.reboot_verified === true
&& Number.isFinite(Date.parse(value.reboot_verified_at))
&& plainObject(value.source_hashes) && Object.keys(value.source_hashes).length > 0
&& Object.values(value.source_hashes).every((hash) => SHA256.test(hash))
&& SHA256.test(value.wave2_suite_hash)
&& value.negative_control_required === true;
}
function proxyToken(headers) {
const value = headers['proxy-authorization'];
if (typeof value !== 'string' || value.length > 512) return null;
if (value.startsWith('Bearer ')) return value.slice(7);
if (!value.startsWith('Basic ')) return null;
let decoded;
try { decoded = Buffer.from(value.slice(6), 'base64').toString('utf8'); } catch { return null; }
const separator = decoded.indexOf(':');
return separator === -1 ? null : decoded.slice(separator + 1);
}
function safeHeaders(headers) {
const result = {};
for (const [name, raw] of Object.entries(headers ?? {})) {
const lower = name.toLowerCase();
const value = Array.isArray(raw) ? raw[0] : raw;
if (SAFE_REQUEST_HEADERS.has(lower) && typeof value === 'string'
&& Buffer.byteLength(value) <= 8 * 1024 && !/[\r\n\0]/u.test(value)) {
result[lower] = value;
}
}
return result;
}
function responseHeaders(headers) {
const result = {};
let total = 0;
for (const [name, raw] of Object.entries(headers ?? {})) {
const lower = name.toLowerCase();
const value = Array.isArray(raw) ? raw.join(', ') : String(raw);
const bytes = Buffer.byteLength(name) + Buffer.byteLength(value) + 4;
if (SAFE_RESPONSE_HEADERS.has(lower) && bytes <= 8 * 1024 && total + bytes <= MAX_HEADER_BYTES
&& !/[\r\n\0]/u.test(value)) {
result[name] = value;
total += bytes;
}
}
return result;
}
function writeProxyError(socket, status, message) {
if (!socket || socket.destroyed) return;
const body = `${message}\n`;
socket.end(
`HTTP/1.1 ${status}\r\nContent-Type: text/plain; charset=utf-8\r\n`
+ `Content-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`,
);
}
function parseConnectAuthority(value) {
if (typeof value !== 'string' || value.length === 0 || value.length > 512
|| /[\s\0]/u.test(value)) return null;
try {
const url = new URL(`https://${value}/`);
if (url.username || url.password || Number(url.port || 443) !== 443) return null;
return url;
} catch {
return null;
}
}
export async function createGuardProxy({
gateway,
token = randomBytes(32).toString('base64url'),
limits = {},
} = {}) {
if (!gateway || typeof gateway.execute !== 'function'
|| typeof gateway.openAuthorizedTunnel !== 'function') {
throw new TypeError('GuardProxy requires the EgressGateway');
}
if (typeof token !== 'string' || token.length < 32 || token.length > 256) {
throw new TypeError('GuardProxy token is invalid');
}
const maxBytes = Number.isSafeInteger(limits.maxBytes) && limits.maxBytes > 0
? Math.min(limits.maxBytes, MAX_RESPONSE_BYTES)
: MAX_RESPONSE_BYTES;
const deadlineMs = Number.isSafeInteger(limits.deadlineMs) && limits.deadlineMs > 0
? Math.min(limits.deadlineMs, DEADLINE_MS)
: DEADLINE_MS;
const sockets = new Set();
const stats = { authorizedRequests: 0, deniedRequests: 0, openedTunnels: 0, bytes: 0 };
let activeTunnels = 0;
let closed = false;
const server = createServer({ maxHeaderSize: MAX_HEADER_BYTES }, async (request, response) => {
const supplied = proxyToken(request.headers);
if (!equalToken(supplied, token)) {
stats.deniedRequests += 1;
response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Lynceuz"', Connection: 'close' });
response.end();
return;
}
if (!['GET', 'HEAD'].includes(request.method)
|| typeof request.url !== 'string' || !/^https?:\/\//u.test(request.url)
|| request.headers['content-length'] !== undefined || request.headers['transfer-encoding'] !== undefined) {
response.writeHead(405, { Connection: 'close' });
response.end();
return;
}
let target;
try {
target = new URL(request.url);
if (target.username || target.password) throw new Error('credentials');
} catch {
response.writeHead(400, { Connection: 'close' });
response.end();
return;
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(new Error('GuardProxy deadline')), deadlineMs);
timer.unref?.();
try {
const upstream = await gateway.execute({
runId: 'browser-guard-proxy',
purpose: 'subresource',
url: target.href,
method: request.method,
headers: safeHeaders(request.headers),
remaining: { wallMs: deadlineMs, bytes: maxBytes, redirects: 5 },
}, { signal: controller.signal });
stats.authorizedRequests += 1;
response.writeHead(upstream.statusCode, responseHeaders(upstream.headers));
let consumed = 0;
const abortBody = () => {
upstream.body.destroy?.(controller.signal.reason ?? new Error('GuardProxy aborted'));
response.destroy();
};
controller.signal.addEventListener('abort', abortBody, { once: true });
upstream.body.on('data', (chunk) => {
consumed += Buffer.byteLength(chunk);
stats.bytes += Buffer.byteLength(chunk);
if (consumed > maxBytes) {
controller.abort(new Error('GuardProxy byte limit'));
upstream.body.destroy?.();
response.destroy();
}
});
upstream.body.once('error', () => response.destroy());
upstream.body.pipe(response);
await Promise.race([once(response, 'finish'), once(response, 'close')]);
controller.signal.removeEventListener('abort', abortBody);
} catch {
if (!response.headersSent) response.writeHead(502, { Connection: 'close' });
response.end();
} finally {
clearTimeout(timer);
}
});
server.headersTimeout = deadlineMs;
server.requestTimeout = deadlineMs;
server.on('connection', (socket) => {
sockets.add(socket);
socket.once('close', () => sockets.delete(socket));
});
server.on('connect', async (request, client, head) => {
if (!equalToken(proxyToken(request.headers), token)) {
stats.deniedRequests += 1;
writeProxyError(client, '407 Proxy Authentication Required', 'proxy authentication required');
return;
}
const target = parseConnectAuthority(request.url);
if (!target || head.length > 0 || activeTunnels >= MAX_TUNNELS) {
writeProxyError(client, '400 Bad Request', 'invalid tunnel request');
return;
}
activeTunnels += 1;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(new Error('GuardProxy tunnel deadline')), deadlineMs);
timer.unref?.();
try {
const opened = await gateway.openAuthorizedTunnel({
runId: 'browser-guard-proxy',
purpose: 'subresource',
url: target.href,
method: 'GET',
headers: {},
remaining: { wallMs: deadlineMs, bytes: maxBytes, redirects: 0 },
}, { signal: controller.signal });
stats.authorizedRequests += 1;
stats.openedTunnels += 1;
const abortTunnel = () => {
client.destroy(controller.signal.reason);
opened.socket.destroy(controller.signal.reason);
};
controller.signal.addEventListener('abort', abortTunnel, { once: true });
let consumed = 0;
const account = (chunk) => {
consumed += Buffer.byteLength(chunk);
stats.bytes += Buffer.byteLength(chunk);
if (consumed > maxBytes) {
client.destroy();
opened.socket.destroy();
}
};
client.on('data', account);
opened.socket.on('data', account);
client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
opened.socket.once('error', () => client.destroy());
client.once('error', () => opened.socket.destroy());
client.pipe(opened.socket);
opened.socket.pipe(client);
await Promise.race([once(client, 'close'), once(opened.socket, 'close')]);
controller.signal.removeEventListener('abort', abortTunnel);
client.destroy();
opened.socket.destroy();
} catch {
writeProxyError(client, '502 Bad Gateway', 'tunnel unavailable');
} finally {
clearTimeout(timer);
activeTunnels -= 1;
}
});
server.listen(0, LOOPBACK);
await once(server, 'listening');
const address = server.address();
if (!address || typeof address === 'string' || address.address !== LOOPBACK) {
server.close();
throw new Error('GuardProxy did not bind IPv4 loopback');
}
return Object.freeze({
host: LOOPBACK,
port: address.port,
token,
stats,
async close() {
if (closed) return;
closed = true;
for (const socket of sockets) socket.destroy();
const closedEvent = server.listening ? once(server, 'close') : Promise.resolve();
server.close();
await closedEvent;
},
});
}
function sandboxProfile(proxyPort) {
return `(version 1)\n(allow default)\n(deny network-outbound)\n(allow network-outbound (remote tcp "localhost:${proxyPort}"))\n`;
}
export async function createChildEgressSandbox({
proxyPort,
platformName = platform(),
sandboxPath = '/usr/bin/sandbox-exec',
probeScript,
} = {}) {
if (!Number.isInteger(proxyPort) || proxyPort < 1 || proxyPort > 65535) {
throw new TypeError('sandbox proxy port is invalid');
}
if (probeScript !== undefined && (typeof probeScript !== 'string' || !isAbsolute(probeScript))) {
throw new TypeError('sandbox probe path is invalid');
}
const profile = sandboxProfile(proxyPort);
const base = {
state: CAPABILITY_STATE.UNAVAILABLE_SECURITY_GATE,
proofEligible: false,
profileHash: sha256(profile),
executable: sandboxPath,
};
if (platformName !== 'darwin') {
return frozen({ ...base, reason: 'sandbox_platform_unsupported' });
}
try {
await access(sandboxPath);
} catch {
return frozen({ ...base, reason: 'sandbox_executable_missing' });
}
// sandbox-exec accepts only `localhost`, not a numeric loopback address. On current Darwin,
// that selector also matches the host's non-loopback addresses, so lo0-only egress cannot
// be proven even when the direct TCP/UDP canaries pass. Keep the launcher unavailable.
return frozen({ ...base, reason: 'sandbox_loopback_scope_unproven' });
}
export async function createPfContainmentBackend({
receipt,
expected,
system,
runner,
canary,
now,
pythonPath,
helperPath = fileURLToPath(new URL('./lynceuz-browser.py', import.meta.url)),
} = {}) {
const fallback = {
state: CAPABILITY_STATE.UNAVAILABLE_SECURITY_GATE,
proofEligible: false,
reason: receipt == null ? 'sandbox_loopback_scope_unproven' : 'containment_receipt_invalid',
};
if (receipt == null) return frozen(fallback);
const verification = await verifyMacosContainmentReceipt({
receipt, expected, system, runner, canary, ...(now ? { now } : {}),
});
if (verification.state !== CAPABILITY_STATE.READY) {
return frozen({ ...fallback, reason: verification.reason });
}
if (typeof pythonPath !== 'string' || !isAbsolute(pythonPath)
|| typeof helperPath !== 'string' || !isAbsolute(helperPath)) {
return frozen({ ...fallback, reason: 'containment_launch_unavailable' });
}
try {
await Promise.all([access(pythonPath), access(helperPath), access('/usr/bin/sudo')]);
} catch {
return frozen({ ...fallback, reason: 'containment_launch_unavailable' });
}
const launchPlan = frozen({
kind: 'lynceuz_macos_containment_launch_plan',
executable: '/usr/bin/sudo',
argv: ['-n', '-u', `#${receipt.uid.uid}`, '--', pythonPath, '-I', helperPath],
uid: receipt.uid.uid,
gid: receipt.uid.gid,
guard_proxy: { host: receipt.guard_proxy.host, port: receipt.guard_proxy.port },
env: { LANG: 'C.UTF-8', LC_ALL: 'C.UTF-8', PYTHONNOUSERSITE: '1' },
shell: false,
});
return frozen({
state: CAPABILITY_STATE.READY,
proofEligible: true,
reason: 'containment_ready',
backend: 'pf_uid_anchor_guardproxy',
launch: () => launchPlan,
});
}
export async function computeBrowserFingerprint({
sourcePaths = SOURCE_PATHS,
runtime,
fingerprintRuntime,
containment,
} = {}) {
if (!sourcePaths || typeof sourcePaths !== 'object' || Array.isArray(sourcePaths)) {
throw new TypeError('fingerprint source paths are invalid');
}
const resolvedRuntime = runtime ?? fingerprintRuntime ?? {
platform: platform(),
arch: arch(),
node: process.version,
python: 'unprobed',
playwright: 'unprobed',
chromium: 'unprobed',
containment: '/usr/bin/sandbox-exec',
profile: 'sandbox_loopback_scope_unproven',
};
const sources = {};
for (const name of Object.keys(sourcePaths).sort()) {
const path = sourcePaths[name];
if (typeof path !== 'string' || path.length === 0) throw new TypeError('fingerprint path is invalid');
let bytes;
try { bytes = await readFile(path); } catch { bytes = Buffer.from('missing'); }
sources[name] = { path: basename(path), hash: sha256(bytes) };
}
if (containment !== undefined && !validContainmentEvidence(containment)) {
throw new TypeError('fingerprint containment evidence is invalid');
}
const payload = {
schema_version: containment === undefined && sourcePaths !== SOURCE_PATHS ? 1 : 2,
runtime: resolvedRuntime,
sources,
...(containment === undefined ? {} : { containment }),
};
return frozen({ ...payload, digest: sha256(stableJson(payload)) });
}
export async function verifyBrowserSecurityProof({
dataRoot,
fingerprint,
now = Date.now,
maxAgeMs = MAX_PROOF_AGE_MS,
} = {}) {
if (typeof dataRoot !== 'string' || basename(resolve(dataRoot)) !== '.lynceuz'
|| !fingerprint || typeof fingerprint.digest !== 'string') {
return frozen({ valid: false, reason: 'proof_input_invalid', fingerprint: null });
}
const proofPath = join(resolve(dataRoot), 'security/browser-proof-v1.json');
let bytes;
try {
const info = await lstat(proofPath);
if (!info.isFile() || info.isSymbolicLink() || info.size > MAX_PROOF_BYTES) {
return frozen({ valid: false, reason: 'proof_corrupt', fingerprint: null });
}
const root = await realpath(resolve(dataRoot));
const file = await realpath(proofPath);
if (!file.startsWith(`${root}/`)) return frozen({ valid: false, reason: 'proof_corrupt', fingerprint: null });
bytes = await readFile(file);
} catch {
return frozen({ valid: false, reason: 'proof_missing', fingerprint: null });
}
let proof;
try { proof = JSON.parse(bytes); } catch {
return frozen({ valid: false, reason: 'proof_corrupt', fingerprint: null });
}
if (proof && typeof proof === 'object' && !Array.isArray(proof)
&& typeof proof.fingerprint === 'string'
&& proof.fingerprint !== fingerprint.digest) {
return frozen({ valid: false, reason: 'fingerprint_mismatch', fingerprint: proof.fingerprint });
}
const proofKeys = proof && typeof proof === 'object' && !Array.isArray(proof)
? Object.keys(proof).sort()
: [];
const channelKeys = proof?.channels && typeof proof.channels === 'object'
&& !Array.isArray(proof.channels) ? Object.keys(proof.channels).sort() : [];
const containmentBound = fingerprint.schema_version === 2;
const expectedProofKeys = containmentBound ? PASSED_PROOF_KEYS : LEGACY_PASSED_PROOF_KEYS;
const expectedChannels = containmentBound ? REQUIRED_CHANNELS : HOSTILE_CHANNELS;
const expectedSuites = containmentBound ? REQUIRED_SUITES : HOSTILE_SUITES;
const sourceMatch = stableJson(proof?.source_hashes) === stableJson(fingerprint.sources);
const runtimeMatch = stableJson(proof?.runtime) === stableJson(fingerprint.runtime);
const containmentMatch = !containmentBound
|| (validContainmentEvidence(fingerprint.containment)
&& proof?.containment_state === CAPABILITY_STATE.READY
&& validContainmentEvidence(proof?.containment)
&& stableJson(proof.containment) === stableJson(fingerprint.containment));
const suites = Array.isArray(proof?.suites) ? proof.suites : [];
const suiteNames = suites.map((suite) => suite?.suite);
const validSuites = suites.length === expectedSuites.length
&& new Set(suiteNames).size === expectedSuites.length
&& expectedSuites.every((suite) => suiteNames.includes(suite))
&& suites.every((suite) => {
const keys = suite && typeof suite === 'object' && !Array.isArray(suite)
? Object.keys(suite).sort()
: [];
return stableJson(keys) === stableJson([
'duration_ms', 'exit_code', 'passed', 'signal', 'skipped', 'stderr_hash',
'stdout_hash', 'suite',
])
&& suite.passed === true && suite.skipped === false
&& suite.exit_code === 0 && suite.signal === null
&& Number.isSafeInteger(suite.duration_ms) && suite.duration_ms >= 0
&& SHA256.test(suite.stdout_hash) && SHA256.test(suite.stderr_hash);
});
let markerMatches = false;
try {
markerMatches = SHA256.test(proof?.marker_hash)
&& proof.marker_hash === createBrowserProofIntegrity(proof);
} catch {}
if (!proof || stableJson(proofKeys) !== stableJson([...expectedProofKeys].sort())
|| proof.kind !== 'browser_security_proof' || proof.schema_version !== 1
|| proof.status !== 'passed' || proof.reason !== 'proof_valid'
|| proof.platform !== fingerprint.runtime?.platform || proof.arch !== fingerprint.runtime?.arch
|| !runtimeMatch || !sourceMatch || !containmentMatch || !validSuites || !markerMatches
|| stableJson(channelKeys) !== stableJson([...expectedChannels].sort())
|| expectedChannels.some((channel) => proof.channels[channel] !== true)) {
return frozen({ valid: false, reason: 'proof_failed_or_incomplete', fingerprint: null });
}
const generated = typeof proof.generated_at === 'string' ? Date.parse(proof.generated_at) : Number.NaN;
const current = Number(now());
if (!Number.isFinite(generated) || !Number.isFinite(current)
|| generated > current + 5 * 60_000 || current - generated > maxAgeMs) {
return frozen({ valid: false, reason: 'proof_stale', fingerprint: proof.fingerprint });
}
return frozen({ valid: true, reason: 'proof_valid', fingerprint: proof.fingerprint, proof });
}
export function browserCapabilityState({ id, installed, version, allowRendered, proof } = {}) {
if (typeof id !== 'string' || !id) throw new TypeError('browser capability id is required');
const common = { id, version: typeof version === 'string' ? version : null };
if (!installed) return frozen({ ...common, state: CAPABILITY_STATE.MISSING, reason: 'engine_missing' });
if (id !== 'playwright') {
return frozen({ ...common, state: CAPABILITY_STATE.UNAVAILABLE_SECURITY_GATE, reason: 'independent_security_proof_missing' });
}
if (!proof?.valid) {
return frozen({
...common,
state: CAPABILITY_STATE.UNAVAILABLE_SECURITY_GATE,
reason: proof?.reason ?? 'proof_missing',
proofFingerprint: proof?.fingerprint ?? null,
});
}
if (allowRendered !== true) {
return frozen({
...common,
state: CAPABILITY_STATE.DISABLED,
reason: 'rendered_not_allowed',
proofFingerprint: proof.fingerprint,
enable_with: '--allow-rendered',
});
}
return frozen({
...common,
state: CAPABILITY_STATE.READY,
reason: 'browser_security_proof_valid',
proofFingerprint: proof.fingerprint,
});
}
export {
HOSTILE_CHANNELS as REQUIRED_BROWSER_PROOF_CHANNELS,
REQUIRED_CHANNELS as REQUIRED_CONTAINMENT_PROOF_CHANNELS,
};
+466
View File
@@ -0,0 +1,466 @@
import {
EXIT_CODE,
RUN_STATUS,
createResultEnvelope,
deepFreeze,
exitCodeForStatus,
validateResultEnvelope,
} from './contracts.mjs';
const COMMANDS = new Set(['url', 'crawl', 'extract', 'search', 'health']);
const ENGINE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
const FORMATS = new Set(['raw', 'markdown', 'metadata', 'links', 'json']);
const CACHE_MODES = new Set(['use', 'refresh', 'off']);
const DISCOVERY_SOURCES = new Set(['alternate', 'api', 'atom', 'html', 'rss', 'sitemap']);
const DEFAULT_TTL_MS = 3_600_000;
const MAX_TTL_MS = 8_000_000_000_000_000;
const MAX_QUERY_LENGTH = 100_000;
const MAX_SCRAPE_RESULTS = 100;
const DEFAULT_SEARCH = Object.freeze({ limit: 10, scrapeResults: 0 });
const DEFAULT_LIMITS = Object.freeze({
wallMs: 60_000,
perAttemptMs: 15_000,
maxBytesPerPage: 5 * 1024 * 1024,
maxTotalBytes: 50 * 1024 * 1024,
maxPages: 100,
maxDepth: 3,
concurrency: 2,
maxRedirects: 5,
retriesPerAdapter: 2,
maxRetryAfterMs: 15_000,
maxFrontier: 1_000,
delayMs: 250,
maxArtifactBytes: 5 * 1024 * 1024,
});
class CliInputError extends Error {
constructor() {
super('invalid input');
this.name = 'CliInputError';
}
}
function invalid() {
throw new CliInputError();
}
function takeValue(argv, index) {
const value = argv[index + 1];
if (value === undefined || value.startsWith('--')) invalid();
return value;
}
function isSafeOutputPath(value) {
if (typeof value !== 'string' || value.length === 0 || value.length > 4096
|| value !== value.trim() || /[\u0000-\u001f\u007f\\]/u.test(value)
|| value.startsWith('/') || /^[a-z]:/iu.test(value)) {
return false;
}
const parts = value.split('/');
return parts.every((part) => part !== '' && part !== '.' && part !== '..');
}
function isDataRoot(value) {
if (typeof value !== 'string' || value.length === 0 || value.length > 4096
|| value !== value.trim() || /[\u0000-\u001f\u007f]/u.test(value)) {
return false;
}
const withoutTrailingSeparators = value.replace(/[\\/]+$/u, '');
if (withoutTrailingSeparators === '') return false;
return withoutTrailingSeparators.split(/[\\/]/u).at(-1) === '.lynceuz';
}
function ttlMilliseconds(value) {
if (value === null) return DEFAULT_TTL_MS;
if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/u.test(value)) invalid();
const milliseconds = Number(value) * 1_000;
if (!Number.isFinite(milliseconds) || milliseconds <= 0 || milliseconds > MAX_TTL_MS) {
invalid();
}
return milliseconds;
}
function positiveNumber(value, { integer = false, scale = 1, max = Infinity } = {}) {
if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/u.test(value)) invalid();
const number = Number(value) * scale;
if (!Number.isFinite(number) || number <= 0 || number > max
|| (integer && !Number.isSafeInteger(number))) invalid();
return number;
}
function safePathGlob(value) {
if (typeof value !== 'string' || value.length === 0 || value.length > 512
|| !value.startsWith('/') || /[\0-\x1f\x7f\\?\[\]{}]/u.test(value)
|| value.split('/').some((part) => part === '..')
|| !/^\/[A-Za-z0-9._~!$&'()+,;=:@%/*-]*$/u.test(value)) {
invalid();
}
return value;
}
function discoverySources(value) {
const sources = value.split(',');
if (sources.length === 0 || sources.some((source) => !DISCOVERY_SOURCES.has(source))) invalid();
return [...new Set(sources)].sort();
}
export function parseArgv(argv) {
if (!Array.isArray(argv) || argv.some((item) => typeof item !== 'string')) invalid();
const positional = [];
const flags = {
json: false,
explain: false,
engine: null,
schema: null,
format: null,
output: null,
dataRoot: null,
cache: null,
ttl: null,
include: [],
exclude: [],
discover: null,
preferDiscoveredSource: false,
maxPages: null,
maxDepth: null,
maxTime: null,
maxBytes: null,
maxFrontier: null,
concurrency: null,
delay: null,
maxRedirects: null,
retries: null,
allowRendered: false,
limit: null,
scrapeResults: null,
allowFreeCloud: false,
};
const seen = new Set();
for (let index = 0; index < argv.length; index += 1) {
const token = argv[index];
if (!token.startsWith('--')) {
positional.push(token);
continue;
}
const repeatable = token === '--include' || token === '--exclude';
if (!repeatable && seen.has(token)) invalid();
if (!repeatable) seen.add(token);
switch (token) {
case '--json': flags.json = true; break;
case '--explain': flags.explain = true; break;
case '--engine':
flags.engine = takeValue(argv, index);
index += 1;
break;
case '--schema':
flags.schema = takeValue(argv, index);
index += 1;
break;
case '--format':
flags.format = takeValue(argv, index);
index += 1;
break;
case '--output':
flags.output = takeValue(argv, index);
index += 1;
break;
case '--data-root':
flags.dataRoot = takeValue(argv, index);
index += 1;
break;
case '--cache':
flags.cache = takeValue(argv, index);
index += 1;
break;
case '--ttl':
flags.ttl = takeValue(argv, index);
index += 1;
break;
case '--include':
flags.include.push(takeValue(argv, index));
index += 1;
break;
case '--exclude':
flags.exclude.push(takeValue(argv, index));
index += 1;
break;
case '--discover':
flags.discover = takeValue(argv, index);
index += 1;
break;
case '--prefer-discovered-source': flags.preferDiscoveredSource = true; break;
case '--max-pages': flags.maxPages = takeValue(argv, index); index += 1; break;
case '--max-depth': flags.maxDepth = takeValue(argv, index); index += 1; break;
case '--max-time': flags.maxTime = takeValue(argv, index); index += 1; break;
case '--max-bytes': flags.maxBytes = takeValue(argv, index); index += 1; break;
case '--max-frontier': flags.maxFrontier = takeValue(argv, index); index += 1; break;
case '--concurrency': flags.concurrency = takeValue(argv, index); index += 1; break;
case '--delay': flags.delay = takeValue(argv, index); index += 1; break;
case '--max-redirects': flags.maxRedirects = takeValue(argv, index); index += 1; break;
case '--retries': flags.retries = takeValue(argv, index); index += 1; break;
case '--allow-rendered': flags.allowRendered = true; break;
case '--limit': flags.limit = takeValue(argv, index); index += 1; break;
case '--scrape-results': flags.scrapeResults = takeValue(argv, index); index += 1; break;
case '--allow-free-cloud': flags.allowFreeCloud = true; break;
default: invalid();
}
}
if (positional.length === 0) invalid();
let command;
let args;
if (COMMANDS.has(positional[0])) {
[command, ...args] = positional;
} else if (/^https?:\/\//i.test(positional[0])) {
command = 'url';
args = positional;
} else {
invalid();
}
if (flags.engine !== null && !ENGINE_ID.test(flags.engine)) invalid();
if (flags.schema !== null && (flags.schema.includes('\0') || flags.schema.length > 4096)) invalid();
if (flags.format !== null && !FORMATS.has(flags.format)) invalid();
if (flags.output !== null && !isSafeOutputPath(flags.output)) invalid();
if (flags.dataRoot !== null && !isDataRoot(flags.dataRoot)) invalid();
if (flags.cache !== null && !CACHE_MODES.has(flags.cache)) invalid();
if (flags.ttl !== null) ttlMilliseconds(flags.ttl);
flags.include = flags.include.map(safePathGlob);
flags.exclude = flags.exclude.map(safePathGlob);
if (flags.discover !== null) discoverySources(flags.discover);
for (const name of ['maxPages', 'maxDepth', 'maxBytes', 'maxFrontier', 'concurrency', 'maxRedirects', 'retries']) {
if (flags[name] !== null) positiveNumber(flags[name], { integer: true });
}
if (flags.maxTime !== null) positiveNumber(flags.maxTime, { scale: 1_000 });
if (flags.delay !== null) positiveNumber(flags.delay, { scale: 1_000 });
if (flags.limit !== null) positiveNumber(flags.limit, { integer: true });
if (flags.scrapeResults !== null) {
positiveNumber(flags.scrapeResults, { integer: true, max: MAX_SCRAPE_RESULTS });
}
if (command !== 'search' && (flags.limit !== null || flags.scrapeResults !== null)) invalid();
const hasNativeOption = flags.format !== null || flags.output !== null
|| flags.dataRoot !== null || flags.cache !== null || flags.ttl !== null;
const hasCrawlOption = flags.include.length > 0 || flags.exclude.length > 0
|| flags.discover !== null || flags.preferDiscoveredSource
|| ['maxPages', 'maxDepth', 'maxTime', 'maxBytes', 'maxFrontier', 'concurrency', 'delay', 'maxRedirects', 'retries']
.some((name) => flags[name] !== null);
if (!['url', 'crawl', 'extract'].includes(command) && hasNativeOption) invalid();
if (!['url', 'crawl', 'extract'].includes(command) && flags.allowRendered) invalid();
if (command !== 'crawl' && hasCrawlOption) invalid();
if (flags.explain && (hasNativeOption || hasCrawlOption)) invalid();
if (command === 'health') {
if (args.length !== 0 || flags.schema !== null) invalid();
} else if (command === 'extract') {
if (args.length !== 1 || flags.schema === null) invalid();
} else {
if (args.length !== 1 || flags.schema !== null) invalid();
}
if (command === 'search' && (args[0].trim() === '' || args[0].length > MAX_QUERY_LENGTH)) invalid();
if (['url', 'crawl', 'extract'].includes(command)) {
try {
const parsed = new URL(args[0]);
if (!['http:', 'https:'].includes(parsed.protocol)) invalid();
} catch {
invalid();
}
}
return deepFreeze({ command, args, flags });
}
export function compileJobSpec(parsed) {
if (!parsed || !COMMANDS.has(parsed.command)) invalid();
const target = parsed.command === 'health'
? {}
: parsed.command === 'search'
? { query: parsed.args[0] }
: parsed.command === 'extract'
? { url: parsed.args[0], schemaPath: parsed.flags.schema }
: { url: parsed.args[0] };
const goals = {
url: 'markdown',
crawl: 'markdown',
extract: 'json',
search: 'search-results',
health: 'status',
};
const isLocalRun = ['url', 'crawl', 'extract'].includes(parsed.command) && !parsed.flags.explain;
const format = parsed.flags.format ?? (parsed.command === 'extract' ? 'json' : 'markdown');
const limitOverrides = {
...(parsed.flags.maxPages === null ? {} : { maxPages: positiveNumber(parsed.flags.maxPages, { integer: true }) }),
...(parsed.flags.maxDepth === null ? {} : { maxDepth: positiveNumber(parsed.flags.maxDepth, { integer: true }) }),
...(parsed.flags.maxTime === null ? {} : { wallMs: positiveNumber(parsed.flags.maxTime, { scale: 1_000 }) }),
...(parsed.flags.maxBytes === null ? {} : { maxTotalBytes: positiveNumber(parsed.flags.maxBytes, { integer: true }) }),
...(parsed.flags.maxFrontier === null ? {} : { maxFrontier: positiveNumber(parsed.flags.maxFrontier, { integer: true }) }),
...(parsed.flags.concurrency === null ? {} : { concurrency: positiveNumber(parsed.flags.concurrency, { integer: true }) }),
...(parsed.flags.delay === null ? {} : { delayMs: positiveNumber(parsed.flags.delay, { scale: 1_000 }) }),
...(parsed.flags.maxRedirects === null ? {} : { maxRedirects: positiveNumber(parsed.flags.maxRedirects, { integer: true }) }),
...(parsed.flags.retries === null ? {} : { retriesPerAdapter: positiveNumber(parsed.flags.retries, { integer: true }) }),
};
const spec = {
schemaVersion: 1,
kind: parsed.command,
target,
goal: goals[parsed.command],
limits: { ...DEFAULT_LIMITS, ...limitOverrides },
policy: {
network: 'public-only',
auth: 'none',
moneyBudget: 0,
allowFreeCloud: parsed.flags.allowFreeCloud,
allowRendered: parsed.flags.allowRendered,
respectRobots: true,
},
output: isLocalRun
? {
json: parsed.flags.json,
format,
path: parsed.flags.output,
dataRoot: parsed.flags.dataRoot,
}
: { json: parsed.flags.json },
routing: {
explain: parsed.flags.explain,
forcedEngine: parsed.flags.engine,
},
scope: {
include: parsed.flags.include.length > 0 ? [...parsed.flags.include] : ['/**'],
exclude: [...parsed.flags.exclude],
},
discovery: {
sources: parsed.flags.discover === null ? [] : discoverySources(parsed.flags.discover),
preferDiscoveredSource: parsed.flags.preferDiscoveredSource,
},
};
if (parsed.command === 'search') {
spec.search = {
limit: parsed.flags.limit === null
? DEFAULT_SEARCH.limit
: positiveNumber(parsed.flags.limit, { integer: true }),
scrapeResults: parsed.flags.scrapeResults === null
? DEFAULT_SEARCH.scrapeResults
: positiveNumber(parsed.flags.scrapeResults, { integer: true, max: MAX_SCRAPE_RESULTS }),
};
}
if (isLocalRun) {
spec.goal = format;
spec.cache = {
mode: parsed.flags.cache ?? 'use',
ttlMs: ttlMilliseconds(parsed.flags.ttl),
};
}
for (const value of Object.values(spec.limits)) {
if (!Number.isFinite(value) || value <= 0) invalid();
}
return deepFreeze(spec);
}
export function writeResult(result, io, { json = false } = {}) {
try {
validateResultEnvelope(result);
} catch (error) {
throw new TypeError(`invalid result envelope: ${error.message}`);
}
if (!io?.stdout || typeof io.stdout.write !== 'function') {
throw new TypeError('invalid output stream');
}
if (!io?.stderr || typeof io.stderr.write !== 'function') {
throw new TypeError('invalid diagnostic stream');
}
for (const warning of result.warnings) io.stderr.write(`warning: ${warning}\n`);
let output = `${result.status}: ${result.message}\n`;
if (result.code === 'health') {
output += result.capabilities
.map((entry) => `${entry.id}\t${entry.state}\t${entry.version ?? '-'}\t${entry.reason}`)
.join('\n');
output += '\n';
} else if (result.code === 'route_explained') {
output += result.route
.map((entry) => `${entry.id}\t${entry.eligible ? 'eligible' : 'blocked'}\t${entry.reason}`)
.join('\n');
output += '\n';
}
if (json) output = `${JSON.stringify(result)}\n`;
io.stdout.write(output);
}
function safeDiagnostic(io, value) {
try {
io?.stderr?.write(value);
} catch {
// A broken diagnostic stream cannot safely be recovered here.
}
}
function invalidInputResult(command = 'health', message = 'Invalid command line') {
return createResultEnvelope({
command: COMMANDS.has(command) ? command : 'health',
status: RUN_STATUS.INVALID_INPUT,
code: 'invalid_input',
message,
route: [],
capabilities: [],
warnings: [],
});
}
function internalErrorResult(command) {
return createResultEnvelope({
command,
status: RUN_STATUS.INTERNAL_ERROR,
code: 'internal_error',
message: 'Internal contract error',
route: [],
capabilities: [],
warnings: [],
});
}
export async function runCli(argv, { io, registry, executeJob, now }) {
const jsonRequested = Array.isArray(argv) && argv.includes('--json');
let spec;
try {
spec = compileJobSpec(parseArgv(argv));
} catch {
const result = invalidInputResult(Array.isArray(argv) ? argv[0] : undefined);
try {
writeResult(result, io, { json: jsonRequested });
return EXIT_CODE.INVALID_INPUT;
} catch {
safeDiagnostic(io, 'output_failure: unable to write result\n');
return EXIT_CODE.OUTPUT_FAILURE;
}
}
const forcedEngine = spec.routing.forcedEngine;
if (forcedEngine !== null && (!Array.isArray(registry)
|| !registry.some((entry) => entry?.id === forcedEngine))) {
const result = invalidInputResult(spec.kind, 'Unknown engine');
try {
writeResult(result, io, { json: spec.output.json });
return EXIT_CODE.INVALID_INPUT;
} catch {
safeDiagnostic(io, 'output_failure: unable to write result\n');
return EXIT_CODE.OUTPUT_FAILURE;
}
}
let result;
try {
if (typeof executeJob !== 'function') throw new TypeError('executeJob is required');
result = await executeJob(spec, { registry, now });
validateResultEnvelope(result);
if (result.command !== spec.kind) throw new TypeError('result command mismatch');
} catch {
result = internalErrorResult(spec.kind);
}
try {
writeResult(result, io, { json: spec.output.json });
} catch {
safeDiagnostic(io, 'output_failure: unable to write result\n');
return EXIT_CODE.OUTPUT_FAILURE;
}
return exitCodeForStatus(result.status, result.termination);
}
+118
View File
@@ -0,0 +1,118 @@
// Fail-closed free-cloud gate (COST-02 opt-in, COST-03 worst-case ledger).
//
// v1 forbids any network provider, so cloud is a MODEL, never runtime: this gate
// consumes only the frozen JobSpec/policy, a provider descriptor, and the shared
// credit ledger — never ambient credentials — and always keeps cloud closed. It
// exists to prove the invariants: zero money, a provider-managed trust boundary,
// provider bodies/hashes that are never local public-only evidence, and a ledger
// that can never be over-debited. When a real free provider ships and runtime
// cloud is wired, `eligible` flips true on a proven cost; nothing here executes.
//
// ponytail: dead model on purpose — no preflight/execute is ever invoked, so the
// billable path stays a single unbuilt branch. Upgrade path: wire a real provider
// behind evaluateCloudEligibility === eligible and add a compare-and-swap commit
// on ledger.committed in reserveWorstCase before any real oversubscription exists.
import { deepFreeze } from './contracts.mjs';
import { authorizeCloudCost } from './policy.mjs';
const BLOCKED = 'unknown_and_blocked';
function moneyStamp() {
return { cost_money: 0, credits_used: BLOCKED };
}
function boundaryStamp() {
return {
trust_boundary: { kind: 'provider-managed', evidence_is_local_public_only: false },
local_public_only_equivalent: false,
};
}
// Pure eligibility: opt-in AND a proven-free bounded cost are necessary, but in v1
// the provider never runs, so the outcome is always blocked. The reason is honest:
// the missing opt-in, the first unproven cost axis, or the disabled runtime.
export function evaluateCloudEligibility(job, { provider, ledger, clock = () => new Date() } = {}) {
const optIn = job?.policy?.allowFreeCloud === true;
const cost = authorizeCloudCost(provider, ledger, clock);
const reason = !optIn
? 'free_cloud_not_allowed'
: cost.allowed ? 'cloud_runtime_disabled' : cost.reason;
return deepFreeze({
eligible: false,
outcome: BLOCKED,
reason,
cost_proven: cost.allowed,
...moneyStamp(),
...boundaryStamp(),
});
}
// Opt-in gate run BEFORE any provider preflight/execute. Returns the local-first
// route and eligibility byte-for-byte — cloud adds no hop when it stays closed.
export async function evaluateCloudGate(job, { provider, ledger, baseline, clock = () => new Date() } = {}) {
const elig = evaluateCloudEligibility(job, { provider, ledger, clock });
return deepFreeze({
outcome: elig.outcome,
reason: elig.reason,
executed: false,
route: baseline.route,
eligibility: baseline.eligibility,
...moneyStamp(),
...boundaryStamp(),
});
}
// Inspects the provider's declared worst-case reservation against the shared run
// ledger. A negative, non-finite, over-ceiling, or over-balance figure is a broken
// provider contract — never "cost went down → free success". v1 never commits, so
// the ledger is never debited and oversubscription is structurally impossible.
export function reserveWorstCase(ledger, { job, provider, clock = () => new Date() } = {}) {
const cost = authorizeCloudCost(provider, ledger, clock);
const broken = cost.reason === 'worst_case_unbounded';
return deepFreeze({
outcome: BLOCKED,
broken,
committed: false,
...moneyStamp(),
});
}
// Produces the honest attempt + manifest records for a blocked cloud attempt. The
// provider is never invoked; its body/hash is never promoted to local evidence and
// never becomes a top-level source hash.
export async function runCloudAttempt(job, { provider, ledger, clock = () => new Date() } = {}) {
const elig = evaluateCloudEligibility(job, { provider, ledger, clock });
const attempt = deepFreeze({
kind: 'cloud',
outcome: BLOCKED,
reason: elig.reason,
executed: false,
...moneyStamp(),
...boundaryStamp(),
});
const manifest = deepFreeze({
kind: 'cloud_attempt',
outcome: BLOCKED,
reason: elig.reason,
provider: {
id: provider?.id ?? null,
version: provider?.version ?? null,
network_model: 'provider-managed',
},
...moneyStamp(),
...boundaryStamp(),
});
return { attempt, manifest };
}
// Binds the gate to one shared run ledger so every evaluate/reserve/attempt draws
// from the same credit state — the reservation point that a future runtime makes
// atomic. In v1 every method fails closed.
export function createCloudGate({ ledger, clock = () => new Date() } = {}) {
return {
evaluate: (job, { provider, baseline }) => evaluateCloudGate(job, { provider, ledger, baseline, clock }),
reserve: (job, provider) => reserveWorstCase(ledger, { job, provider, clock }),
attempt: (job, provider) => runCloudAttempt(job, { provider, ledger, clock }),
};
}
+278
View File
@@ -0,0 +1,278 @@
export const RUN_STATUS = Object.freeze({
OK: 'ok',
INVALID_INPUT: 'invalid_input',
PARTIAL: 'partial',
EXHAUSTED: 'exhausted',
BLOCKED: 'blocked',
INTERNAL_ERROR: 'internal_error',
OUTPUT_FAILURE: 'output_failure',
INTERRUPTED: 'interrupted',
});
export const EXIT_CODE = Object.freeze({
OK: 0,
INVALID_INPUT: 2,
PARTIAL: 3,
EXHAUSTED: 4,
BLOCKED: 5,
INTERNAL_ERROR: 70,
OUTPUT_FAILURE: 74,
TIMEOUT: 124,
SIGINT: 130,
SIGTERM: 143,
});
export const ATTEMPT_KIND = Object.freeze({
SUCCESS: 'success',
SKIP: 'skip',
RETRYABLE: 'retryable',
INADEQUATE: 'inadequate',
TERMINAL: 'terminal',
BROKEN: 'broken',
});
export const ATTEMPT_CODE = Object.freeze({
OK: 'ok',
UNAVAILABLE: 'unavailable',
UNSUPPORTED: 'unsupported',
CLOUD_DISABLED: 'cloud_disabled',
POLICY_UNENFORCEABLE: 'policy_unenforceable',
TIMEOUT: 'timeout',
NETWORK: 'network',
HTTP_5XX: 'http_5xx',
RATE_LIMITED: 'rate_limited',
JS_SHELL: 'js_shell',
EMPTY: 'empty',
WRONG_MIME: 'wrong_mime',
PARSE_FAILED: 'parse_failed',
POLICY_DENIED: 'policy_denied',
ROBOTS_DENIED: 'robots_denied',
ACCESS_DENIED: 'access_denied',
AUTH_REQUIRED: 'auth_required',
CAPTCHA: 'captcha',
PAYWALL: 'paywall',
PAID_REQUIRED: 'paid_required',
NOT_FOUND: 'not_found',
GONE: 'gone',
HARD_LIMIT: 'hard_limit',
ADAPTER_CRASH: 'adapter_crash',
ADAPTER_PROTOCOL_ERROR: 'adapter_protocol_error',
HASH_MISMATCH: 'hash_mismatch',
});
export const CAPABILITY_STATE = Object.freeze({
READY: 'ready',
MISSING: 'missing',
DISABLED: 'disabled',
MISCONFIGURED: 'misconfigured',
UNAVAILABLE_SECURITY_GATE: 'unavailable_security_gate',
});
const COMMANDS = new Set(['url', 'crawl', 'extract', 'search', 'health']);
const REQUIRED_FIELDS = [
'schema_version',
'command',
'status',
'code',
'message',
'route',
'capabilities',
'warnings',
];
const OPTIONAL_FIELDS = new Set([
'termination',
'manifest_path',
'artifact_path',
'source_hash',
'cache_status',
]);
const CACHE_STATUS = new Set(['off', 'miss', 'hit', 'revalidated']);
const SHA256 = /^sha256:[a-f0-9]{64}$/u;
const ALLOWED_CODES = Object.freeze({
[RUN_STATUS.OK]: new Set(['ok', 'health', 'route_explained']),
[RUN_STATUS.INVALID_INPUT]: new Set(['invalid_input']),
[RUN_STATUS.PARTIAL]: new Set(['partial']),
[RUN_STATUS.EXHAUSTED]: new Set([
'exhausted',
'no_eligible_engine',
'unavailable_no_free_search_provider',
ATTEMPT_CODE.NOT_FOUND,
ATTEMPT_CODE.GONE,
]),
[RUN_STATUS.BLOCKED]: new Set([
'blocked',
ATTEMPT_CODE.POLICY_DENIED,
ATTEMPT_CODE.ROBOTS_DENIED,
ATTEMPT_CODE.ACCESS_DENIED,
ATTEMPT_CODE.AUTH_REQUIRED,
ATTEMPT_CODE.CAPTCHA,
ATTEMPT_CODE.PAYWALL,
ATTEMPT_CODE.PAID_REQUIRED,
ATTEMPT_CODE.HARD_LIMIT,
ATTEMPT_CODE.RATE_LIMITED,
]),
[RUN_STATUS.INTERNAL_ERROR]: new Set([
'internal_error',
'unknown_attempt_code',
ATTEMPT_CODE.ADAPTER_CRASH,
ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR,
ATTEMPT_CODE.HASH_MISMATCH,
]),
[RUN_STATUS.OUTPUT_FAILURE]: new Set(['output_failure']),
[RUN_STATUS.INTERRUPTED]: new Set(['interrupted', ATTEMPT_CODE.TIMEOUT]),
});
function assertPlainObject(value, label) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new TypeError(`${label} must be an object`);
}
const prototype = Object.getPrototypeOf(value);
if (prototype !== Object.prototype && prototype !== null) {
throw new TypeError(`${label} must be a plain object`);
}
}
function copyJson(value, label, seen = new WeakSet()) {
if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
if (typeof value === 'number') {
if (!Number.isFinite(value)) throw new TypeError(`${label} contains a non-finite number`);
return value;
}
if (typeof value !== 'object') throw new TypeError(`${label} contains a non-JSON value`);
if (seen.has(value)) throw new TypeError(`${label} contains a cycle`);
seen.add(value);
if (Array.isArray(value)) {
const copied = value.map((item, index) => copyJson(item, `${label}[${index}]`, seen));
seen.delete(value);
return copied;
}
assertPlainObject(value, label);
const copied = {};
for (const [key, item] of Object.entries(value)) {
copied[key] = copyJson(item, `${label}.${key}`, seen);
}
seen.delete(value);
return copied;
}
export function deepFreeze(value) {
if (!value || typeof value !== 'object' || Object.isFrozen(value)) return value;
for (const child of Object.values(value)) deepFreeze(child);
return Object.freeze(value);
}
function validateTermination(termination) {
assertPlainObject(termination, 'termination');
const keys = Object.keys(termination);
if (keys.length === 0 || keys.some((key) => !['reason', 'signal'].includes(key))) {
throw new TypeError('termination has unexpected field');
}
if ('reason' in termination && termination.reason !== 'timeout') {
throw new TypeError('termination reason must be timeout');
}
if ('signal' in termination && !['SIGINT', 'SIGTERM'].includes(termination.signal)) {
throw new TypeError('termination signal is unknown');
}
}
function validateRelativeResultPath(value, field) {
if (typeof value !== 'string' || value.length === 0 || value.length > 4096) {
throw new TypeError(`${field} must be a relative path`);
}
if (value !== value.trim() || /[\u0000-\u001f\u007f\\]/u.test(value) || value.startsWith('/')
|| /^[a-z]:/iu.test(value)) {
throw new TypeError(`${field} must be a relative path`);
}
const parts = value.split('/');
if (parts.some((part) => part === '' || part === '.' || part === '..')) {
throw new TypeError(`${field} must be a relative path`);
}
}
export function validateResultEnvelope(value) {
assertPlainObject(value, 'result envelope');
const keys = Object.keys(value);
for (const field of REQUIRED_FIELDS) {
if (!Object.hasOwn(value, field)) throw new TypeError(`result envelope missing ${field}`);
}
for (const field of keys) {
if (!REQUIRED_FIELDS.includes(field) && !OPTIONAL_FIELDS.has(field)) {
throw new TypeError(`unexpected field: ${field}`);
}
}
if (value.schema_version !== 1) throw new TypeError('schema_version must be 1');
if (!COMMANDS.has(value.command)) throw new TypeError('command is unknown');
if (!Object.values(RUN_STATUS).includes(value.status)) throw new TypeError('status is unknown');
if (typeof value.code !== 'string' || !ALLOWED_CODES[value.status]?.has(value.code)) {
throw new TypeError(`code does not match status: ${value.status}`);
}
if (typeof value.message !== 'string') throw new TypeError('message must be a string');
if (!Array.isArray(value.route)) throw new TypeError('route must be an array');
if (!Array.isArray(value.capabilities)) throw new TypeError('capabilities must be an array');
if (!Array.isArray(value.warnings) || value.warnings.some((item) => typeof item !== 'string')) {
throw new TypeError('warnings must contain strings');
}
copyJson(value.route, 'route');
copyJson(value.capabilities, 'capabilities');
if (value.termination !== undefined) validateTermination(value.termination);
if (value.manifest_path !== undefined) {
validateRelativeResultPath(value.manifest_path, 'manifest_path');
}
if (value.artifact_path !== undefined) {
validateRelativeResultPath(value.artifact_path, 'artifact_path');
}
if (value.source_hash !== undefined
&& (typeof value.source_hash !== 'string' || !SHA256.test(value.source_hash))) {
throw new TypeError('source_hash must be a lowercase sha256 marker');
}
if (value.cache_status !== undefined && !CACHE_STATUS.has(value.cache_status)) {
throw new TypeError('cache_status is unknown');
}
if (value.status === RUN_STATUS.INTERRUPTED && value.termination === undefined) {
throw new TypeError('interrupted result requires termination');
}
return true;
}
export function createResultEnvelope(fields) {
assertPlainObject(fields, 'result fields');
const value = {
schema_version: fields.schema_version ?? 1,
command: fields.command,
status: fields.status,
code: fields.code,
message: fields.message,
route: copyJson(fields.route, 'route'),
capabilities: copyJson(fields.capabilities, 'capabilities'),
warnings: copyJson(fields.warnings, 'warnings'),
};
for (const field of OPTIONAL_FIELDS) {
if (fields[field] !== undefined) value[field] = copyJson(fields[field], field);
}
for (const field of Object.keys(fields)) {
if (!REQUIRED_FIELDS.includes(field) && !OPTIONAL_FIELDS.has(field)) {
throw new TypeError(`unexpected field: ${field}`);
}
}
validateResultEnvelope(value);
return deepFreeze(value);
}
export function exitCodeForStatus(status, termination) {
switch (status) {
case RUN_STATUS.OK: return EXIT_CODE.OK;
case RUN_STATUS.INVALID_INPUT: return EXIT_CODE.INVALID_INPUT;
case RUN_STATUS.PARTIAL: return EXIT_CODE.PARTIAL;
case RUN_STATUS.EXHAUSTED: return EXIT_CODE.EXHAUSTED;
case RUN_STATUS.BLOCKED: return EXIT_CODE.BLOCKED;
case RUN_STATUS.INTERNAL_ERROR: return EXIT_CODE.INTERNAL_ERROR;
case RUN_STATUS.OUTPUT_FAILURE: return EXIT_CODE.OUTPUT_FAILURE;
case RUN_STATUS.INTERRUPTED:
if (termination?.reason === 'timeout') return EXIT_CODE.TIMEOUT;
if (termination?.signal === 'SIGINT') return EXIT_CODE.SIGINT;
if (termination?.signal === 'SIGTERM') return EXIT_CODE.SIGTERM;
throw new TypeError('interrupted status requires known termination');
default:
throw new TypeError(`unknown run status: ${String(status)}`);
}
}
+1762
View File
File diff suppressed because it is too large Load Diff
+410
View File
@@ -0,0 +1,410 @@
import { readFile } from 'node:fs/promises';
import { parsePublicUrl } from './policy.mjs';
const SNIFF_BYTES = 8 * 1024;
const DEFAULT_MAX_ARTIFACT_BYTES = 8 * 1024 * 1024;
const FORMATS = new Set(['raw', 'markdown', 'metadata', 'links', 'json']);
const XML_KINDS = new Set(['xml', 'rss', 'atom', 'sitemap']);
class RepresentationError extends Error {
constructor(code, message) {
super(message);
this.name = 'RepresentationError';
this.code = code;
}
}
function fail(code, message) {
throw new RepresentationError(code, message);
}
function headerValue(headers, wantedName) {
if (headers?.get instanceof Function) {
const value = headers.get(wantedName);
return Array.isArray(value) ? value[0] : value;
}
if (!headers || typeof headers !== 'object') return undefined;
const entry = Object.entries(headers).find(([name]) => name.toLowerCase() === wantedName);
const value = entry?.[1];
return Array.isArray(value) ? value[0] : value;
}
function normalizeMediaType(value) {
if (typeof value !== 'string') return '';
const mediaType = value.split(';', 1)[0].trim().toLowerCase();
return /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/u.test(mediaType) ? mediaType : '';
}
function declaredKind(mediaType) {
if (['text/html', 'application/xhtml+xml'].includes(mediaType)) return 'html';
if (['text/markdown', 'text/x-markdown', 'application/markdown'].includes(mediaType)) return 'markdown';
if (mediaType === 'application/rss+xml') return 'rss';
if (mediaType === 'application/atom+xml') return 'atom';
if (mediaType === 'application/sitemap+xml') return 'sitemap';
if (['application/json', 'text/json'].includes(mediaType) || mediaType.endsWith('+json')) return 'json';
if (['application/xml', 'text/xml'].includes(mediaType) || mediaType.endsWith('+xml')) return 'xml';
return null;
}
function sniffKind(prefixBytes) {
const prefix = Buffer.isBuffer(prefixBytes)
? prefixBytes.subarray(0, SNIFF_BYTES)
: Buffer.from(prefixBytes ?? '').subarray(0, SNIFF_BYTES);
if (prefix.length === 0) return null;
let text = prefix.toString('utf8').replace(/^\ufeff/u, '').trimStart();
const lower = text.toLowerCase();
if (/^<!doctype\s+html(?:\s|>)/u.test(lower) || /^<html(?:\s|>)/u.test(lower)) return 'html';
if (text[0] === '{' || text[0] === '[') return 'json';
for (let pass = 0; pass < 4; pass += 1) {
const before = text;
text = text
.replace(/^<\?xml\b[^?]*(?:\?>|$)\s*/iu, '')
.replace(/^<!--[^]*?(?:-->|$)\s*/u, '')
.replace(/^<!doctype\b[^>]*(?:>|$)\s*/iu, '');
if (text === before) break;
}
const root = text.match(/^<\s*([a-z_][\w:.-]*)(?:\s|\/?>)/iu)?.[1]?.toLowerCase();
if (!root) return null;
const localRoot = root.includes(':') ? root.slice(root.lastIndexOf(':') + 1) : root;
if (localRoot === 'rss') return 'rss';
if (localRoot === 'feed') return 'atom';
if (localRoot === 'urlset' || localRoot === 'sitemapindex') return 'sitemap';
if (['html', 'head', 'body'].includes(localRoot)) return 'html';
return 'xml';
}
export function detectRepresentation({ headers = {}, prefixBytes = Buffer.alloc(0) } = {}) {
const mediaType = normalizeMediaType(headerValue(headers, 'content-type')) || 'application/octet-stream';
const declared = declaredKind(mediaType);
const sniffed = sniffKind(prefixBytes);
let kind = declared;
if (!kind) kind = sniffed;
if (kind === 'xml' && ['rss', 'atom', 'sitemap'].includes(sniffed)) kind = sniffed;
if (!kind) kind = 'binary';
const warnings = kind === 'binary' ? ['unknown_mime_raw_preserved'] : [];
const result = {
kind,
mediaType,
declaredType: declared,
warnings: Object.freeze(warnings),
};
if (sniffed && sniffed !== declared) result.sniffedType = sniffed;
return Object.freeze(result);
}
function artifactLimit(value) {
const limit = value === undefined ? DEFAULT_MAX_ARTIFACT_BYTES : value;
if (!Number.isSafeInteger(limit) || limit <= 0) {
fail('hard_limit', 'maxArtifactBytes must be a positive finite integer');
}
return limit;
}
function checkedArtifact(bytes, limit) {
const artifact = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
if (artifact.length > limit) {
const error = new RepresentationError('hard_limit', 'derived artifact exceeds maxArtifactBytes');
error.limit = 'artifact_bytes';
error.maxBytes = limit;
error.actualBytes = artifact.length;
throw error;
}
return artifact;
}
async function loadSource(sourcePath) {
if (typeof sourcePath !== 'string' || sourcePath.length === 0) {
fail('output_failure', 'sourcePath must name a stored source object');
}
try {
return await readFile(sourcePath);
} catch (cause) {
const error = new RepresentationError('output_failure', 'unable to read stored source bytes');
error.cause = cause;
throw error;
}
}
function stableJson(value) {
if (value === null || typeof value === 'string' || typeof value === 'boolean') return JSON.stringify(value);
if (typeof value === 'number') {
if (!Number.isFinite(value)) fail('output_failure', 'JSON contains a non-finite number');
return JSON.stringify(value);
}
if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
const entries = Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`);
return `{${entries.join(',')}}`;
}
function jsonBytes(value) {
return Buffer.from(`${stableJson(value)}\n`, 'utf8');
}
function parseJson(source) {
let parsed;
try {
parsed = JSON.parse(source.toString('utf8'));
} catch (cause) {
const error = new RepresentationError('output_failure', 'stored source is not valid JSON');
error.cause = cause;
throw error;
}
return parsed;
}
function decodeHtmlEntities(value) {
const named = new Map([
['amp', '&'], ['apos', "'"], ['gt', '>'], ['lt', '<'], ['nbsp', ' '], ['quot', '"'],
]);
return value.replace(/&(#(?:x[0-9a-f]+|[0-9]+)|[a-z][a-z0-9]+);/giu, (entity, name) => {
const normalized = name.toLowerCase();
if (!normalized.startsWith('#')) return named.get(normalized) ?? entity;
const hexadecimal = normalized[1] === 'x';
const digits = normalized.slice(hexadecimal ? 2 : 1);
const codePoint = Number.parseInt(digits, hexadecimal ? 16 : 10);
if (!Number.isInteger(codePoint)
|| codePoint <= 0
|| codePoint > 0x10ffff
|| (codePoint >= 0xd800 && codePoint <= 0xdfff)) return '\ufffd';
return String.fromCodePoint(codePoint);
});
}
function attributeValue(tag, name) {
const escaped = name.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
const match = tag.match(new RegExp(`(?:^|\\s)${escaped}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\u0060]+))`, 'iu'));
return match ? decodeHtmlEntities(match[1] ?? match[2] ?? match[3] ?? '') : null;
}
function publicUrl(candidate, baseUrl) {
if (typeof candidate !== 'string' || candidate.length === 0 || candidate !== candidate.trim()) return null;
if (candidate.length > 8192 || /[\\\u0000-\u001f\u007f]/u.test(candidate)) return null;
let resolved;
try {
resolved = new URL(candidate, baseUrl).href;
return parsePublicUrl(resolved).canonicalUrl;
} catch {
return null;
}
}
function withoutNonDataMarkup(source) {
return source
.replace(/<!--[^]*?(?:-->|$)/gu, '')
.replace(/<(script|style|template|noscript|iframe|object|svg|canvas)\b[^>]*>[^]*?<\/\1\s*>/giu, '')
.replace(/<(script|style|template|noscript|iframe|object|svg|canvas)\b[^>]*\/?\s*>/giu, '');
}
function markupCandidates(source) {
const cleaned = withoutNonDataMarkup(source);
const values = [];
for (const match of cleaned.matchAll(/<[^>]+>/gu)) {
const href = attributeValue(match[0], 'href');
if (href !== null) values.push(href);
}
for (const match of cleaned.matchAll(/<(?:loc|link)\b[^>]*>([^<]*)<\/(?:loc|link)\s*>/giu)) {
values.push(decodeHtmlEntities(match[1].trim()));
}
return values;
}
function markdownCandidates(source) {
const values = [];
for (const match of source.matchAll(/!?\[[^\]]*\]\(([^\s)]+)(?:\s+["'][^"']*["'])?\)/gu)) values.push(match[1]);
for (const match of source.matchAll(/<(https?:\/\/[^\s<>]+)>/giu)) values.push(match[1]);
return values;
}
function jsonCandidates(value, values = []) {
if (typeof value === 'string') {
if (/^(?:https?:\/\/|\/\/|\/|\.\.?\/)/iu.test(value)) values.push(value);
return values;
}
if (Array.isArray(value)) {
for (const item of value) jsonCandidates(item, values);
return values;
}
if (value && typeof value === 'object') {
for (const item of Object.values(value)) jsonCandidates(item, values);
}
return values;
}
function extractLinks(source, kind, finalUrl) {
let candidates = [];
const text = source.toString('utf8');
if (kind === 'html' || XML_KINDS.has(kind)) candidates = markupCandidates(text);
else if (kind === 'markdown') candidates = markdownCandidates(text);
else if (kind === 'json') candidates = jsonCandidates(parseJson(source));
const links = new Set();
for (const candidate of candidates) {
const safe = publicUrl(candidate, finalUrl);
if (safe) links.add(safe);
}
return [...links].sort();
}
function appendBreak(output, count = 2) {
const withoutSpaces = output.replace(/[ \t]+$/u, '');
const trailing = withoutSpaces.match(/\n*$/u)?.[0].length ?? 0;
return `${withoutSpaces}${'\n'.repeat(Math.max(0, count - trailing))}`;
}
function markdownLinkUrl(url) {
return url.replace(/\\/gu, '%5C').replace(/\(/gu, '%28').replace(/\)/gu, '%29');
}
function htmlMarkdown(source, finalUrl) {
const body = withoutNonDataMarkup(source).replace(/<head\b[^>]*>[^]*?<\/head\s*>/giu, '');
const tokens = body.match(/<[^>]*>|[^<]+/gu) ?? [];
const anchors = [];
let output = '';
for (const token of tokens) {
if (!token.startsWith('<')) {
const compact = decodeHtmlEntities(token).replace(/\s+/gu, ' ');
if (compact.trim() === '') {
if (output !== '' && !/[\s]$/u.test(output)) output += ' ';
} else {
const text = /(?:^|[\s])$/u.test(output) ? compact.trimStart() : compact;
output += text;
}
continue;
}
const parsed = token.match(/^<\s*(\/?)\s*([a-z][\w:-]*)/iu);
if (!parsed) continue;
const closing = parsed[1] === '/';
const name = parsed[2].toLowerCase();
if (name === 'a') {
if (!closing) {
anchors.push({ start: output.length, url: publicUrl(attributeValue(token, 'href'), finalUrl) });
} else {
const anchor = anchors.pop();
if (anchor?.url) {
const before = output.slice(0, anchor.start);
const label = output.slice(anchor.start).trim().replace(/([\[\]\\])/gu, '\\$1');
output = `${before}[${label || anchor.url}](${markdownLinkUrl(anchor.url)})`;
}
}
continue;
}
const heading = name.match(/^h([1-6])$/u);
if (heading) {
output = appendBreak(output);
if (!closing) output += `${'#'.repeat(Number(heading[1]))} `;
continue;
}
if (name === 'br') {
output = appendBreak(output, 1);
continue;
}
if (name === 'li') {
output = appendBreak(output, 1);
if (!closing) output += '- ';
continue;
}
if (['p', 'div', 'section', 'article', 'main', 'header', 'footer', 'nav', 'aside', 'blockquote', 'pre', 'table', 'tr', 'ul', 'ol'].includes(name)) {
output = appendBreak(output);
continue;
}
if (name === 'img' && !closing) {
const alt = attributeValue(token, 'alt')?.replace(/\s+/gu, ' ').trim();
if (alt) output += alt;
}
}
output = output
.replace(/[ \t]+\n/gu, '\n')
.replace(/\n{3,}/gu, '\n\n')
.trim();
return output === '' ? '' : `${output}\n`;
}
function fencedSource(source, language) {
const text = source.toString('utf8');
let fenceLength = 3;
for (const run of text.matchAll(/`+/gu)) fenceLength = Math.max(fenceLength, run[0].length + 1);
const fence = '`'.repeat(fenceLength);
return `${fence}${language}\n${text}${text.endsWith('\n') ? '' : '\n'}${fence}\n`;
}
function safeFinalUrl(finalUrl) {
try {
return parsePublicUrl(finalUrl).canonicalUrl;
} catch (cause) {
const error = new RepresentationError('output_failure', 'finalUrl is not a safe public HTTP(S) URL');
error.cause = cause;
throw error;
}
}
export async function deriveRepresentation({
format,
sourcePath,
mediaType,
finalUrl,
maxArtifactBytes,
} = {}) {
if (!FORMATS.has(format)) fail('unsupported_format', 'requested representation format is unsupported');
const limit = artifactLimit(maxArtifactBytes);
const source = await loadSource(sourcePath);
const normalizedMediaType = normalizeMediaType(mediaType) || 'application/octet-stream';
const detected = detectRepresentation({
headers: { 'content-type': normalizedMediaType },
prefixBytes: source.subarray(0, SNIFF_BYTES),
});
const warnings = [...detected.warnings];
if (format === 'raw') {
return Object.freeze({
format: 'raw',
mediaType: normalizedMediaType,
bytes: checkedArtifact(source, limit),
warnings: Object.freeze(warnings),
});
}
const canonicalFinalUrl = safeFinalUrl(finalUrl);
let bytes;
let effectiveFormat = format;
if (format === 'metadata') {
bytes = jsonBytes({
bytes: source.length,
final_url: canonicalFinalUrl,
media_type: normalizedMediaType,
});
} else if (format === 'links') {
bytes = jsonBytes(extractLinks(source, detected.kind, canonicalFinalUrl));
} else if (format === 'json') {
bytes = jsonBytes(parseJson(source));
} else if (detected.kind === 'markdown') {
bytes = source;
} else if (detected.kind === 'json') {
bytes = Buffer.from(fencedSource(source, 'json'), 'utf8');
} else if (XML_KINDS.has(detected.kind)) {
bytes = Buffer.from(fencedSource(source, 'xml'), 'utf8');
} else if (detected.kind === 'html') {
bytes = Buffer.from(htmlMarkdown(source.toString('utf8'), canonicalFinalUrl), 'utf8');
} else {
effectiveFormat = 'raw';
bytes = source;
if (!warnings.includes('unknown_mime_raw_preserved')) warnings.push('unknown_mime_raw_preserved');
}
return Object.freeze({
format: effectiveFormat,
mediaType: normalizedMediaType,
bytes: checkedArtifact(bytes, limit),
warnings: Object.freeze(warnings),
});
}
+639
View File
@@ -0,0 +1,639 @@
import {
ATTEMPT_CODE,
ATTEMPT_KIND,
RUN_STATUS,
} from './contracts.mjs';
const DEFAULT_LIMITS = Object.freeze({
maxPages: 100,
maxDepth: 3,
wallMs: 60_000,
maxTotalBytes: 64 * 1024 * 1024,
maxFrontier: 1_000,
concurrency: 1,
delayMs: 250,
retriesPerAdapter: 2,
maxRedirects: 5,
});
const GLOB_MAX_LENGTH = 1_024;
const UNSAFE_GLOB = /[\u0000-\u001f\u007f\\?#\[\]{}()^|]/u;
function positiveInteger(value, fallback, label) {
const resolved = value ?? fallback;
if (!Number.isSafeInteger(resolved) || resolved <= 0) {
throw new TypeError(`${label} must be a positive finite integer`);
}
return resolved;
}
function positiveFinite(value, fallback, label) {
const resolved = value ?? fallback;
if (!Number.isFinite(resolved) || resolved <= 0) {
throw new TypeError(`${label} must be a positive finite number`);
}
return resolved;
}
function nonnegativeInteger(value, fallback, label) {
const resolved = value ?? fallback;
if (!Number.isSafeInteger(resolved) || resolved < 0) {
throw new TypeError(`${label} must be a non-negative finite integer`);
}
return resolved;
}
function normalizeLimits(input = {}) {
if (!input || typeof input !== 'object' || Array.isArray(input)) {
throw new TypeError('crawl limits must be an object');
}
return Object.freeze({
maxPages: positiveInteger(input.maxPages, DEFAULT_LIMITS.maxPages, 'maxPages'),
maxDepth: positiveInteger(input.maxDepth, DEFAULT_LIMITS.maxDepth, 'maxDepth'),
wallMs: positiveFinite(input.wallMs, DEFAULT_LIMITS.wallMs, 'wallMs'),
maxTotalBytes: positiveInteger(
input.maxTotalBytes,
DEFAULT_LIMITS.maxTotalBytes,
'maxTotalBytes',
),
maxFrontier: positiveInteger(
input.maxFrontier,
DEFAULT_LIMITS.maxFrontier,
'maxFrontier',
),
concurrency: positiveInteger(
input.concurrency,
DEFAULT_LIMITS.concurrency,
'concurrency',
),
delayMs: positiveFinite(input.delayMs, DEFAULT_LIMITS.delayMs, 'delayMs'),
retriesPerAdapter: nonnegativeInteger(
input.retriesPerAdapter,
DEFAULT_LIMITS.retriesPerAdapter,
'retriesPerAdapter',
),
maxRedirects: nonnegativeInteger(
input.maxRedirects,
DEFAULT_LIMITS.maxRedirects,
'maxRedirects',
),
});
}
function originOf(value) {
let url;
try {
url = new URL(value);
} catch {
throw new TypeError('crawl origin must be an absolute HTTP URL');
}
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) {
throw new TypeError('crawl origin must be an absolute HTTP URL');
}
return url.origin;
}
/**
* Return the narrow WHATWG identity used by a single crawl.
* Query bytes and ordering are intentionally preserved; fragments are not sent on HTTP.
*/
export function canonicalFrontierKey(candidate, exactOrigin) {
const origin = originOf(exactOrigin);
let url;
try {
url = new URL(candidate, `${origin}/`);
} catch {
throw new TypeError('candidate must belong to the crawl exact origin');
}
if (url.origin !== origin || !['http:', 'https:'].includes(url.protocol)
|| url.username || url.password) {
throw new TypeError('candidate must belong to the crawl exact origin');
}
url.hash = '';
return url.href;
}
function validateGlob(glob) {
if (typeof glob !== 'string' || glob.length === 0 || glob.length > GLOB_MAX_LENGTH
|| !glob.startsWith('/') || UNSAFE_GLOB.test(glob) || /\*{3,}/u.test(glob)) {
throw new TypeError('crawl glob must be an anchored safe pathname glob');
}
const segments = glob.split('/');
if (segments.some((segment) => segment === '..' || segment === '.')) {
throw new TypeError('crawl glob must be an anchored safe pathname glob');
}
return glob;
}
function escapeRegex(value) {
return value.replace(/[.+$]/gu, '\\$&');
}
function compileGlob(glob) {
const validated = validateGlob(glob);
let expression = '';
for (let index = 0; index < validated.length; index += 1) {
const character = validated[index];
if (character !== '*') {
expression += escapeRegex(character);
continue;
}
if (validated[index + 1] === '*') {
expression += '.*';
index += 1;
} else {
expression += '[^/]*';
}
}
return new RegExp(`^${expression}$`, 'u');
}
function copyLedgerEntry(entry, extra = {}) {
return {
url: entry.url,
depth: entry.depth,
source: entry.source,
...(entry.provenance === undefined ? {} : { provenance: entry.provenance }),
...extra,
};
}
/**
* FIFO crawl frontier. It owns canonical dedupe and scope; it never performs I/O.
*/
export function createFrontier({
seedUrl,
include = ['/**'],
exclude = [],
limits = {},
} = {}) {
const origin = originOf(seedUrl);
if (!Array.isArray(include) || !Array.isArray(exclude) || include.length === 0) {
throw new TypeError('crawl include/exclude must be non-empty arrays');
}
const normalizedLimits = normalizeLimits(limits);
const includeMatchers = include.map(compileGlob);
const excludeMatchers = exclude.map(compileGlob);
const queue = [];
const seen = new Set();
function enqueue(candidate, {
depth = 0,
source = seedUrl,
provenance,
seed = false,
} = {}) {
if (!Number.isSafeInteger(depth) || depth < 0) {
return { accepted: false, reason: 'invalid_depth', url: String(candidate), depth, source };
}
let key;
try {
const resolved = typeof source === 'string'
? new URL(candidate, source).href
: candidate;
key = canonicalFrontierKey(resolved, origin);
} catch {
return { accepted: false, reason: 'off_origin', url: String(candidate), depth, source };
}
const pathname = new URL(key).pathname;
const entry = { url: key, depth, source, provenance };
if (depth > normalizedLimits.maxDepth) {
return { accepted: false, reason: 'max_depth', ...entry };
}
if (excludeMatchers.some((matcher) => matcher.test(pathname))) {
return { accepted: false, reason: 'excluded', ...entry };
}
// The seed is allowed to act as a discovery index for a narrower include scope.
if (!seed && !includeMatchers.some((matcher) => matcher.test(pathname))) {
return { accepted: false, reason: 'not_included', ...entry };
}
if (seen.has(key)) return { accepted: false, reason: 'duplicate', ...entry };
if (queue.length >= normalizedLimits.maxFrontier) {
return { accepted: false, reason: 'max_frontier', ...entry };
}
seen.add(key);
queue.push(entry);
return { accepted: true, ...entry };
}
const seed = enqueue(seedUrl, { depth: 0, source: null, provenance: 'seed', seed: true });
return Object.freeze({
origin,
limits: normalizedLimits,
seed,
enqueue,
dequeue() {
return queue.shift() ?? null;
},
drain() {
return queue.splice(0, queue.length);
},
snapshot() {
return queue.map((entry) => ({ ...entry }));
},
hasSeen(candidate) {
try {
return seen.has(canonicalFrontierKey(candidate, origin));
} catch {
return false;
}
},
get size() {
return queue.length;
},
});
}
function outcomeOf(result) {
if (result?.outcome && typeof result.outcome === 'object') return result.outcome;
if (result?.status === RUN_STATUS.OK || result?.status === 'ok') {
return { kind: ATTEMPT_KIND.SUCCESS, code: ATTEMPT_CODE.OK };
}
if (result?.status === RUN_STATUS.BLOCKED || result?.status === 'blocked') {
return { kind: ATTEMPT_KIND.TERMINAL, code: result.code ?? ATTEMPT_CODE.ACCESS_DENIED };
}
return {
kind: ATTEMPT_KIND.BROKEN,
code: result?.code ?? ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR,
};
}
function isAccepted(outcome) {
return outcome.kind === ATTEMPT_KIND.SUCCESS && outcome.code === ATTEMPT_CODE.OK;
}
function isBlocked(outcome) {
return outcome.kind === ATTEMPT_KIND.TERMINAL;
}
function byteUsage(usage = {}) {
const finite = (value) => Number.isFinite(value) && value >= 0 ? value : 0;
const wireBytes = finite(usage.wireBytes ?? usage.wire_bytes);
const decodedBytes = finite(usage.decodedBytes ?? usage.decoded_bytes);
const artifactBytes = finite(usage.artifactBytes ?? usage.artifact_bytes);
const explicit = finite(usage.totalBytes ?? usage.total_bytes);
return {
wireBytes,
decodedBytes,
artifactBytes,
totalBytes: explicit > 0 ? explicit : wireBytes + decodedBytes + artifactBytes,
};
}
function discoverySources(job, explicit) {
const raw = explicit?.sources ?? explicit ?? job?.discovery?.sources ?? [];
return new Set(Array.isArray(raw) ? raw : []);
}
function candidateUrl(candidate) {
if (typeof candidate === 'string') return candidate;
if (!candidate || typeof candidate !== 'object') return null;
return candidate.url ?? candidate.href ?? null;
}
function candidateKind(candidate, fallback) {
if (!candidate || typeof candidate !== 'object') return fallback;
const raw = String(
candidate.kind ?? candidate.type ?? candidate.sourceType ?? candidate.rel ?? fallback,
).toLowerCase();
if (raw.includes('rss')) return 'rss';
if (raw.includes('atom')) return 'atom';
if (raw.includes('json') || raw === 'api') return 'api';
if (raw.includes('sitemap')) return 'sitemap';
if (raw.includes('html')) return 'html';
return raw;
}
function alternativeCandidates(result) {
const lists = [
result?.alternativeCandidates,
result?.alternative_candidates,
result?.representation?.alternativeCandidates,
result?.representation?.alternative_candidates,
result?.representation?.alternatives,
];
return lists.flatMap((list) => Array.isArray(list) ? list : []);
}
function pageLinks(result) {
const links = result?.representation?.links ?? result?.links;
return Array.isArray(links) ? links : [];
}
function appendEnqueueResult(result, ledgers, setLimit) {
if (result.accepted) return;
const entry = copyLedgerEntry(result, { reason: result.reason });
if (result.reason === 'max_depth' || result.reason === 'max_frontier') {
ledgers.unvisited.push(entry);
setLimit(result.reason);
} else {
ledgers.skipped.push(entry);
}
}
function resultStatus(accepted, blocked, failed, unvisited, limit) {
if (accepted.length > 0) {
return limit || blocked.length > 0 || failed.length > 0 || unvisited.length > 0
? RUN_STATUS.PARTIAL
: RUN_STATUS.OK;
}
if (blocked.length > 0) return RUN_STATUS.BLOCKED;
return RUN_STATUS.EXHAUSTED;
}
/**
* Schedule a bounded exact-origin crawl. All network work is delegated to the
* injected robots gate and shared URL pipeline, in that order.
*/
export async function runBoundedCrawl({
job,
context,
adapters,
robotsGate,
runUrlPipeline,
limits = job?.limits ?? {},
include = job?.scope?.include ?? ['/**'],
exclude = job?.scope?.exclude ?? [],
discover,
discovery,
clock = Date.now,
sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)),
signal = context?.signal,
} = {}) {
if (!job?.target?.url || typeof robotsGate?.check !== 'function'
|| typeof runUrlPipeline !== 'function' || typeof clock !== 'function'
|| typeof sleep !== 'function') {
throw new TypeError('bounded crawl requires a job, robots gate and URL pipeline');
}
const normalizedLimits = normalizeLimits(limits);
const frontier = createFrontier({
seedUrl: job.target.url,
include,
exclude,
limits: normalizedLimits,
});
const sources = discoverySources(job, discover ?? discovery);
const ledgers = { accepted: [], skipped: [], blocked: [], failed: [], unvisited: [] };
const usage = {
wireBytes: 0,
decodedBytes: 0,
artifactBytes: 0,
totalBytes: 0,
retriesUsed: 0,
redirectsUsed: 0,
};
const startedAt = clock();
const deadline = startedAt + normalizedLimits.wallMs;
let limit = null;
let pipelineCalls = 0;
let nextPageStartAt = startedAt;
let retriesRemaining = normalizedLimits.retriesPerAdapter;
let redirectsRemaining = normalizedLimits.maxRedirects;
const seenRobotsSitemaps = new Set();
const setLimit = (reason) => {
if (limit === null) {
limit = reason === 'max_depth' ? 'max_depth'
: reason === 'max_frontier' ? 'max_frontier'
: reason;
}
};
const recordEnqueue = (candidate, metadata) => {
const result = frontier.enqueue(candidate, metadata);
appendEnqueueResult(result, ledgers, setLimit);
return result;
};
if (!frontier.seed.accepted) appendEnqueueResult(frontier.seed, ledgers, setLimit);
const addDiscoveries = (result, parent) => {
for (const link of pageLinks(result)) {
const url = candidateUrl(link);
if (url === null) continue;
recordEnqueue(url, {
depth: parent.depth + 1,
source: parent.url,
provenance: candidateKind(link, 'html_link'),
});
}
for (const candidate of alternativeCandidates(result)) {
const kind = candidateKind(candidate, 'alternate');
if (!sources.has(kind) && !(kind === 'alternate' && sources.has('html'))) continue;
const url = candidateUrl(candidate);
if (url === null) continue;
recordEnqueue(url, {
depth: parent.depth + 1,
source: parent.url,
provenance: kind,
});
}
};
let stop = false;
while (!stop && frontier.size > 0) {
if (signal?.aborted) {
setLimit('aborted');
break;
}
if (clock() >= deadline) {
setLimit('max_time');
break;
}
const running = [];
let batchRetryAllowance = retriesRemaining;
let batchRedirectAllowance = redirectsRemaining;
while (!stop && running.length < normalizedLimits.concurrency && frontier.size > 0) {
const entry = frontier.dequeue();
if (signal?.aborted) {
ledgers.unvisited.push(copyLedgerEntry(entry, { reason: 'aborted' }));
setLimit('aborted');
stop = true;
break;
}
if (clock() >= deadline) {
ledgers.unvisited.push(copyLedgerEntry(entry, { reason: 'max_time' }));
setLimit('max_time');
stop = true;
break;
}
let robots;
try {
robots = await robotsGate.check(entry.url, {
runId: context?.runId ?? context?.run?.id,
signal,
});
} catch {
robots = { kind: ATTEMPT_KIND.TERMINAL, code: ATTEMPT_CODE.ROBOTS_DENIED };
}
if (!robots || robots.kind !== ATTEMPT_KIND.SUCCESS) {
ledgers.blocked.push(copyLedgerEntry(entry, {
reason: robots?.code ?? ATTEMPT_CODE.ROBOTS_DENIED,
}));
continue;
}
if (sources.has('sitemap') && Array.isArray(robots.sitemaps)) {
for (const sitemap of robots.sitemaps) {
if (seenRobotsSitemaps.has(sitemap)) continue;
seenRobotsSitemaps.add(sitemap);
recordEnqueue(sitemap, {
depth: entry.depth + 1,
source: entry.url,
provenance: 'robots_sitemap',
});
}
}
// Policy/robots are gates, not pages. Page/byte caps are checked after them.
if (pipelineCalls >= normalizedLimits.maxPages) {
ledgers.unvisited.push(copyLedgerEntry(entry, { reason: 'max_pages' }));
setLimit('max_pages');
stop = true;
break;
}
if (usage.totalBytes >= normalizedLimits.maxTotalBytes) {
ledgers.unvisited.push(copyLedgerEntry(entry, { reason: 'max_total_bytes' }));
setLimit('max_total_bytes');
stop = true;
break;
}
const crawlDelayMs = Number.isFinite(robots.crawlDelayMs) && robots.crawlDelayMs >= 0
? robots.crawlDelayMs
: 0;
const effectiveDelayMs = Math.max(normalizedLimits.delayMs, crawlDelayMs);
const now = clock();
const waitMs = Math.max(0, nextPageStartAt - now);
if (now + waitMs >= deadline) {
ledgers.unvisited.push(copyLedgerEntry(entry, { reason: 'max_time' }));
setLimit('max_time');
stop = true;
break;
}
if (waitMs > 0) {
try {
await sleep(waitMs, { signal });
} catch {
ledgers.unvisited.push(copyLedgerEntry(entry, { reason: 'aborted' }));
setLimit('aborted');
stop = true;
break;
}
}
nextPageStartAt = now + waitMs + effectiveDelayMs;
pipelineCalls += 1;
const remainingWallMs = Math.max(1, Math.floor(deadline - clock()));
const retryAllowance = batchRetryAllowance;
const redirectAllowance = batchRedirectAllowance;
batchRetryAllowance = 0;
batchRedirectAllowance = 0;
const pageJob = {
...job,
kind: 'url',
target: { ...job.target, url: entry.url },
limits: {
...job.limits,
wallMs: Math.min(job.limits?.wallMs ?? remainingWallMs, remainingWallMs),
retriesPerAdapter: retryAllowance,
maxRedirects: redirectAllowance,
},
};
const promise = Promise.resolve()
.then(() => runUrlPipeline({ job: pageJob, context, adapters }))
.then((result) => ({ entry, result }))
.catch(() => ({
entry,
result: {
outcome: { kind: ATTEMPT_KIND.BROKEN, code: ATTEMPT_CODE.ADAPTER_CRASH },
},
}));
running.push(promise);
}
const completed = await Promise.all(running);
for (const { entry, result } of completed) {
const outcome = outcomeOf(result);
const acquisitionAttempts = Array.isArray(result?.timeline)
? result.timeline.filter((attempt) => attempt?.type !== 'transform')
: [];
const retriesUsed = Math.max(0, acquisitionAttempts.length - 1);
const redirectsUsed = acquisitionAttempts.reduce((total, attempt) => (
total + (Array.isArray(attempt?.http?.redirect_chain) ? attempt.http.redirect_chain.length : 0)
), 0);
usage.retriesUsed += retriesUsed;
usage.redirectsUsed += redirectsUsed;
retriesRemaining = Math.max(0, retriesRemaining - retriesUsed);
redirectsRemaining = Math.max(0, redirectsRemaining - redirectsUsed);
const pageUsage = byteUsage(result?.usage);
const nextTotal = usage.totalBytes + pageUsage.totalBytes;
usage.wireBytes += pageUsage.wireBytes;
usage.decodedBytes += pageUsage.decodedBytes;
usage.artifactBytes += pageUsage.artifactBytes;
usage.totalBytes = nextTotal;
if (nextTotal > normalizedLimits.maxTotalBytes) {
ledgers.blocked.push(copyLedgerEntry(entry, { reason: ATTEMPT_CODE.HARD_LIMIT }));
setLimit('max_total_bytes');
stop = true;
continue;
}
if (isAccepted(outcome)) {
ledgers.accepted.push(copyLedgerEntry(entry, {
reason: ATTEMPT_CODE.OK,
requestedUrl: entry.url,
effectiveUrl: result?.effectiveUrl ?? result?.effective_url ?? entry.url,
source_hash: result?.sourceRef?.hash ?? result?.source_hash ?? null,
artifact_hash: result?.artifactRef?.hash ?? result?.artifact_hash ?? null,
usage: pageUsage,
}));
addDiscoveries(result, entry);
} else if (isBlocked(outcome)) {
ledgers.blocked.push(copyLedgerEntry(entry, { reason: outcome.code }));
} else {
ledgers.failed.push(copyLedgerEntry(entry, { reason: outcome.code }));
}
}
if (clock() > deadline) {
setLimit('max_time');
stop = true;
}
}
const remainingReason = limit ?? 'not_visited';
for (const entry of frontier.drain()) {
ledgers.unvisited.push(copyLedgerEntry(entry, { reason: remainingReason }));
}
const status = resultStatus(
ledgers.accepted,
ledgers.blocked,
ledgers.failed,
ledgers.unvisited,
limit,
);
const code = status === RUN_STATUS.OK ? ATTEMPT_CODE.OK
: status === RUN_STATUS.PARTIAL ? 'partial'
: status === RUN_STATUS.BLOCKED
? ledgers.blocked[0]?.reason ?? ATTEMPT_CODE.HARD_LIMIT
: 'exhausted';
const ledger = Object.entries(ledgers).flatMap(([state, entries]) => (
entries.map((entry) => ({ state, ...entry }))
));
return {
status,
code,
limit,
...ledgers,
ledger,
usage,
pagesAttempted: pipelineCalls,
};
}
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Strict render-only Playwright helper. It is never launched without a proven sandbox."""
from __future__ import annotations
import asyncio
import hashlib
import json
import os
from pathlib import Path
import sys
MAX_INPUT_BYTES = 64 * 1024
MAX_DOM_BYTES = 5 * 1024 * 1024
MAX_WAIT_MS = 5_000
MAX_SCROLL_STEPS = 10
MAX_SCROLL_Y = 2_000
SAFE_KEYS = {
"version", "id", "operation", "url", "output_path", "wait_ms",
"scroll_steps", "scroll_y", "proxy",
}
def response(request_id: str, ok: bool, **fields: object) -> None:
value = {"version": 1, "id": request_id, "ok": ok, **fields}
sys.stdout.write(json.dumps(value, separators=(",", ":")) + "\n")
def contained_output(raw_path: object) -> Path:
if not isinstance(raw_path, str) or not raw_path:
raise ValueError("invalid output path")
candidate = Path(raw_path)
if not candidate.is_absolute():
raise ValueError("output path must be absolute")
root = Path.cwd().resolve(strict=True)
parent = candidate.parent.resolve(strict=True)
if parent != root and root not in parent.parents:
raise ValueError("output escaped scratch")
if candidate.exists() or candidate.is_symlink():
raise ValueError("output already exists")
return candidate
def validate(request: object) -> dict[str, object]:
if not isinstance(request, dict) or set(request) - SAFE_KEYS:
raise ValueError("invalid request")
request_id = request.get("id")
if not isinstance(request_id, str) or not request_id or len(request_id) > 128:
raise ValueError("invalid request id")
if request.get("version") != 1:
raise ValueError("invalid version")
if request.get("operation") != "render":
return {"id": request_id, "unsupported": True}
url = request.get("url")
if not isinstance(url, str) or len(url) > 8_192 or not url.startswith(("http://", "https://")):
raise ValueError("invalid URL")
wait_ms = request.get("wait_ms", 0)
scroll_steps = request.get("scroll_steps", 0)
scroll_y = request.get("scroll_y", 0)
if not isinstance(wait_ms, int) or not 0 <= wait_ms <= MAX_WAIT_MS:
raise ValueError("invalid wait")
if not isinstance(scroll_steps, int) or not 0 <= scroll_steps <= MAX_SCROLL_STEPS:
raise ValueError("invalid scroll steps")
if not isinstance(scroll_y, int) or not 0 <= scroll_y <= MAX_SCROLL_Y:
raise ValueError("invalid scroll distance")
proxy = request.get("proxy")
if not isinstance(proxy, dict) or set(proxy) != {"server", "username", "password"}:
raise ValueError("invalid proxy")
if not all(isinstance(proxy[key], str) and proxy[key] for key in proxy):
raise ValueError("invalid proxy")
return {**request, "output": contained_output(request.get("output_path"))}
async def render(request: dict[str, object]) -> dict[str, object]:
from playwright.async_api import async_playwright
browser = None
context = None
async with async_playwright() as playwright:
try:
browser = await playwright.chromium.launch(
headless=True,
proxy=request["proxy"],
args=["--disable-quic"],
)
context = await browser.new_context(
accept_downloads=False,
service_workers="block",
permissions=[],
)
async def route_handler(route: object, playwright_request: object) -> None:
method = playwright_request.method
url = playwright_request.url
if method not in {"GET", "HEAD"} or not url.startswith(("http://", "https://")):
await route.abort()
return
await route.continue_()
await context.route("**/*", route_handler)
await context.route_web_socket("**/*", lambda route: route.close())
page = await context.new_page()
page.on("download", lambda download: asyncio.create_task(download.cancel()))
page.on("popup", lambda popup: asyncio.create_task(popup.close()))
await page.goto(
str(request["url"]),
wait_until="domcontentloaded",
timeout=15_000,
)
wait_ms = int(request["wait_ms"])
if wait_ms:
await page.wait_for_timeout(wait_ms)
for _ in range(int(request["scroll_steps"])):
await page.mouse.wheel(0, int(request["scroll_y"]))
dom = (await page.content()).encode("utf-8")
if not dom or len(dom) > MAX_DOM_BYTES:
raise ValueError("rendered DOM size is invalid")
output = request["output"]
temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp")
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(descriptor, "wb") as handle:
handle.write(dom)
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, output)
finally:
if temporary.exists():
temporary.unlink()
return {
"output_path": str(output),
"source_hash": "sha256:" + hashlib.sha256(dom).hexdigest(),
"bytes": len(dom),
"final_url": page.url,
}
finally:
if context is not None:
await context.close()
if browser is not None:
await browser.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):
response("invalid", False, code="invalid_request")
return 0
try:
request = json.loads(raw)
validated = validate(request)
except (json.JSONDecodeError, OSError, TypeError, ValueError):
request_id = request.get("id", "invalid") if isinstance(locals().get("request"), dict) else "invalid"
response(str(request_id), False, code="invalid_request")
return 0
if validated.get("unsupported"):
response(str(validated["id"]), False, code="unsupported_operation")
return 0
try:
payload = asyncio.run(render(validated))
response(str(validated["id"]), True, payload=payload)
except Exception:
response(str(validated["id"]), False, code="render_failed")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+479
View File
@@ -0,0 +1,479 @@
#!/usr/bin/env python3
"""Deterministic, networkless transforms over files already stored by Lynceuz."""
from __future__ import annotations
import socket
import sys
class NetworkDenied(RuntimeError):
pass
class InputHashMismatch(RuntimeError):
pass
class HelperBoundaryError(RuntimeError):
pass
def install_network_tripwire() -> None:
def denied(*_args: object, **_kwargs: object) -> None:
raise NetworkDenied("network access is disabled")
class DeniedSocket:
def __init__(self, *_args: object, **_kwargs: object) -> None:
denied()
socket.socket = DeniedSocket # type: ignore[assignment]
socket.create_connection = denied # type: ignore[assignment]
socket.getaddrinfo = denied # type: ignore[assignment]
socket.gethostbyname = denied # type: ignore[assignment]
socket.gethostbyname_ex = denied # type: ignore[assignment]
socket.gethostbyaddr = denied # type: ignore[assignment]
install_network_tripwire()
try:
from bs4 import BeautifulSoup, NavigableString, Tag, __version__ as BS4_VERSION
except Exception: # optional capability: absence is reported, not fatal to core
BeautifulSoup = None # type: ignore[assignment]
NavigableString = None # type: ignore[assignment]
Tag = None # type: ignore[assignment]
BS4_VERSION = None
import hashlib
import json
import math
import os
import re
import stat
from pathlib import Path
from typing import Any
from urllib.parse import urljoin, urlsplit, urlunsplit
MAX_REQUEST_BYTES = 128 * 1024
MAX_INPUT_BYTES = 16 * 1024 * 1024
MAX_OUTPUT_BYTES = 2 * 1024 * 1024
OPS = {"self_check", "parse_html", "extract_schema"}
SPACE = re.compile(r"[ \t\f\v]+")
BLANKS = re.compile(r"\n{3,}")
SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
def response(request_id: str, ok: bool, **fields: Any) -> dict[str, Any]:
return {"version": 1, "id": request_id, "ok": ok, **fields}
def failure(request_id: str, code: str, details: dict[str, Any] | None = None) -> dict[str, Any]:
fields: dict[str, Any] = {"code": code}
if details is not None:
fields["details"] = details
return response(request_id, False, **fields)
def emit(payload: dict[str, Any]) -> None:
data = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
sys.stdout.write(data + "\n")
sys.stdout.flush()
def self_check(request_id: str) -> dict[str, Any]:
if BeautifulSoup is None:
return failure(request_id, "dependency_unavailable", {"parser": "beautifulsoup4"})
return response(
request_id,
True,
payload={
"helper_version": "1",
"network_tripwire": True,
"parser": {"name": "beautifulsoup4", "version": BS4_VERSION},
"python": sys.version.split()[0],
"isolated": bool(sys.flags.isolated),
},
)
def normalized_url(value: str | None, base_url: str) -> str | None:
if not value or len(value) > 4096:
return None
try:
split = urlsplit(urljoin(base_url, value.strip()))
except ValueError:
return None
if split.scheme not in {"http", "https"} or not split.hostname:
return None
if split.username or split.password:
return None
return urlunsplit((split.scheme, split.netloc, split.path or "/", split.query, ""))
def clean_text(value: str) -> str:
lines = [SPACE.sub(" ", line).strip() for line in value.replace("\r", "\n").split("\n")]
return BLANKS.sub("\n\n", "\n".join(line for line in lines if line)).strip()
def visible_text(node: Any) -> str:
return clean_text(node.get_text("\n", strip=True))
def inline_markdown(node: Any, base_url: str) -> str:
output: list[str] = []
for child in node.children:
if NavigableString is not None and isinstance(child, NavigableString):
output.append(SPACE.sub(" ", str(child)))
continue
if Tag is None or not isinstance(child, Tag):
continue
name = child.name.lower()
if name in {"script", "style", "template", "noscript"}:
continue
text = inline_markdown(child, base_url).strip()
if name == "a":
target = normalized_url(child.get("href"), base_url)
output.append(f"[{text}]({target})" if text and target else text)
elif name in {"strong", "b"} and text:
output.append(f"**{text}**")
elif name in {"em", "i"} and text:
output.append(f"*{text}*")
elif name == "code" and text:
output.append(f"`{text}`")
elif name == "br":
output.append("\n")
else:
output.append(text)
return SPACE.sub(" ", "".join(output)).strip()
def markdown(node: Any, base_url: str) -> str:
blocks: list[str] = []
for child in node.descendants:
if Tag is None or not isinstance(child, Tag):
continue
name = child.name.lower()
if name in {"script", "style", "template", "noscript"}:
continue
if name in {"h1", "h2", "h3", "h4", "h5", "h6"}:
text = inline_markdown(child, base_url)
if text:
blocks.append(f"{'#' * int(name[1])} {text}")
elif name in {"p", "blockquote"}:
text = inline_markdown(child, base_url)
if text:
blocks.append(f"> {text}" if name == "blockquote" else text)
elif name == "li":
text = inline_markdown(child, base_url)
if text:
blocks.append(f"- {text}")
if not blocks:
text = visible_text(node)
if text:
blocks.append(text)
return "\n\n".join(blocks).strip()
def json_ld_documents(soup: Any) -> list[Any]:
documents: list[Any] = []
for tag in soup.find_all("script"):
media_type = str(tag.get("type", "")).split(";", 1)[0].strip().lower()
if media_type != "application/ld+json":
continue
raw = tag.string if tag.string is not None else tag.get_text()
if not raw or len(raw) > MAX_INPUT_BYTES:
continue
try:
value = json.loads(raw)
except (TypeError, ValueError):
continue
if isinstance(value, (dict, list)):
documents.append(value)
return documents
def parsed_html(raw: bytes, base_url: str) -> tuple[Any, dict[str, Any]]:
if BeautifulSoup is None:
raise RuntimeError("dependency_unavailable")
soup = BeautifulSoup(raw.decode("utf-8", errors="replace"), "html.parser")
json_ld = json_ld_documents(soup)
title = clean_text(soup.title.get_text(" ", strip=True)) if soup.title else ""
canonical_url = None
canonical = soup.find("link", rel=lambda value: value and "canonical" in value)
if canonical is not None:
canonical_url = normalized_url(canonical.get("href"), base_url)
metadata: dict[str, str] = {}
for tag in soup.find_all("meta"):
key = tag.get("name") or tag.get("property") or tag.get("itemprop")
content = tag.get("content")
if isinstance(key, str) and isinstance(content, str) and len(metadata) < 128:
metadata[key.strip().lower()] = clean_text(content)[:4096]
alternatives: dict[tuple[str, str], dict[str, str]] = {}
for tag in soup.find_all("link"):
rel_values = tag.get("rel") or []
if isinstance(rel_values, str):
rel_values = rel_values.split()
if "alternate" not in {str(value).lower() for value in rel_values}:
continue
target = normalized_url(tag.get("href"), base_url)
media_type = str(tag.get("type") or "text/html").strip().lower()
if target:
alternatives[(media_type, target)] = {"type": media_type, "url": target}
links = {
target
for tag in soup.find_all("a")
if (target := normalized_url(tag.get("href"), base_url)) is not None
}
for tag in soup.find_all(["script", "style", "template", "noscript"]):
tag.decompose()
main = soup.find("main") or soup.find("article") or soup.body or soup
result = {
"title": title,
"canonical_candidate": canonical_url,
"text": visible_text(main),
"markdown": markdown(main, base_url),
"links": sorted(links),
"metadata": dict(sorted(metadata.items())),
"alternate_candidates": [alternatives[key] for key in sorted(alternatives)],
"jsonld": json_ld,
}
return soup, result
def follow_path(value: Any, path: list[Any]) -> tuple[bool, Any]:
current = value
for segment in path:
if isinstance(segment, int) and isinstance(current, list) and 0 <= segment < len(current):
current = current[segment]
elif isinstance(segment, str) and isinstance(current, dict) and segment in current:
current = current[segment]
else:
return False, None
return True, current
def primitive_matches(value: Any, expected: str | None) -> bool:
if expected is None:
return value is None or isinstance(value, (str, int, float, bool))
if expected == "string":
return isinstance(value, str)
if expected == "number":
return isinstance(value, (int, float)) and not isinstance(value, bool)
if expected == "boolean":
return isinstance(value, bool)
if expected == "null":
return value is None
return False
def coerce_primitive(value: Any, expected: str | None) -> Any:
if expected is None:
return value
if expected == "number" and isinstance(value, str):
if not re.fullmatch(r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", value.strip()):
return value
try:
number = float(value.strip())
except ValueError:
return value
if not math.isfinite(number):
return value
return int(number) if number.is_integer() else number
if expected == "boolean" and isinstance(value, str):
lowered = value.strip().lower()
if lowered in {"true", "1", "yes"}:
return True
if lowered in {"false", "0", "no"}:
return False
return value
def schema_values(soup: Any, documents: list[Any], schema: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
result: dict[str, Any] = {}
invalid: list[str] = []
for name, field in schema["fields"].items():
many = bool(field.get("many", False))
required = bool(field.get("required", False))
expected_type = field.get("type")
values: list[Any] = []
if field["source"] == "css":
try:
matches = soup.select(field["selector"])
except Exception:
invalid.append(name)
continue
for match in matches:
if field["take"] == "text":
value: Any = clean_text(match.get_text(" ", strip=True))
else:
value = match.get(field["take"][1:])
if isinstance(value, list):
value = " ".join(str(item) for item in value)
if value not in (None, ""):
values.append(coerce_primitive(value, expected_type))
else:
for document in documents:
found, value = follow_path(document, field["path"])
if found:
if many and isinstance(value, list):
values.extend(coerce_primitive(item, expected_type) for item in value)
else:
values.append(coerce_primitive(value, expected_type))
selected: Any = values if many else (values[0] if values else None)
checked = values if many else ([] if selected is None else [selected])
if checked and not all(primitive_matches(value, expected_type) for value in checked):
if required:
invalid.append(name)
continue
if not checked:
if required:
invalid.append(name)
continue
result[name] = selected
return result, sorted(set(invalid))
def input_bytes(path_value: Any, hash_value: Any) -> bytes:
if not isinstance(path_value, str) or not os.path.isabs(path_value):
raise HelperBoundaryError("invalid input path")
if not isinstance(hash_value, str) or not re.fullmatch(r"sha256:[0-9a-f]{64}", hash_value):
raise HelperBoundaryError("invalid input hash")
flags = os.O_RDONLY
if hasattr(os, "O_NOFOLLOW"):
flags |= os.O_NOFOLLOW
descriptor = os.open(path_value, flags)
try:
info = os.fstat(descriptor)
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_INPUT_BYTES:
raise HelperBoundaryError("invalid input file")
with os.fdopen(descriptor, "rb", closefd=False) as handle:
data = handle.read(MAX_INPUT_BYTES + 1)
finally:
os.close(descriptor)
if len(data) > MAX_INPUT_BYTES:
raise HelperBoundaryError("input too large")
if "sha256:" + hashlib.sha256(data).hexdigest() != hash_value:
raise InputHashMismatch("input hash mismatch")
return data
def write_output(path_value: Any, value: Any) -> tuple[str, int]:
if not isinstance(path_value, str) or not os.path.isabs(path_value):
raise HelperBoundaryError("invalid output path")
cwd = Path.cwd().resolve(strict=True)
path = Path(path_value)
parent = path.parent.resolve(strict=True)
try:
parent.relative_to(cwd)
except ValueError as error:
raise HelperBoundaryError("output path escapes scratch") from error
data = (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n").encode()
if len(data) > MAX_OUTPUT_BYTES:
raise HelperBoundaryError("output too large")
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
if hasattr(os, "O_NOFOLLOW"):
flags |= os.O_NOFOLLOW
descriptor = os.open(path, flags, 0o600)
try:
with os.fdopen(descriptor, "wb", closefd=False) as handle:
handle.write(data)
handle.flush()
os.fsync(handle.fileno())
finally:
os.close(descriptor)
return str(path), len(data)
def handle(request: dict[str, Any]) -> dict[str, Any]:
request_id = request.get("id")
if request.get("version") != 1 or not isinstance(request_id, str) or not SAFE_ID.fullmatch(request_id):
return failure("invalid", "parse_failed")
operation = request.get("operation")
if operation not in OPS:
return failure(request_id, "unsupported")
if operation == "self_check":
if set(request) != {"version", "id", "operation"}:
return failure(request_id, "parse_failed", {"reason": "invalid_request"})
return self_check(request_id)
allowed = {"version", "id", "operation", "input_path", "input_hash", "base_url", "output_path"}
if operation == "extract_schema":
allowed.add("schema")
if not set(request).issubset(allowed):
return failure(request_id, "parse_failed", {"reason": "invalid_request"})
if BeautifulSoup is None:
return failure(request_id, "dependency_unavailable", {"parser": "beautifulsoup4"})
base_url = request.get("base_url")
if not isinstance(base_url, str) or normalized_url(base_url, base_url) is None:
return failure(request_id, "parse_failed")
try:
raw = input_bytes(request.get("input_path"), request.get("input_hash"))
soup, parsed = parsed_html(raw, base_url)
if operation == "parse_html":
output_path, size = write_output(request.get("output_path"), parsed)
return response(
request_id,
True,
payload={"output_path": output_path, "bytes": size},
)
schema = request.get("schema")
if not isinstance(schema, dict):
return failure(request_id, "parse_failed")
values, invalid = schema_values(soup, parsed["jsonld"], schema)
if invalid:
return failure(
request_id,
"required_fields_missing",
{"reason": "required_fields_missing", "missing": invalid},
)
output_path, size = write_output(request.get("output_path"), values)
return response(
request_id,
True,
payload={"output_path": output_path, "bytes": size},
)
except InputHashMismatch:
return failure(request_id, "hash_mismatch")
except (HelperBoundaryError, OSError, RuntimeError, TypeError):
return failure(request_id, "adapter_error")
except ValueError:
return failure(request_id, "parse_failed")
def read_request() -> dict[str, Any]:
line = sys.stdin.buffer.readline(MAX_REQUEST_BYTES + 1)
if not line or len(line) > MAX_REQUEST_BYTES or not line.endswith(b"\n"):
raise ValueError("invalid request framing")
if sys.stdin.buffer.read(1):
raise ValueError("extra request data")
value = json.loads(line)
if not isinstance(value, dict):
raise ValueError("request must be an object")
return value
def main() -> int:
if sys.argv[1:] == ["--self-check"]:
result = self_check("cli-self-check")
if result.get("ok") and isinstance(result.get("payload"), dict):
result["python"] = result["payload"].get("python")
emit(result)
return 0 if BeautifulSoup is not None else 3
if sys.argv[1:]:
emit(failure("invalid", "unsupported"))
return 0
try:
emit(handle(read_request()))
except (json.JSONDecodeError, UnicodeError, ValueError):
emit(failure("invalid", "parse_failed"))
return 0
if __name__ == "__main__":
raise SystemExit(main())
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env node
import { lookup as dnsLookup } from 'node:dns/promises';
import { constants as FS_CONSTANTS } from 'node:fs';
import { access } from 'node:fs/promises';
import { request as httpRequest } from 'node:http';
import { request as httpsRequest } from 'node:https';
import { resolve } from 'node:path';
import { runCli } from './cli.mjs';
import { createPythonTransformAdapter } from './adapters/python-helper.mjs';
import { createProductionExecutor } from './core.mjs';
import { createEgressGateway, createNodeRequestPinned } from './network.mjs';
import { createDefaultRegistry } from './router.mjs';
import { createStorage } from './storage.mjs';
const registry = createDefaultRegistry(process.version).map((capability) => (
capability.id === 'native'
? {
...capability,
version: '1',
state: 'ready',
reason: 'native_http_ready',
commands: ['url', 'crawl', 'extract'],
}
: capability
));
async function lookupAll(hostname, { signal } = {}) {
if (signal?.aborted) throw signal.reason ?? new Error('DNS lookup aborted');
const lookup = dnsLookup(hostname, { all: true, verbatim: true });
if (!signal) return lookup;
return new Promise((resolveLookup, rejectLookup) => {
const abort = () => rejectLookup(signal.reason ?? new Error('DNS lookup aborted'));
signal.addEventListener('abort', abort, { once: true });
lookup.then(resolveLookup, rejectLookup).finally(() => signal.removeEventListener('abort', abort));
});
}
const gateway = createEgressGateway({
lookupAll,
requestPinned: createNodeRequestPinned({ httpRequest, httpsRequest }),
connectPinned: async () => { throw new Error('tunnel transport is not enabled'); },
});
const executeJob = createProductionExecutor({
gateway,
storage: (job) => createStorage({
dataRoot: job.output.dataRoot ?? resolve(process.cwd(), '.lynceuz'),
clock: Date.now,
}),
clock: Date.now,
sleep: (milliseconds) => new Promise((resolveSleep) => setTimeout(resolveSleep, milliseconds)),
// Real process only: SIGINT/SIGTERM and the run's wall deadline funnel through
// one guard that commits an interrupted manifest and exits 130/143/124.
interruption: { emitter: process, exit: (code) => process.exit(code) },
pythonAdapter: async ({ storage, job }) => {
if (!['url', 'extract', 'crawl'].includes(job.kind)) return null;
const candidates = [
'/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',
'/Library/Frameworks/Python.framework/Versions/3.10/bin/python3',
'/usr/bin/python3',
];
for (const pythonPath of candidates) {
try {
await access(pythonPath, FS_CONSTANTS.X_OK);
const adapter = createPythonTransformAdapter({ pythonPath, storage });
if ((await adapter.probe()).state === 'ready') return adapter;
} catch {
// Optional local capability: continue to the next fixed executable.
}
}
return null;
},
});
process.exitCode = await runCli(process.argv.slice(2), {
io: { stdout: process.stdout, stderr: process.stderr },
registry,
executeJob,
now: () => new Date(),
});
+310
View File
@@ -0,0 +1,310 @@
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
const READY = 'ready';
const UNAVAILABLE = 'unavailable_security_gate';
const HASH = /^sha256:[a-f0-9]{64}$/u;
const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/u;
const CHANNELS = Object.freeze(['proxy_tcp', 'direct_tcp', 'udp', 'quic']);
const RECEIPT_KEYS = Object.freeze([
'backend', 'boot_session', 'canary', 'generated_at', 'guard_proxy', 'kind', 'pf',
'reboot_verified', 'reboot_verified_at', 'schema_version', 'source_hashes', 'status',
'suite_hashes', 'uid',
]);
const RUN_OPTIONS = Object.freeze({
encoding: 'utf8',
env: Object.freeze({ LANG: 'C', LC_ALL: 'C' }),
maxBuffer: 256 * 1024,
shell: false,
timeout: 5_000,
});
function unavailable(reason, details = undefined) {
return Object.freeze({ state: UNAVAILABLE, reason, ...(details ? { details } : {}) });
}
function plainObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value)
&& Object.getPrototypeOf(value) === Object.prototype;
}
function exactKeys(value, keys) {
return plainObject(value)
&& Object.keys(value).sort().join('\0') === [...keys].sort().join('\0');
}
function validText(value, max = 512) {
return typeof value === 'string' && value.length > 0 && value.length <= max
&& !/[\0\r\n]/u.test(value);
}
function validHashes(value, expected) {
if (!plainObject(value) || !plainObject(expected)) return false;
const keys = Object.keys(expected).sort();
return keys.length > 0 && keys.length <= 32
&& exactKeys(value, keys)
&& keys.every((key) => validText(key, 128) && HASH.test(value[key]) && value[key] === expected[key]);
}
function validObservation(value, channel) {
return exactKeys(value, ['channel', 'operation_succeeded', 'response', 'response_confirmed'])
&& value.channel === channel
&& typeof value.operation_succeeded === 'boolean'
&& (value.response === null || validText(value.response, 256))
&& typeof value.response_confirmed === 'boolean'
&& (!value.response_confirmed || value.response !== null);
}
function validCanaryShape(value) {
if (!exactKeys(value, [
'detected_channels', 'exit_code', 'observations', 'passed', 'reason', 'status',
])) return false;
if (!Array.isArray(value.detected_channels) || value.detected_channels.length > CHANNELS.length
|| !value.detected_channels.every((channel) => CHANNELS.includes(channel))
|| !Number.isSafeInteger(value.exit_code) || value.exit_code < 0 || value.exit_code > 255
|| typeof value.passed !== 'boolean' || !validText(value.reason)
|| !validText(value.status, 64) || !exactKeys(value.observations, CHANNELS)) return false;
return CHANNELS.every((channel) => validObservation(value.observations[channel], channel));
}
function canaryPassed(value) {
return validCanaryShape(value)
&& value.passed === true
&& value.status === 'passed'
&& value.reason === 'containment_canary_passed'
&& value.exit_code === 0
&& value.detected_channels.length === 0
&& value.observations.proxy_tcp.response_confirmed === true
&& ['direct_tcp', 'udp', 'quic'].every(
(channel) => value.observations[channel].response_confirmed === false,
);
}
function validExpected(expected) {
return plainObject(expected)
&& expected.backend === 'pf_uid_anchor_guardproxy'
&& validText(expected.uid_name, 64)
&& Number.isSafeInteger(expected.uid) && expected.uid > 0
&& Number.isSafeInteger(expected.gid) && expected.gid > 0
&& expected.guard_proxy_host === '127.0.0.1'
&& Number.isSafeInteger(expected.guard_proxy_port)
&& expected.guard_proxy_port > 0 && expected.guard_proxy_port <= 65_535
&& validText(expected.anchor_name, 128)
&& validText(expected.anchor_path, 512) && expected.anchor_path.startsWith('/')
&& HASH.test(expected.anchor_sha256)
&& HASH.test(expected.rules_sha256)
&& validHashes(expected.source_hashes, expected.source_hashes)
&& validHashes(expected.suite_hashes, expected.suite_hashes);
}
function validReceiptShape(receipt) {
return exactKeys(receipt, RECEIPT_KEYS)
&& receipt.kind === 'lynceuz_macos_containment_receipt'
&& receipt.schema_version === 1
&& receipt.status === READY
&& validText(receipt.backend, 64)
&& ISO.test(receipt.generated_at)
&& exactKeys(receipt.uid, ['gid', 'name', 'uid'])
&& validText(receipt.uid.name, 64)
&& Number.isSafeInteger(receipt.uid.uid) && receipt.uid.uid > 0
&& Number.isSafeInteger(receipt.uid.gid) && receipt.uid.gid > 0
&& exactKeys(receipt.guard_proxy, ['host', 'port'])
&& receipt.guard_proxy.host === '127.0.0.1'
&& Number.isSafeInteger(receipt.guard_proxy.port)
&& receipt.guard_proxy.port > 0 && receipt.guard_proxy.port <= 65_535
&& exactKeys(receipt.pf, ['anchor_name', 'anchor_path', 'anchor_sha256', 'rules_sha256'])
&& validText(receipt.pf.anchor_name, 128)
&& validText(receipt.pf.anchor_path, 512) && receipt.pf.anchor_path.startsWith('/')
&& HASH.test(receipt.pf.anchor_sha256)
&& HASH.test(receipt.pf.rules_sha256)
&& validText(receipt.boot_session, 512)
&& typeof receipt.reboot_verified === 'boolean'
&& ISO.test(receipt.reboot_verified_at)
&& validCanaryShape(receipt.canary)
&& plainObject(receipt.source_hashes)
&& plainObject(receipt.suite_hashes);
}
function receiptMatchesExpected(receipt, expected) {
return receipt.backend === expected.backend
&& receipt.uid.name === expected.uid_name
&& receipt.uid.uid === expected.uid
&& receipt.uid.gid === expected.gid
&& receipt.guard_proxy.host === expected.guard_proxy_host
&& receipt.guard_proxy.port === expected.guard_proxy_port
&& receipt.pf.anchor_name === expected.anchor_name
&& receipt.pf.anchor_path === expected.anchor_path
&& receipt.pf.anchor_sha256 === expected.anchor_sha256
&& receipt.pf.rules_sha256 === expected.rules_sha256
&& validHashes(receipt.source_hashes, expected.source_hashes)
&& validHashes(receipt.suite_hashes, expected.suite_hashes);
}
export function safeRules(text, expected) {
if (typeof text !== 'string' || text.length === 0 || text.length > 256 * 1024
|| /^\s*set\s+skip\s+on\s+lo0\b/imu.test(text)) return false;
const lines = text.split(/\r?\n/u)
.map((line) => line.replace(/#.*$/u, '').trim())
.filter(Boolean);
const pass = lines.filter((line) => /^pass\b/iu.test(line));
const uid = String(expected.uid).replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
const port = String(expected.guard_proxy_port);
// Real pfctl prints `port = <port>` / `user = <uid>`, places `user` at the end of the
// line, and appends a `flags ... keep state` tail. The older middle-`user` form (and the
// spelling without `=`) stays accepted; the destination is still pinned to 127.0.0.1:<port>.
const dstOld = `from\\s+any\\s+user\\s*=?\\s*${uid}\\s+to\\s+127\\.0\\.0\\.1\\s+port\\s*=?\\s*${port}`;
const dstNew = `from\\s+any\\s+to\\s+127\\.0\\.0\\.1\\s+port\\s*=?\\s*${port}\\s+user\\s*=?\\s*${uid}`;
const tail = '(?:\\s+flags\\s+\\S+)?(?:\\s+(?:keep|modulate)\\s+state)?';
const allowed = new RegExp(
`^pass\\s+(?:(?:out|quick|on\\s+lo0)\\s+)*inet\\s+proto\\s+tcp\\s+(?:${dstOld}|${dstNew})${tail}$`,
'iu',
);
if (pass.length !== 1 || !allowed.test(pass[0]) || !/\bquick\b/iu.test(pass[0])) return false;
// Blocks: the real `inet all user = <uid>` shorthand alongside the old `inet from any user <uid> to any`.
const blockFor = (family) => new RegExp(
`^block\\s+drop\\s+(?:(?:out|quick)\\s+)*${family}\\s+(?:from\\s+any\\s+user\\s*=?\\s*${uid}\\s+to\\s+any|all\\s+user\\s*=?\\s*${uid})$`,
'iu',
);
const block4 = blockFor('inet');
const block6 = blockFor('inet6');
return lines.some((line) => block4.test(line) && /\bquick\b/iu.test(line))
&& lines.some((line) => block6.test(line) && /\bquick\b/iu.test(line));
}
function sha256(value) {
return `sha256:${createHash('sha256').update(value).digest('hex')}`;
}
function defaultRunner(executable, argv, options) {
return spawnSync(executable, argv, options);
}
async function runReadOnly(runner, executable, argv) {
let result;
try {
result = await runner(executable, Object.freeze([...argv]), RUN_OPTIONS);
} catch (error) {
throw Object.assign(new Error('read_only_command_unavailable'), { cause: error });
}
if (!plainObject(result) || result.status !== 0 || result.signal != null || result.error) {
throw new Error('read_only_command_unavailable');
}
const stdout = typeof result.stdout === 'string'
? result.stdout
: Buffer.isBuffer(result.stdout) ? result.stdout.toString('utf8') : '';
const stderr = typeof result.stderr === 'string'
? result.stderr
: Buffer.isBuffer(result.stderr) ? result.stderr.toString('utf8') : '';
if (Buffer.byteLength(stdout) > RUN_OPTIONS.maxBuffer
|| Buffer.byteLength(stderr) > RUN_OPTIONS.maxBuffer) {
throw new Error('read_only_command_output_limit');
}
return stdout.trim();
}
// Root reads PF facts directly. A non-root gate reads the SAME two calls through a
// password-less, no-exec sudo path (ops/macos/sudoers/lynceuz-browser). If `sudo -n` is
// denied, runReadOnly throws like any other failure and the caller stays fail-closed.
function pfctlReader(geteuid) {
const asRoot = typeof geteuid === 'function' && geteuid() === 0;
return (argv) => asRoot
? { executable: '/sbin/pfctl', argv }
: { executable: '/usr/bin/sudo', argv: ['-n', '/sbin/pfctl', ...argv] };
}
export async function inspectMacosContainment({
expected, runner = defaultRunner, geteuid = typeof process.geteuid === 'function' ? () => process.geteuid() : undefined,
} = {}) {
if (!validExpected(expected) || typeof runner !== 'function') {
return unavailable('containment_configuration_invalid');
}
const pfctl = pfctlReader(geteuid);
const pfInfoCall = pfctl(['-s', 'info']);
const rulesCall = pfctl(['-a', expected.anchor_name, '-sr']);
try {
const [uidText, gidText, pfInfo, rulesText, bootSession, anchorHashText] = await Promise.all([
runReadOnly(runner, '/usr/bin/id', ['-u', expected.uid_name]),
runReadOnly(runner, '/usr/bin/id', ['-g', expected.uid_name]),
runReadOnly(runner, pfInfoCall.executable, pfInfoCall.argv),
runReadOnly(runner, rulesCall.executable, rulesCall.argv),
runReadOnly(runner, '/usr/sbin/sysctl', ['-n', 'kern.boottime']),
runReadOnly(runner, '/usr/bin/shasum', ['-a', '256', expected.anchor_path]),
]);
const uid = Number(uidText);
const gid = Number(gidText);
const anchorDigest = /^([a-f0-9]{64})(?:\s|$)/u.exec(anchorHashText)?.[1];
if (!Number.isSafeInteger(uid) || uid <= 0 || !Number.isSafeInteger(gid) || gid <= 0
|| !anchorDigest || !bootSession) throw new Error('read_only_command_parse_failed');
return Object.freeze({
uid: Object.freeze({ name: expected.uid_name, uid, gid, dedicated: true }),
pf: Object.freeze({
active: /(?:^|\n)Status:\s+Enabled(?:\s|$)|^Enabled$/imu.test(pfInfo),
anchor_name: expected.anchor_name,
anchor_path: expected.anchor_path,
anchor_sha256: `sha256:${anchorDigest}`,
rules_sha256: sha256(rulesText),
rules_text: rulesText,
}),
boot_session: bootSession,
});
} catch (error) {
return unavailable('containment_system_facts_unavailable', {
failure: error?.message === 'read_only_command_output_limit' ? 'output_limit' : 'permission_or_read_failure',
});
}
}
export async function verifyMacosContainmentReceipt({
receipt,
expected,
system,
runner,
canary = null,
now = Date.now,
maxAgeMs = 5 * 60_000,
} = {}) {
if (receipt == null) return unavailable('containment_receipt_missing');
if (!validExpected(expected) || typeof now !== 'function'
|| !Number.isSafeInteger(maxAgeMs) || maxAgeMs <= 0) {
return unavailable('containment_configuration_invalid');
}
if (!validReceiptShape(receipt)) return unavailable('containment_receipt_invalid');
if (!receiptMatchesExpected(receipt, expected)) return unavailable('containment_receipt_tampered');
const nowMs = Number(now());
const generatedMs = Date.parse(receipt.generated_at);
const rebootVerifiedMs = Date.parse(receipt.reboot_verified_at);
if (!Number.isFinite(nowMs) || !Number.isFinite(generatedMs) || generatedMs > nowMs
|| nowMs - generatedMs > maxAgeMs) return unavailable('containment_receipt_stale');
if (receipt.reboot_verified !== true || !Number.isFinite(rebootVerifiedMs)
|| rebootVerifiedMs > nowMs || nowMs - rebootVerifiedMs > maxAgeMs) {
return unavailable('containment_reboot_unverified');
}
const facts = system ?? await inspectMacosContainment({ expected, runner });
if (facts?.state === UNAVAILABLE) return facts;
if (!plainObject(facts) || !plainObject(facts.uid) || !plainObject(facts.pf)) {
return unavailable('containment_system_facts_unavailable');
}
if (facts.boot_session !== receipt.boot_session) {
return unavailable('containment_boot_session_mismatch');
}
if (facts.pf.active !== true) return unavailable('containment_anchor_inactive');
if (facts.uid.dedicated !== true) return unavailable('containment_uid_not_dedicated');
if (facts.uid.name !== receipt.uid.name || facts.uid.uid !== receipt.uid.uid
|| facts.uid.gid !== receipt.uid.gid) return unavailable('containment_uid_mismatch');
if (facts.pf.anchor_name !== receipt.pf.anchor_name
|| facts.pf.anchor_path !== receipt.pf.anchor_path
|| facts.pf.anchor_sha256 !== receipt.pf.anchor_sha256
|| facts.pf.rules_sha256 !== receipt.pf.rules_sha256) {
return unavailable('containment_anchor_mismatch');
}
if (!safeRules(facts.pf.rules_text, expected)) {
return unavailable('containment_pf_rules_unsafe');
}
if (canary == null) return unavailable('containment_canary_missing');
if (!canaryPassed(receipt.canary) || !canaryPassed(canary)) {
return unavailable('containment_canary_failed');
}
return Object.freeze({ state: READY, reason: 'containment_ready' });
}
+503
View File
@@ -0,0 +1,503 @@
import { deepFreeze } from './contracts.mjs';
import { connect as connectTcp } from 'node:net';
import {
PolicyError,
authorizeResolvedTarget,
classifyIpAddress,
parsePublicUrl,
} from './policy.mjs';
const PURPOSES = new Set(['robots', 'page', 'subresource', 'search-api', 'cloud-api']);
const METHODS = new Set(['GET', 'HEAD']);
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
const MAX_REQUEST_HEADER_BYTES = 16 * 1024;
const MAX_RESPONSE_HEADER_BYTES = 32 * 1024;
const MAX_HEADER_VALUE_BYTES = 8 * 1024;
const HEADER_TIMEOUT_MS = 10_000;
const SAFE_REQUEST_HEADERS = new Map([
['accept', 'Accept'],
['accept-encoding', 'Accept-Encoding'],
['if-modified-since', 'If-Modified-Since'],
['if-none-match', 'If-None-Match'],
['user-agent', 'User-Agent'],
]);
function policyError(code, message) {
return new PolicyError(code, message);
}
function normalizeRequestHeaders(headers) {
if (headers === undefined) return Object.freeze({});
if (!headers || typeof headers !== 'object' || Array.isArray(headers)) {
throw policyError('invalid_headers', 'request headers are invalid');
}
const normalized = {};
const seen = new Set();
let totalBytes = 0;
for (const [rawName, value] of Object.entries(headers)) {
const name = rawName.toLowerCase();
const canonicalName = SAFE_REQUEST_HEADERS.get(name);
if (!canonicalName || seen.has(name) || typeof value !== 'string') {
throw policyError('invalid_headers', 'request headers are not allowed');
}
const valueBytes = Buffer.byteLength(value);
if (valueBytes === 0 || valueBytes > MAX_HEADER_VALUE_BYTES
|| /[\u0000-\u001f\u007f]/u.test(value)) {
throw policyError('invalid_headers', 'request header value is invalid');
}
totalBytes += Buffer.byteLength(canonicalName) + valueBytes + 4;
if (totalBytes > MAX_REQUEST_HEADER_BYTES) {
throw policyError('invalid_headers', 'request headers are too large');
}
seen.add(name);
normalized[canonicalName] = value;
}
return Object.freeze(normalized);
}
function normalizeIntent(intent) {
if (!intent || typeof intent !== 'object') throw policyError('invalid_intent', 'network intent is invalid');
if (typeof intent.runId !== 'string' || intent.runId.length === 0 || intent.runId.length > 128) {
throw policyError('invalid_intent', 'network intent run id is invalid');
}
if (!PURPOSES.has(intent.purpose) || !METHODS.has(intent.method)) {
throw policyError('invalid_intent', 'network intent authority is invalid');
}
const remaining = intent.remaining;
if (!remaining || !Number.isFinite(remaining.wallMs) || remaining.wallMs <= 0
|| !Number.isFinite(remaining.bytes) || remaining.bytes <= 0
|| !Number.isInteger(remaining.redirects) || remaining.redirects < 0) {
throw policyError('invalid_intent', 'network intent budget is invalid');
}
return {
runId: intent.runId,
purpose: intent.purpose,
url: intent.url,
method: intent.method,
headers: normalizeRequestHeaders(intent.headers),
remaining: {
wallMs: remaining.wallMs,
bytes: remaining.bytes,
redirects: remaining.redirects,
},
};
}
function validateRequestPermit(permit, method) {
if (!permit || typeof permit !== 'object' || !METHODS.has(method)
|| !['http:', 'https:'].includes(permit.protocol)
|| typeof permit.canonicalUrl !== 'string'
|| typeof permit.hostname !== 'string' || permit.hostname.length === 0
|| !Number.isInteger(permit.port) || ![80, 443].includes(permit.port)
|| typeof permit.selectedAddress !== 'string') {
throw new TypeError('pinned request requires a valid permit');
}
let target;
try {
target = new URL(permit.canonicalUrl);
} catch {
throw new TypeError('pinned request requires a valid permit');
}
const canonicalPort = Number(target.port || (target.protocol === 'https:' ? 443 : 80));
if (target.protocol !== permit.protocol || target.hostname !== permit.hostname
|| canonicalPort !== permit.port || target.username !== '' || target.password !== '') {
throw new TypeError('pinned request permit is inconsistent');
}
const selected = classifyIpAddress(permit.selectedAddress);
return { target, family: selected.family, address: permit.selectedAddress };
}
function requestHost(target) {
const defaultPort = target.protocol === 'https:' ? '443' : '80';
return target.port === '' || target.port === defaultPort
? target.hostname
: `${target.hostname}:${target.port}`;
}
function requestTimeout(permit) {
if (!Number.isFinite(permit.expiresAtMs)) return HEADER_TIMEOUT_MS;
return Math.max(1, Math.min(HEADER_TIMEOUT_MS, permit.expiresAtMs - Date.now()));
}
export function createNodeRequestPinned({ httpRequest, httpsRequest }) {
if (typeof httpRequest !== 'function' || typeof httpsRequest !== 'function') {
throw new TypeError('pinned request requires HTTP and HTTPS request functions');
}
return async function requestPinned({ permit, method, headers, signal } = {}) {
const { target, family, address } = validateRequestPermit(permit, method);
const safeHeaders = normalizeRequestHeaders(headers);
const timeoutMs = requestTimeout(permit);
const request = permit.protocol === 'https:' ? httpsRequest : httpRequest;
const lookup = (hostname, options, callback) => {
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof callback !== 'function') throw new TypeError('lookup callback is required');
queueMicrotask(() => {
if (hostname !== permit.hostname) {
callback(new Error('pinned lookup hostname mismatch'));
return;
}
if (options?.all === true) callback(null, [{ address, family }]);
else callback(null, address, family);
});
};
return new Promise((resolve, reject) => {
let settled = false;
let clientRequest;
let timer;
const finish = (action, value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener?.('abort', onAbort);
action(value);
};
const fail = (error) => finish(reject, error instanceof Error ? error : new Error('request failed'));
const onAbort = () => {
const reason = signal?.reason instanceof Error ? signal.reason : new Error('request aborted');
try {
clientRequest?.destroy?.(reason);
} catch {
fail(reason);
return;
}
fail(reason);
};
const onTimeout = () => {
const error = new Error('response header timeout');
error.code = 'ERR_RESPONSE_HEADER_TIMEOUT';
try {
clientRequest?.destroy?.(error);
} catch {
fail(error);
return;
}
fail(error);
};
if (signal?.aborted) {
onAbort();
return;
}
const options = {
protocol: permit.protocol,
hostname: permit.hostname,
port: permit.port,
path: `${target.pathname}${target.search}`,
method,
headers: { ...safeHeaders, Host: requestHost(target) },
setHost: false,
agent: false,
signal,
lookup,
maxHeaderSize: MAX_RESPONSE_HEADER_BYTES,
timeout: timeoutMs,
...(permit.protocol === 'https:' ? { servername: permit.hostname } : {}),
};
try {
clientRequest = request(options, (response) => {
const peerAddress = response?.socket?.remoteAddress;
if (typeof peerAddress !== 'string') {
response?.destroy?.();
fail(new Error('response peer address is unavailable'));
return;
}
let normalizedPeer;
try {
normalizedPeer = classifyIpAddress(peerAddress).normalized;
} catch {
response?.destroy?.();
fail(new Error('response peer address is invalid'));
return;
}
clientRequest?.setTimeout?.(0);
finish(resolve, {
statusCode: response.statusCode,
headers: response.headers ?? {},
body: response,
peerAddress: normalizedPeer,
});
});
clientRequest.once('error', fail);
if (settled) return;
signal?.addEventListener?.('abort', onAbort, { once: true });
if (signal?.aborted) {
onAbort();
return;
}
clientRequest.setTimeout?.(timeoutMs, onTimeout);
timer = setTimeout(onTimeout, timeoutMs);
clientRequest.end();
} catch (error) {
fail(error);
}
});
};
}
export function createNodeConnectPinned({ connect = connectTcp, now = Date.now } = {}) {
if (typeof connect !== 'function' || typeof now !== 'function') {
throw new TypeError('pinned connector requires a TCP connector and clock');
}
return async function connectPinned({ permit, signal } = {}) {
if (!permit || typeof permit !== 'object' || !['http:', 'https:'].includes(permit.protocol)
|| !Number.isInteger(permit.port) || ![80, 443].includes(permit.port)
|| typeof permit.selectedAddress !== 'string') {
throw new TypeError('pinned connector requires a valid permit');
}
const selected = classifyIpAddress(permit.selectedAddress);
const remainingMs = Number.isFinite(permit.expiresAtMs) ? permit.expiresAtMs - now() : 10_000;
if (remainingMs <= 0) throw policyError('permit_expired', 'network permit expired');
const timeoutMs = Math.min(10_000, remainingMs);
return new Promise((resolve, reject) => {
let socket;
let settled = false;
let timer;
const finish = (action, value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener?.('abort', onAbort);
action(value);
};
const fail = (error) => {
try { socket?.destroy?.(); } catch {}
finish(reject, error instanceof Error ? error : new Error('TCP connection failed'));
};
const onAbort = () => fail(signal?.reason ?? new Error('TCP connection aborted'));
if (signal?.aborted) {
onAbort();
return;
}
try {
socket = connect({
host: selected.normalized,
port: permit.port,
family: selected.family,
});
socket.once('connect', () => {
const peerAddress = socket.remoteAddress;
if (typeof peerAddress !== 'string') {
fail(new Error('TCP peer address is unavailable'));
return;
}
finish(resolve, { socket, peerAddress });
});
socket.once('error', fail);
signal?.addEventListener?.('abort', onAbort, { once: true });
timer = setTimeout(() => fail(new Error('TCP connection timeout')), timeoutMs);
timer.unref?.();
} catch (error) {
fail(error);
}
});
};
}
function literalRecord(target) {
if (!target.isIpLiteral) return null;
const hostname = target.hostname.startsWith('[') && target.hostname.endsWith(']')
? target.hostname.slice(1, -1)
: target.hostname;
const classified = classifyIpAddress(hostname);
return [{ address: classified.normalized, family: classified.family }];
}
function peerMatches(selectedAddress, peerAddress) {
if (typeof peerAddress !== 'string') return false;
try {
const selected = classifyIpAddress(selectedAddress);
const peer = classifyIpAddress(peerAddress);
if (selected.family === peer.family) return selected.normalized === peer.normalized;
const mapped = peer.family === 6 && peer.reason === 'ipv4-mapped'
? peer.bytes.slice(12).join('.')
: null;
return selected.family === 4 && selected.normalized === mapped;
} catch {
return false;
}
}
function redirectLocation(headers) {
if (!headers || typeof headers !== 'object') return null;
const matches = Object.entries(headers).filter(([name]) => name.toLowerCase() === 'location');
if (matches.length !== 1) return null;
const value = matches[0][1];
if (Array.isArray(value)) {
if (value.length !== 1 || typeof value[0] !== 'string') return null;
return validLocation(value[0]) ? value[0] : null;
}
return typeof value === 'string' && validLocation(value) ? value : null;
}
function validLocation(value) {
return value.length > 0 && value.length <= 8192 && !/[\u0000-\u001f\u007f]/u.test(value);
}
async function closeRedirectBody(body) {
try {
if (!body) return;
if (typeof body.destroy === 'function') {
body.destroy();
return;
}
if (typeof body.cancel === 'function') await body.cancel();
} catch {
throw policyError('invalid_port_result', 'response body cleanup failed');
}
}
function closeSocket(socket) {
try {
socket?.destroy?.();
} catch {
// The policy decision remains fail-closed even when cleanup fails.
}
}
function assertPortResult(value, kind) {
if (!value || typeof value !== 'object' || typeof value.peerAddress !== 'string') {
throw policyError('invalid_port_result', `${kind} port returned an invalid peer`);
}
}
export function createEgressGateway({ lookupAll, connectPinned, requestPinned, now = Date.now }) {
if (typeof lookupAll !== 'function' || typeof connectPinned !== 'function' || typeof requestPinned !== 'function') {
throw new TypeError('egress gateway requires injected ports');
}
if (typeof now !== 'function') throw new TypeError('egress gateway requires a clock');
async function authorizeIntent(rawIntent, { signal } = {}) {
const intent = normalizeIntent(rawIntent);
const target = parsePublicUrl(intent.url);
let records = literalRecord(target);
if (!records) {
try {
records = await lookupAll(target.hostname, { signal });
} catch {
throw policyError('dns_resolution_failed', 'DNS resolution failed');
}
}
const authorized = authorizeResolvedTarget(target, records);
return deepFreeze({
canonicalUrl: target.canonicalUrl,
protocol: target.protocol,
hostname: target.hostname,
port: target.port,
resolved: authorized.resolved,
selectedAddress: authorized.selectedAddress,
policyVersion: '1',
purpose: intent.purpose,
method: intent.method,
expiresAtMs: now() + Math.min(intent.remaining.wallMs, 10_000),
});
}
function assertFresh(permit) {
if (now() > permit.expiresAtMs) throw policyError('permit_expired', 'network permit expired');
}
async function openAuthorizedTunnel(intent, { signal } = {}) {
const permit = await authorizeIntent(intent, { signal });
assertFresh(permit);
let opened;
try {
opened = await connectPinned({ permit, signal });
} catch {
throw policyError('connect_failed', 'pinned connection failed');
}
assertPortResult(opened, 'connector');
if (!peerMatches(permit.selectedAddress, opened.peerAddress)) {
closeSocket(opened.socket);
throw policyError('peer_mismatch', 'peer address mismatch');
}
return { socket: opened.socket, permit, peerAddress: opened.peerAddress };
}
async function execute(rawIntent, { signal } = {}) {
let intent = normalizeIntent(rawIntent);
const redirectChain = [];
const visited = new Set();
while (true) {
const permit = await authorizeIntent(intent, { signal });
assertFresh(permit);
visited.add(permit.canonicalUrl);
let response;
try {
response = await requestPinned({
permit,
method: intent.method,
headers: intent.headers,
signal,
});
} catch {
throw policyError('request_failed', 'pinned request failed');
}
assertPortResult(response, 'request');
if (!peerMatches(permit.selectedAddress, response.peerAddress)) {
await closeRedirectBody(response.body);
throw policyError('peer_mismatch', 'peer address mismatch');
}
if (!Number.isInteger(response.statusCode) || response.statusCode < 100 || response.statusCode > 599) {
await closeRedirectBody(response.body);
throw policyError('invalid_port_result', 'request port returned an invalid status');
}
const isRedirect = REDIRECT_STATUS.has(response.statusCode);
const location = isRedirect ? redirectLocation(response.headers) : null;
if (isRedirect && location === null) {
await closeRedirectBody(response.body);
throw policyError('invalid_redirect', 'redirect response is invalid');
}
if (!isRedirect) {
return {
statusCode: response.statusCode,
headers: response.headers ?? {},
body: response.body,
finalUrl: permit.canonicalUrl,
redirectChain: deepFreeze(redirectChain),
permit,
};
}
await closeRedirectBody(response.body);
if (intent.remaining.redirects === 0) throw policyError('redirect_limit', 'redirect limit exhausted');
let nextAbsolute;
try {
nextAbsolute = new URL(location, permit.canonicalUrl).href;
} catch {
throw policyError('invalid_redirect', 'redirect target is invalid');
}
const next = parsePublicUrl(nextAbsolute);
if (permit.protocol === 'https:' && next.protocol === 'http:') {
throw policyError('redirect_downgrade', 'redirect downgrade is not allowed');
}
if (visited.has(next.canonicalUrl)) throw policyError('redirect_loop', 'redirect loop detected');
redirectChain.push(deepFreeze({
statusCode: response.statusCode,
from: permit.canonicalUrl,
to: next.canonicalUrl,
}));
intent = {
...intent,
url: next.canonicalUrl,
method: response.statusCode === 303 ? 'GET' : intent.method,
headers: intent.headers,
remaining: { ...intent.remaining, redirects: intent.remaining.redirects - 1 },
};
}
}
return Object.freeze({ authorizeIntent, openAuthorizedTunnel, execute });
}
+364
View File
@@ -0,0 +1,364 @@
import { RUN_STATUS, deepFreeze } from './contracts.mjs';
const SENSITIVE_QUERY_KEY = /(?:access.?token|api.?key|auth(?:orization)?|client.?secret|credential|cookie|passw(?:or)?d|pwd|secret|session(?:id)?|signature|token)$/i;
const SPECIAL_HOSTS = new Set(['localhost', 'local', 'test', 'invalid', 'example', 'onion', 'home.arpa']);
const TERMINAL_BLOCKED = new Set([
'policy_denied',
'robots_denied',
'access_denied',
'auth_required',
'captcha',
'paywall',
'paid_required',
'hard_limit',
]);
export class PolicyError extends Error {
constructor(code, message) {
super(message);
this.name = 'PolicyError';
this.code = code;
}
}
function deny(code, message) {
throw new PolicyError(code, message);
}
function isDecimal(text) {
if (text.length === 0) return false;
for (const char of text) {
if (char < '0' || char > '9') return false;
}
return true;
}
function parseIpv4(text) {
const parts = text.split('.');
if (parts.length !== 4) return null;
const bytes = [];
for (const part of parts) {
if (!isDecimal(part) || (part.length > 1 && part[0] === '0')) return null;
const value = Number(part);
if (!Number.isInteger(value) || value > 255) return null;
bytes.push(value);
}
return bytes;
}
function isHex(text) {
if (text.length === 0 || text.length > 4) return false;
for (const char of text.toLowerCase()) {
if (!((char >= '0' && char <= '9') || (char >= 'a' && char <= 'f'))) return false;
}
return true;
}
function parseIpv6(text) {
let source = text;
if (source.startsWith('[') && source.endsWith(']')) source = source.slice(1, -1);
if (source.includes('%')) return null;
if (source.includes('.')) {
const splitAt = source.lastIndexOf(':');
if (splitAt < 0) return null;
const ipv4 = parseIpv4(source.slice(splitAt + 1));
if (!ipv4) return null;
source = `${source.slice(0, splitAt)}:${((ipv4[0] << 8) | ipv4[1]).toString(16)}:${((ipv4[2] << 8) | ipv4[3]).toString(16)}`;
}
const halves = source.split('::');
if (halves.length > 2) return null;
const parseHalf = (half) => {
if (half === '') return [];
const groups = half.split(':');
if (groups.some((group) => !isHex(group))) return null;
return groups.map((group) => Number.parseInt(group, 16));
};
const left = parseHalf(halves[0]);
const right = parseHalf(halves[1] ?? '');
if (!left || !right) return null;
if (halves.length === 1) {
if (left.length !== 8) return null;
return left;
}
const missing = 8 - left.length - right.length;
if (missing < 1) return null;
return [...left, ...Array(missing).fill(0), ...right];
}
function wordsToBytes(words) {
const bytes = [];
for (const word of words) bytes.push(word >>> 8, word & 0xff);
return bytes;
}
function formatIpv6(words) {
let bestStart = -1;
let bestLength = 0;
for (let index = 0; index < words.length;) {
if (words[index] !== 0) {
index += 1;
continue;
}
let end = index;
while (end < words.length && words[end] === 0) end += 1;
if (end - index > bestLength && end - index >= 2) {
bestStart = index;
bestLength = end - index;
}
index = end;
}
const rendered = words.map((word) => word.toString(16));
if (bestStart < 0) return rendered.join(':');
const before = rendered.slice(0, bestStart).join(':');
const after = rendered.slice(bestStart + bestLength).join(':');
if (before === '' && after === '') return '::';
if (before === '') return `::${after}`;
if (after === '') return `${before}::`;
return `${before}::${after}`;
}
function prefixMatches(bytes, prefix, bits) {
const fullBytes = Math.floor(bits / 8);
for (let index = 0; index < fullBytes; index += 1) {
if (bytes[index] !== prefix[index]) return false;
}
const remaining = bits % 8;
if (remaining === 0) return true;
const mask = (0xff << (8 - remaining)) & 0xff;
return (bytes[fullBytes] & mask) === (prefix[fullBytes] & mask);
}
const IPV4_SPECIAL = [
['0.0.0.0', 8, 'current-network'],
['10.0.0.0', 8, 'private'],
['100.64.0.0', 10, 'shared-address-space'],
['127.0.0.0', 8, 'loopback'],
['169.254.0.0', 16, 'link-local'],
['172.16.0.0', 12, 'private'],
['192.0.0.0', 24, 'special-purpose'],
['192.0.2.0', 24, 'documentation'],
['192.31.196.0', 24, 'special-purpose'],
['192.52.193.0', 24, 'special-purpose'],
['192.88.99.0', 24, 'deprecated-relay'],
['192.168.0.0', 16, 'private'],
['192.175.48.0', 24, 'special-purpose'],
['198.18.0.0', 15, 'benchmark'],
['198.51.100.0', 24, 'documentation'],
['203.0.113.0', 24, 'documentation'],
['224.0.0.0', 4, 'multicast'],
['240.0.0.0', 4, 'reserved'],
].map(([address, bits, reason]) => ({ prefix: parseIpv4(address), bits, reason }));
const IPV6_SPECIAL = [
['::', 96, 'ipv4-compatible'],
['::ffff:0:0', 96, 'ipv4-mapped'],
['64:ff9b::', 96, 'translation'],
['64:ff9b:1::', 48, 'translation-local'],
['100::', 64, 'discard-only'],
['2001::', 23, 'special-purpose'],
['2001:db8::', 32, 'documentation'],
['2002::', 16, 'deprecated-6to4'],
['2620:4f:8000::', 48, 'special-purpose'],
['3fff::', 20, 'documentation'],
['5f00::', 16, 'segment-routing'],
['fc00::', 7, 'unique-local'],
['fe80::', 10, 'link-local'],
['fec0::', 10, 'deprecated-site-local'],
['ff00::', 8, 'multicast'],
].map(([address, bits, reason]) => ({ prefix: wordsToBytes(parseIpv6(address)), bits, reason }));
export function classifyIpAddress(address) {
if (typeof address !== 'string' || address.length === 0) deny('invalid_ip', 'invalid IP address');
const source = address.startsWith('[') && address.endsWith(']') ? address.slice(1, -1) : address;
const ipv4 = parseIpv4(source);
if (ipv4) {
const special = IPV4_SPECIAL.find((range) => prefixMatches(ipv4, range.prefix, range.bits));
return deepFreeze({
family: 4,
normalized: ipv4.join('.'),
bytes: ipv4,
public: !special,
reason: special?.reason ?? 'global',
});
}
const words = parseIpv6(source.toLowerCase());
if (!words) deny('invalid_ip', 'invalid IP address');
const bytes = wordsToBytes(words);
const special = IPV6_SPECIAL.find((range) => prefixMatches(bytes, range.prefix, range.bits));
return deepFreeze({
family: 6,
normalized: formatIpv6(words),
bytes,
public: !special,
reason: special?.reason ?? 'global',
});
}
function normalizeHostname(hostname) {
const bracketed = hostname.startsWith('[') && hostname.endsWith(']');
if (bracketed) return hostname.toLowerCase();
return hostname.toLowerCase().replace(/\.+$/, '');
}
function specialHostname(hostname) {
const labels = hostname.split('.');
const suffix = labels.at(-1);
return SPECIAL_HOSTS.has(hostname)
|| SPECIAL_HOSTS.has(suffix)
|| hostname.endsWith('.localhost')
|| hostname.endsWith('.internal')
|| hostname === 'metadata.google.internal';
}
function maybeClassifyIp(hostname) {
const source = hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
if (!source.includes(':') && !isDecimal(source.replaceAll('.', ''))) return null;
try {
return classifyIpAddress(source);
} catch {
return null;
}
}
export function parsePublicUrl(input) {
if (typeof input !== 'string' || input.length === 0 || input.length > 8192) {
deny('invalid_url', 'invalid target URL');
}
if (input !== input.trim() || /[\u0000-\u001f\u007f\\]/u.test(input) || /%(?:00|0a|0d)/i.test(input)) {
deny('ambiguous_url', 'target URL contains ambiguous bytes');
}
const authorityStart = input.indexOf('://');
const afterScheme = authorityStart >= 0 ? input.slice(authorityStart + 3) : '';
const authorityEnd = afterScheme.search(/[/?#]/u);
const authority = authorityEnd < 0 ? afterScheme : afterScheme.slice(0, authorityEnd);
if (/%(?:25|2f|3a|40|5c)/i.test(authority)) {
deny('ambiguous_url', 'target URL contains encoded authority delimiter');
}
let url;
try {
url = new URL(input);
} catch {
deny('invalid_url', 'invalid target URL');
}
if (!['http:', 'https:'].includes(url.protocol)) deny('scheme_denied', 'target scheme is not allowed');
if (url.username !== '' || url.password !== '') deny('userinfo_denied', 'target credentials are not allowed');
if (url.hostname === '') deny('empty_host', 'target hostname is empty');
if (url.hostname.includes('%')) deny('zone_identifier_denied', 'target zone identifier is not allowed');
if (url.port !== '' && !['80', '443'].includes(url.port)) deny('port_denied', 'target port is not allowed');
for (const key of url.searchParams.keys()) {
const normalized = key.normalize('NFKC').replace(/[\s._-]/gu, '');
if (SENSITIVE_QUERY_KEY.test(normalized)) deny('sensitive_query', 'target has a sensitive query key');
}
const hostname = normalizeHostname(url.hostname);
if (specialHostname(hostname)) deny('special_hostname', 'target hostname is not public');
const literal = maybeClassifyIp(hostname);
if (literal && !literal.public) deny('non_public_ip', 'target IP is not public');
url.hostname = hostname;
url.hash = '';
const port = Number(url.port || (url.protocol === 'https:' ? 443 : 80));
return deepFreeze({
canonicalUrl: url.href,
protocol: url.protocol,
hostname,
port,
isIpLiteral: literal !== null,
});
}
function compareBytes(left, right) {
if (left.family !== right.family) return left.family - right.family;
for (let index = 0; index < left.bytes.length; index += 1) {
if (left.bytes[index] !== right.bytes[index]) return left.bytes[index] - right.bytes[index];
}
return 0;
}
export function authorizeResolvedTarget(target, records) {
if (!target || typeof target !== 'object' || typeof target.hostname !== 'string') {
deny('invalid_target', 'invalid canonical target');
}
if (!Array.isArray(records) || records.length === 0) deny('empty_dns', 'DNS answer set is empty');
const classified = records.map((record) => {
if (!record || typeof record.address !== 'string' || ![4, 6].includes(record.family)) {
deny('invalid_dns_answer', 'DNS answer is invalid');
}
const result = classifyIpAddress(record.address);
if (result.family !== record.family) deny('dns_family_mismatch', 'DNS address family mismatch');
if (!result.public) deny('dns_non_public', 'DNS answer is not public');
return result;
}).sort(compareBytes);
const unique = classified.filter((entry, index) => (
index === 0 || entry.family !== classified[index - 1].family || entry.normalized !== classified[index - 1].normalized
));
return deepFreeze({
resolved: unique.map(({ normalized, family }) => ({ address: normalized, family })),
selectedAddress: unique[0].normalized,
});
}
export function authorizeCost(descriptor) {
const allowed = descriptor?.cost === 'local-zero' && descriptor?.price === 0;
return deepFreeze(allowed
? { allowed: true, state: 'allowed_zero', reason: 'proven_local_zero' }
: { allowed: false, state: 'unknown_and_blocked', reason: 'price_not_proven_zero' });
}
// A balance/price reading is trustworthy only while fresh; a stale figure is a
// silent overdraft waiting to happen, so it fails closed like an unknown one.
const CLOUD_BALANCE_MAX_AGE_MS = 5 * 60 * 1000;
function isFreshBalance(balance, observedAt, now) {
if (!Number.isFinite(balance) || typeof observedAt !== 'string') return false;
const at = Date.parse(observedAt);
if (Number.isNaN(at)) return false;
const age = now - at;
return age >= 0 && age <= CLOUD_BALANCE_MAX_AGE_MS;
}
// Additive credit-cost proof for provider-managed (cloud) descriptors. Credentials
// or a binary never grant authority — only a fresh free balance, a proven-zero
// money price, a hard no-overage ceiling, and a bounded worst case that fits both
// the ceiling and the run-ledger's remaining credits do. Anything unknown, stale,
// negative, impossible, or over-reserve fails closed. Pure: never mutates ledger.
export function authorizeCloudCost(descriptor, ledger, clock = () => new Date()) {
const provider = descriptor ?? {};
const runLedger = ledger ?? {};
const now = clock().getTime();
const block = (reason) => deepFreeze({ allowed: false, state: 'unknown_and_blocked', reason, reserve: 0 });
if (!isFreshBalance(provider.balance, provider.balanceObservedAt, now)
|| !isFreshBalance(runLedger.balance, runLedger.observedAt, now)) {
return block('balance_unknown_or_stale');
}
if (!Number.isFinite(provider.price) || provider.price !== 0) return block('price_unknown');
const ceiling = Math.min(...[provider.hardCeiling, runLedger.hardCeiling].filter(Number.isFinite));
if (!Number.isFinite(ceiling) || ceiling <= 0) return block('no_hard_ceiling');
const worst = provider.worstCaseCredits;
const committed = Number.isFinite(runLedger.committed) ? runLedger.committed : 0;
const available = runLedger.balance - committed;
if (!(Number.isInteger(worst) && worst > 0 && worst <= ceiling && worst <= available)) {
return block('worst_case_unbounded');
}
if (!(Number.isFinite(provider.freeCredits) && provider.freeCredits >= worst)) {
return block('insufficient_free_credits');
}
if (provider.preflightMayCharge !== false) return block('preflight_may_charge');
return deepFreeze({ allowed: true, state: 'reservable_free', reason: 'cost_proven', reserve: worst });
}
export function classifyTerminalOutcome(outcome) {
const code = outcome?.code;
if (TERMINAL_BLOCKED.has(code)) {
return deepFreeze({ terminal: true, status: RUN_STATUS.BLOCKED, code });
}
if (code === 'not_found' || code === 'gone') {
return deepFreeze({ terminal: true, status: RUN_STATUS.EXHAUSTED, code });
}
if (code === 'rate_limited' && outcome?.exhausted === true) {
return deepFreeze({ terminal: true, status: RUN_STATUS.BLOCKED, code });
}
return deepFreeze({ terminal: false, status: null, code: code ?? null });
}
+375
View File
@@ -0,0 +1,375 @@
import { spawn as nodeSpawn } from 'node:child_process';
import { realpath } from 'node:fs/promises';
import { basename, dirname, isAbsolute, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { ATTEMPT_CODE, ATTEMPT_KIND } from './contracts.mjs';
const PROFILE_ID = 'python-parser';
const BROWSER_PROFILE_ID = 'python-browser';
export const PYTHON_HELPER_PATH = fileURLToPath(new URL('./lynceuz-helper.py', import.meta.url));
const OPERATIONS = new Set(['self_check', 'parse_html', 'extract_schema']);
const ENV_KEYS = new Set([
'LANG',
'LC_ALL',
'PYTHONHASHSEED',
'PYTHONIOENCODING',
'PYTHONNOUSERSITE',
]);
const REQUEST_KEYS = new Set([
'version',
'id',
'operation',
'input_path',
'input_hash',
'base_url',
'output_path',
'schema',
]);
const RESPONSE_KEYS = new Set(['version', 'id', 'ok', 'code', 'details', 'payload']);
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
const HASH = /^sha256:[0-9a-f]{64}$/u;
const BROWSER_ENV_KEYS = Object.freeze(['LANG', 'LC_ALL', 'PYTHONNOUSERSITE']);
const LAUNCH_PLAN_KEYS = Object.freeze([
'argv', 'env', 'executable', 'gid', 'guard_proxy', 'kind', 'shell', 'uid',
]);
const BROWSER_LIMITS = Object.freeze({
maxInputBytes: 64 * 1024,
maxStdoutBytes: 64 * 1024,
maxStderrBytes: 64 * 1024,
timeoutMs: 30_000,
});
function plainObject(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function nowMilliseconds(clock) {
const value = clock();
const milliseconds = value instanceof Date ? value.getTime() : Number(value);
if (!Number.isFinite(milliseconds)) throw new TypeError('clock returned invalid time');
return milliseconds;
}
function absolutePath(value, label) {
if (typeof value !== 'string' || value.length === 0 || !isAbsolute(value)) {
throw new TypeError(`${label} must be an absolute path`);
}
return value;
}
function exactKeys(value, keys) {
return plainObject(value)
&& Object.keys(value).sort().join('\0') === [...keys].sort().join('\0');
}
function safeLaunchText(value, maximum = 4096) {
return typeof value === 'string' && value.length > 0 && value.length <= maximum
&& !/[\0\r\n]/u.test(value);
}
function frozenData(value) {
return Object.isFrozen(value)
&& Object.values(Object.getOwnPropertyDescriptors(value)).every((field) => 'value' in field);
}
export function validContainedBrowserLaunchPlan(plan) {
if (!exactKeys(plan, LAUNCH_PLAN_KEYS) || !frozenData(plan)
|| plan.kind !== 'lynceuz_macos_containment_launch_plan'
|| plan.executable !== '/usr/bin/sudo' || plan.shell !== false
|| !Number.isSafeInteger(plan.uid) || plan.uid < 1
|| !Number.isSafeInteger(plan.gid) || plan.gid < 1
|| !Array.isArray(plan.argv) || !frozenData(plan.argv) || plan.argv.length !== 7
|| plan.argv[0] !== '-n' || plan.argv[1] !== '-u' || plan.argv[2] !== `#${plan.uid}`
|| plan.argv[3] !== '--' || plan.argv[5] !== '-I'
|| !isAbsolute(plan.argv[4]) || !/^python(?:\d+(?:\.\d+)*)?$/u.test(basename(plan.argv[4]))
|| !isAbsolute(plan.argv[6]) || basename(plan.argv[6]) !== 'lynceuz-browser.py'
|| !plan.argv.every((value) => safeLaunchText(value))) return false;
if (!exactKeys(plan.guard_proxy, ['host', 'port']) || !frozenData(plan.guard_proxy)
|| plan.guard_proxy.host !== '127.0.0.1'
|| !Number.isInteger(plan.guard_proxy.port)
|| plan.guard_proxy.port < 1 || plan.guard_proxy.port > 65_535) return false;
return exactKeys(plan.env, BROWSER_ENV_KEYS) && frozenData(plan.env)
&& BROWSER_ENV_KEYS.every((key) => safeLaunchText(plan.env[key], 128))
&& plan.env.PYTHONNOUSERSITE === '1';
}
function contained(root, candidate) {
const fromRoot = relative(root, candidate);
return fromRoot === '' || (fromRoot !== '..' && !fromRoot.startsWith('../') && !isAbsolute(fromRoot));
}
function assertProfile(id, profile) {
if (id !== PROFILE_ID || !plainObject(profile)) {
throw new TypeError('only the fixed python-parser profile is supported');
}
absolutePath(profile.command, 'python-parser command');
absolutePath(profile.cwd, 'python-parser cwd');
if (!/^python(?:\d+(?:\.\d+)*)?$/u.test(basename(profile.command))) {
throw new TypeError('python-parser command must be Python');
}
if (!Array.isArray(profile.args) || profile.args.length !== 2 || profile.args[0] !== '-I'
|| profile.args[1] !== PYTHON_HELPER_PATH) {
throw new TypeError('python-parser argv is not the fixed helper argv');
}
if (!plainObject(profile.env)) throw new TypeError('python-parser env is invalid');
for (const [key, value] of Object.entries(profile.env)) {
if (!ENV_KEYS.has(key) || typeof value !== 'string' || value.length > 128 || /[\r\n\0]/u.test(value)) {
throw new TypeError(`python-parser env entry is not allowlisted: ${key}`);
}
}
for (const field of ['maxInputBytes', 'maxStdoutBytes', 'maxStderrBytes', 'timeoutMs']) {
if (!Number.isSafeInteger(profile[field]) || profile[field] < 1) {
throw new TypeError(`python-parser ${field} is invalid`);
}
}
}
function fixedProfile(profile) {
return Object.freeze({
...profile,
args: Object.freeze([...profile.args]),
env: Object.freeze({ ...profile.env }),
});
}
function typed(kind, code, details = undefined) {
return Object.freeze({ kind, code, ...(details === undefined ? {} : { details }) });
}
function protocol(reason) {
return typed(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR, { reason });
}
function collectStream(stream, maximum, overflow) {
const chunks = [];
let length = 0;
let exceeded = false;
stream.on('data', (chunk) => {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
if (exceeded) return;
if (length + bytes.length > maximum) {
exceeded = true;
overflow();
return;
}
length += bytes.length;
chunks.push(Buffer.from(bytes));
});
return () => Buffer.concat(chunks, length);
}
async function defaultKillProcessTree(child, {
platform,
graceMs = 200,
setTimer = setTimeout,
} = {}) {
if (!child?.pid) return;
const processGroup = platform !== 'win32';
try {
if (processGroup) process.kill(-child.pid, 'SIGTERM');
else child.kill('SIGTERM');
} catch {}
await new Promise((resolveGrace) => {
const timer = setTimer(resolveGrace, graceMs);
timer.unref?.();
});
try {
if (processGroup) process.kill(-child.pid, 'SIGKILL');
else child.kill('SIGKILL');
} catch {}
}
function validateRequest(request) {
if (!plainObject(request) || Object.keys(request).some((key) => !REQUEST_KEYS.has(key))) {
throw new TypeError('request has unknown fields');
}
if (request.version !== 1 || !SAFE_ID.test(request.id ?? '') || !OPERATIONS.has(request.operation)) {
throw new TypeError('request envelope is invalid');
}
if (request.operation === 'self_check') {
if (Object.keys(request).length !== 3) throw new TypeError('self_check has extra data');
return;
}
absolutePath(request.input_path, 'input path');
absolutePath(request.output_path, 'output path');
if (!HASH.test(request.input_hash ?? '')) throw new TypeError('input hash is invalid');
if (typeof request.base_url !== 'string' || Buffer.byteLength(request.base_url) > 8192) {
throw new TypeError('base URL is invalid');
}
if (request.operation === 'extract_schema' && !plainObject(request.schema)) {
throw new TypeError('extract_schema requires schema');
}
if (request.operation === 'parse_html' && request.schema !== undefined) {
throw new TypeError('parse_html cannot receive schema');
}
}
async function validatePaths(request, payload, profile) {
if (request.operation === 'self_check') return profile.cwd;
absolutePath(payload.inputRoot, 'input root');
absolutePath(payload.scratchDir, 'scratch directory');
const [inputRoot, scratchRoot, inputPath, outputParent] = await Promise.all([
realpath(payload.inputRoot),
realpath(payload.scratchDir),
realpath(request.input_path),
realpath(dirname(request.output_path)),
]);
if (!contained(inputRoot, inputPath)) throw new TypeError('input escaped storage root');
if (!contained(scratchRoot, outputParent)) throw new TypeError('output escaped scratch root');
return scratchRoot;
}
function validResponse(response, id) {
return plainObject(response)
&& Object.keys(response).every((key) => RESPONSE_KEYS.has(key))
&& response.version === 1
&& response.id === id
&& typeof response.ok === 'boolean'
&& (response.ok ? response.code === undefined : typeof response.code === 'string')
&& (response.code === undefined || typeof response.code === 'string')
&& (response.details === undefined || plainObject(response.details))
&& (response.payload === undefined || plainObject(response.payload));
}
export function createProcessSupervisor({
profiles,
spawnImpl = nodeSpawn,
clock = Date.now,
platform = process.platform,
killProcessTree = defaultKillProcessTree,
setTimer = setTimeout,
clearTimer = clearTimeout,
} = {}) {
if (!(profiles instanceof Map) || profiles.size !== 1 || !profiles.has(PROFILE_ID)) {
throw new TypeError('profile registry must contain only python-parser');
}
if (typeof spawnImpl !== 'function' || typeof clock !== 'function'
|| typeof killProcessTree !== 'function' || typeof setTimer !== 'function'
|| typeof clearTimer !== 'function') {
throw new TypeError('process supervisor ports are invalid');
}
const configured = profiles.get(PROFILE_ID);
assertProfile(PROFILE_ID, configured);
const profile = fixedProfile(configured);
async function run(profileId, payload = {}) {
if (profileId !== PROFILE_ID && profileId !== BROWSER_PROFILE_ID) {
return typed(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.UNSUPPORTED, { reason: 'unknown_profile' });
}
const request = payload.request ?? payload;
let execution = profile;
let cwd;
let requestBytes;
try {
if (profileId === BROWSER_PROFILE_ID) {
if (!validContainedBrowserLaunchPlan(payload.launchPlan)) throw new TypeError('invalid launch plan');
if (!plainObject(request) || request.version !== 1 || !SAFE_ID.test(request.id ?? '')
|| request.operation !== 'render') throw new TypeError('invalid browser request');
cwd = request.output_path === undefined
? profile.cwd
: await realpath(dirname(absolutePath(request.output_path, 'output path')));
execution = { ...BROWSER_LIMITS, ...payload.launchPlan };
} else {
validateRequest(request);
cwd = await validatePaths(request, payload, profile);
}
requestBytes = Buffer.from(`${JSON.stringify(request)}\n`);
} catch {
return protocol(profileId === BROWSER_PROFILE_ID ? 'invalid_contained_launch' : 'invalid_request');
}
if (requestBytes.length > execution.maxInputBytes) return protocol('input_oversized');
if (payload.signal?.aborted) {
return typed(ATTEMPT_KIND.RETRYABLE, ATTEMPT_CODE.TIMEOUT, { reason: 'aborted' });
}
const startedAt = nowMilliseconds(clock);
let child;
try {
child = spawnImpl(execution.command ?? execution.executable, execution.args ?? execution.argv, {
cwd,
env: { ...execution.env },
shell: false,
detached: platform !== 'win32',
stdio: ['pipe', 'pipe', 'pipe'],
});
} catch (error) {
if (error?.code === 'ENOENT') {
return typed(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.UNAVAILABLE, { reason: 'python_missing' });
}
return typed(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_CRASH, { reason: 'spawn_failed' });
}
let stopReason = null;
let spawnError = null;
let killPromise = null;
const terminate = (reason) => {
stopReason ??= reason;
killPromise ??= Promise.resolve(killProcessTree(child, { platform, setTimer }));
};
const stdout = collectStream(child.stdout, execution.maxStdoutBytes, () => terminate('stdout_oversized'));
const stderr = collectStream(child.stderr, execution.maxStderrBytes, () => terminate('stderr_oversized'));
child.once('error', (error) => { spawnError = error; });
child.stdin.on('error', () => {});
const abort = () => terminate('aborted');
payload.signal?.addEventListener('abort', abort, { once: true });
const timer = setTimer(() => terminate('timeout'), execution.timeoutMs);
timer.unref?.();
try {
child.stdin.end(requestBytes);
const [exitCode, signal] = await new Promise((resolveClose) => {
child.once('close', (code, closeSignal) => resolveClose([code, closeSignal]));
});
if (killPromise) await killPromise;
if (spawnError) {
if (spawnError.code === 'ENOENT') {
return typed(ATTEMPT_KIND.SKIP, ATTEMPT_CODE.UNAVAILABLE, { reason: 'python_missing' });
}
return typed(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_CRASH, { reason: 'spawn_failed' });
}
if (stopReason === 'timeout' || stopReason === 'aborted') {
return typed(ATTEMPT_KIND.RETRYABLE, ATTEMPT_CODE.TIMEOUT, {
reason: stopReason,
exitCode,
signal,
durationMs: Math.max(0, nowMilliseconds(clock) - startedAt),
});
}
if (stopReason) return protocol(stopReason);
if (exitCode !== 0) {
return typed(ATTEMPT_KIND.BROKEN, ATTEMPT_CODE.ADAPTER_CRASH, {
reason: 'non_zero_exit', exitCode, signal,
});
}
const output = stdout().toString('utf8');
const diagnostics = stderr().toString('utf8');
const lines = output.split(/\r?\n/u);
if (lines.at(-1) === '') lines.pop();
if (lines.length !== 1 || lines[0].length === 0) return protocol('invalid_framing');
let response;
try {
response = JSON.parse(lines[0]);
} catch {
return protocol('invalid_json');
}
if (!validResponse(response, request.id)) return protocol('invalid_response');
return Object.freeze({
kind: ATTEMPT_KIND.SUCCESS,
code: ATTEMPT_CODE.OK,
response,
details: {
durationMs: Math.max(0, nowMilliseconds(clock) - startedAt),
stderrBytes: Buffer.byteLength(diagnostics),
},
});
} finally {
clearTimer(timer);
payload.signal?.removeEventListener('abort', abort);
}
}
return Object.freeze({ run });
}
+583
View File
@@ -0,0 +1,583 @@
import { ATTEMPT_CODE, ATTEMPT_KIND, deepFreeze } from './contracts.mjs';
import { parsePublicUrl } from './policy.mjs';
const ROBOTS_USER_AGENT = 'Lynceuz/1.0';
const MAX_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
const DEFAULT_BODY_BYTES = 512 * 1024;
const DEFAULT_TIMEOUT_MS = 10_000;
const DEFAULT_CACHE_ENTRIES = 256;
const MAX_LINE_BYTES = 16 * 1024;
const MAX_RULES = 10_000;
const UNRESERVED = /^[A-Za-z0-9._~-]$/u;
const HEX_PAIR = /^[0-9A-Fa-f]{2}$/u;
const POLICY_FAILURE_CODES = new Set([
'ambiguous_url',
'dns_family_mismatch',
'dns_non_public',
'empty_host',
'invalid_dns_answer',
'invalid_redirect',
'invalid_url',
'non_public_ip',
'peer_mismatch',
'port_denied',
'redirect_downgrade',
'redirect_loop',
'scheme_denied',
'sensitive_query',
'special_hostname',
'userinfo_denied',
'zone_identifier_denied',
]);
function finiteInteger(value, label, { minimum = 0, maximum = Number.MAX_SAFE_INTEGER } = {}) {
if (!Number.isInteger(value) || value < minimum || value > maximum) {
throw new TypeError(`${label} is invalid`);
}
return value;
}
function nowMilliseconds(clock) {
const value = clock();
const milliseconds = value instanceof Date ? value.valueOf() : value;
if (!Number.isFinite(milliseconds)) throw new TypeError('robots clock returned an invalid value');
return milliseconds;
}
function normalizePercentEncoding(value) {
let normalized = '';
for (let index = 0; index < value.length;) {
if (value[index] === '%' && index + 2 < value.length) {
const pair = value.slice(index + 1, index + 3);
if (HEX_PAIR.test(pair)) {
const character = String.fromCharCode(Number.parseInt(pair, 16));
normalized += UNRESERVED.test(character) ? character : `%${pair.toUpperCase()}`;
index += 3;
continue;
}
}
const codePoint = value.codePointAt(index);
const character = String.fromCodePoint(codePoint);
if (codePoint <= 0x7f) normalized += character;
else normalized += encodeURIComponent(character).toUpperCase();
index += character.length;
}
return normalized;
}
function regexEscape(character) {
return /[\\^$.*+?()[\]{}|]/u.test(character) ? `\\${character}` : character;
}
function compileRule(rawPattern, allow) {
const endAnchored = rawPattern.endsWith('$');
const withoutAnchor = endAnchored ? rawPattern.slice(0, -1) : rawPattern;
const pattern = normalizePercentEncoding(withoutAnchor);
let expression = '^';
let previousStar = false;
for (const character of pattern) {
if (character === '*') {
if (!previousStar) expression += '.*';
previousStar = true;
} else {
expression += regexEscape(character);
previousStar = false;
}
}
if (endAnchored) expression += '$';
const specificity = Buffer.byteLength(pattern.replaceAll('*', ''));
return Object.freeze({
allow,
pattern: rawPattern,
matcher: new RegExp(expression, 'u'),
specificity,
});
}
function targetPath(value) {
let parsed;
try {
parsed = value.startsWith('/')
? new URL(value, 'https://robots.invalid')
: new URL(value);
} catch {
throw new TypeError('robots target URL is invalid');
}
return normalizePercentEncoding(`${parsed.pathname}${parsed.search}`);
}
function parseSitemap(value) {
let parsed;
try {
parsed = new URL(value);
} catch {
return null;
}
if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password) return null;
parsed.hash = '';
return parsed.href;
}
function selectGroups(groups, userAgent) {
const productToken = userAgent.toLowerCase().split(/[\s/]/u, 1)[0];
const wildcard = [];
let bestLength = -1;
let specific = [];
for (const group of groups) {
let groupBest = -1;
for (const agent of group.agents) {
const token = agent.toLowerCase();
if (token === '*') continue;
if (productToken.includes(token)) groupBest = Math.max(groupBest, token.length);
}
if (group.agents.includes('*')) wildcard.push(group);
if (groupBest > bestLength) {
bestLength = groupBest;
specific = groupBest < 0 ? [] : [group];
} else if (groupBest >= 0 && groupBest === bestLength) {
specific.push(group);
}
}
return specific.length > 0 ? specific : wildcard;
}
export function parseRobots(source, {
userAgent = ROBOTS_USER_AGENT,
maxBytes = DEFAULT_BODY_BYTES,
} = {}) {
if (typeof source !== 'string' || typeof userAgent !== 'string'
|| userAgent.length === 0 || userAgent.length > 128
|| /[\u0000-\u001f\u007f]/u.test(userAgent)) {
throw new TypeError('robots input is invalid');
}
finiteInteger(maxBytes, 'robots maxBytes', { minimum: 1 });
if (Buffer.byteLength(source) > maxBytes || source.includes('\0')) {
throw new TypeError('robots body is invalid');
}
const groups = [];
const sitemaps = [];
const sitemapSet = new Set();
let current = null;
let directivesStarted = false;
let ruleCount = 0;
for (let rawLine of source.replace(/^\uFEFF/u, '').split(/\r?\n/u)) {
if (Buffer.byteLength(rawLine) > MAX_LINE_BYTES) throw new TypeError('robots line is too large');
const comment = rawLine.indexOf('#');
if (comment >= 0) rawLine = rawLine.slice(0, comment);
const separator = rawLine.indexOf(':');
if (separator < 0) continue;
const field = rawLine.slice(0, separator).trim().toLowerCase();
const value = rawLine.slice(separator + 1).trim();
if (field === 'sitemap') {
const sitemap = parseSitemap(value);
if (sitemap && !sitemapSet.has(sitemap)) {
sitemapSet.add(sitemap);
sitemaps.push(sitemap);
}
continue;
}
if (field === 'user-agent') {
const agent = value.toLowerCase();
if (agent.length === 0 || agent.length > 128 || /[^\x21-\x7e]/u.test(agent)) continue;
if (!current || directivesStarted) {
current = { agents: [], rules: [], crawlDelays: [] };
groups.push(current);
directivesStarted = false;
}
if (!current.agents.includes(agent)) current.agents.push(agent);
continue;
}
if (!current || current.agents.length === 0) continue;
if (field === 'allow' || field === 'disallow') {
directivesStarted = true;
if (value === '') continue;
ruleCount += 1;
if (ruleCount > MAX_RULES) throw new TypeError('robots has too many rules');
current.rules.push(compileRule(value, field === 'allow'));
continue;
}
if (field === 'crawl-delay') {
directivesStarted = true;
if (!/^(?:\d+\.?\d*|\.\d+)$/u.test(value)) continue;
const seconds = Number(value);
if (Number.isFinite(seconds) && seconds >= 0 && seconds <= 86_400) {
current.crawlDelays.push(Math.ceil(seconds * 1000));
}
}
}
const selected = selectGroups(groups, userAgent);
const rules = selected.flatMap((group) => group.rules);
const selectedDelays = selected
.filter((group) => group.agents.some((agent) => agent !== '*'))
.flatMap((group) => group.crawlDelays);
const fallbackDelays = selected.flatMap((group) => group.crawlDelays);
const delays = selectedDelays.length > 0 ? selectedDelays : fallbackDelays;
const crawlDelayMs = delays.length === 0 ? 0 : Math.max(...delays);
function decide(url) {
const path = targetPath(url);
let winner = null;
for (const rule of rules) {
if (!rule.matcher.test(path)) continue;
if (!winner || rule.specificity > winner.specificity
|| (rule.specificity === winner.specificity && rule.allow && !winner.allow)) {
winner = rule;
}
}
return Object.freeze({
allowed: winner?.allow ?? true,
matchedRule: winner?.pattern ?? null,
});
}
return Object.freeze({
allows: (url) => decide(url).allowed,
decide,
crawlDelayMs,
sitemaps: Object.freeze([...sitemaps]),
});
}
function singleHeader(headers, wantedName) {
if (!headers || typeof headers !== 'object') return null;
const matches = Object.entries(headers)
.filter(([name]) => name.toLowerCase() === wantedName)
.map(([, value]) => value);
if (matches.length !== 1) return null;
const value = matches[0];
if (Array.isArray(value)) return value.length === 1 ? String(value[0]) : null;
return value === undefined ? null : String(value);
}
function abortable(promise, signal) {
if (!signal) return promise;
if (signal.aborted) return Promise.reject(signal.reason ?? new Error('robots request aborted'));
return new Promise((resolve, reject) => {
const onAbort = () => reject(signal.reason ?? new Error('robots request aborted'));
signal.addEventListener('abort', onAbort, { once: true });
Promise.resolve(promise).then(
(value) => {
signal.removeEventListener('abort', onAbort);
resolve(value);
},
(error) => {
signal.removeEventListener('abort', onAbort);
reject(error);
},
);
});
}
async function readBoundedBody(body, maxBytes, signal) {
if (body === null || body === undefined) return Buffer.alloc(0);
if (Buffer.isBuffer(body) || body instanceof Uint8Array || typeof body === 'string') {
const bytes = Buffer.from(body);
if (bytes.length > maxBytes) throw new TypeError('robots body exceeds limit');
return bytes;
}
const chunks = [];
let total = 0;
try {
if (typeof body[Symbol.asyncIterator] === 'function') {
const iterator = body[Symbol.asyncIterator]();
while (true) {
const { done, value: chunk } = await abortable(iterator.next(), signal);
if (done) break;
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
total += bytes.length;
if (total > maxBytes) throw new TypeError('robots body exceeds limit');
chunks.push(bytes);
}
} else if (typeof body.getReader === 'function') {
const reader = body.getReader();
try {
while (true) {
const { done, value } = await abortable(reader.read(), signal);
if (done) break;
const bytes = Buffer.from(value);
total += bytes.length;
if (total > maxBytes) throw new TypeError('robots body exceeds limit');
chunks.push(bytes);
}
} finally {
reader.releaseLock?.();
}
} else {
throw new TypeError('robots response body is invalid');
}
} catch (error) {
try {
body.destroy?.();
await body.cancel?.();
} catch {
// The fail-closed result below is more important than cleanup diagnostics.
}
throw error;
}
return Buffer.concat(chunks, total);
}
function discardBody(body) {
try {
body?.destroy?.();
const cancellation = body?.cancel?.();
cancellation?.catch?.(() => {});
} catch {
// Decision remains fail-closed if response cleanup itself fails.
}
}
function terminal(code, reason, details = {}) {
return deepFreeze({
kind: ATTEMPT_KIND.TERMINAL,
code,
cacheStatus: 'miss',
details: { reason, ...details },
});
}
function success({ cacheStatus, crawlDelayMs = 0, sitemaps = [], reason, matchedRule = null }) {
return deepFreeze({
kind: ATTEMPT_KIND.SUCCESS,
code: ATTEMPT_CODE.OK,
cacheStatus,
crawlDelayMs,
sitemaps: [...sitemaps],
details: { reason, matchedRule },
});
}
function retryAfterMilliseconds(headers, now) {
const value = singleHeader(headers, 'retry-after');
if (value === null) return 0;
if (/^\d+$/u.test(value.trim())) return Number(value.trim()) * 1000;
const date = Date.parse(value);
return Number.isFinite(date) ? Math.max(0, date - now) : 0;
}
async function defaultSleep(milliseconds, { signal } = {}) {
if (milliseconds <= 0) return;
await new Promise((resolve, reject) => {
let settled = false;
const finish = (action, value) => {
if (settled) return;
settled = true;
signal?.removeEventListener?.('abort', onAbort);
action(value);
};
const timer = setTimeout(() => finish(resolve), milliseconds);
const onAbort = () => {
clearTimeout(timer);
finish(reject, signal?.reason ?? new Error('robots retry aborted'));
};
if (signal?.aborted) onAbort();
else signal?.addEventListener?.('abort', onAbort, { once: true });
});
}
export function createRobotsGate({
gateway,
clock = Date.now,
ttlMs = MAX_CACHE_TTL_MS,
maxBodyBytes = DEFAULT_BODY_BYTES,
maxRedirects = 5,
timeoutMs = DEFAULT_TIMEOUT_MS,
maxCacheEntries = DEFAULT_CACHE_ENTRIES,
retries = 0,
sleep = defaultSleep,
setTimer = setTimeout,
clearTimer = clearTimeout,
} = {}) {
if (!gateway || typeof gateway.execute !== 'function') {
throw new TypeError('robots gate requires EgressGateway');
}
if (typeof clock !== 'function' || typeof sleep !== 'function'
|| typeof setTimer !== 'function' || typeof clearTimer !== 'function') {
throw new TypeError('robots gate ports are invalid');
}
if (!Number.isFinite(ttlMs) || ttlMs < 0) throw new TypeError('robots ttlMs is invalid');
finiteInteger(maxBodyBytes, 'robots maxBodyBytes', { minimum: 1 });
finiteInteger(maxRedirects, 'robots maxRedirects');
finiteInteger(maxCacheEntries, 'robots maxCacheEntries', { minimum: 1, maximum: 4096 });
finiteInteger(retries, 'robots retries', { maximum: 8 });
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new TypeError('robots timeoutMs is invalid');
const effectiveTtlMs = Math.min(ttlMs, MAX_CACHE_TTL_MS);
const cache = new Map();
function remember(origin, entry, now) {
if (effectiveTtlMs === 0) return;
cache.delete(origin);
cache.set(origin, { ...entry, expiresAt: now + effectiveTtlMs });
while (cache.size > maxCacheEntries) cache.delete(cache.keys().next().value);
}
function cached(origin, now) {
const entry = cache.get(origin);
if (!entry) return null;
if (now >= entry.expiresAt) {
cache.delete(origin);
return null;
}
cache.delete(origin);
cache.set(origin, entry);
return entry;
}
function decide(entry, targetUrl, cacheStatus) {
if (entry.kind === 'allow_all') {
return success({ cacheStatus, reason: entry.reason });
}
const decision = entry.parsed.decide(targetUrl);
if (!decision.allowed) {
return deepFreeze({
kind: ATTEMPT_KIND.TERMINAL,
code: ATTEMPT_CODE.ROBOTS_DENIED,
cacheStatus,
crawlDelayMs: entry.parsed.crawlDelayMs,
sitemaps: [...entry.parsed.sitemaps],
details: { reason: 'rule_denied', matchedRule: decision.matchedRule },
});
}
return success({
cacheStatus,
crawlDelayMs: entry.parsed.crawlDelayMs,
sitemaps: entry.parsed.sitemaps,
reason: 'rule_allowed',
matchedRule: decision.matchedRule,
});
}
async function check(inputUrl, { runId = 'robots', signal } = {}) {
let target;
try {
target = parsePublicUrl(inputUrl);
} catch (error) {
return terminal(ATTEMPT_CODE.POLICY_DENIED, error?.code ?? 'invalid_url');
}
const targetUrl = target.canonicalUrl;
const origin = new URL(targetUrl).origin;
const now = nowMilliseconds(clock);
const hit = cached(origin, now);
if (hit) return decide(hit, targetUrl, 'hit');
const controller = new AbortController();
const onAbort = () => controller.abort(signal?.reason ?? new Error('robots request aborted'));
if (signal?.aborted) onAbort();
else signal?.addEventListener?.('abort', onAbort, { once: true });
const timer = setTimer(() => controller.abort(new Error('robots request timed out')), timeoutMs);
try {
const robotsUrl = new URL('/robots.txt', origin).href;
for (let attempt = 0; attempt <= retries; attempt += 1) {
let response;
try {
response = await gateway.execute({
runId,
purpose: 'robots',
url: robotsUrl,
method: 'GET',
headers: {
Accept: 'text/plain, text/*;q=0.9, */*;q=0.1',
'User-Agent': ROBOTS_USER_AGENT,
},
remaining: {
wallMs: timeoutMs,
bytes: maxBodyBytes,
redirects: maxRedirects,
},
}, { signal: controller.signal });
} catch (error) {
if (POLICY_FAILURE_CODES.has(error?.code)) {
return terminal(ATTEMPT_CODE.POLICY_DENIED, error.code, { stage: 'robots_fetch' });
}
const reason = error?.code === 'redirect_limit'
? 'robots_redirect_limit'
: 'robots_unreachable';
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, reason);
}
const statusCode = response.statusCode;
if (controller.signal.aborted) {
discardBody(response.body);
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, 'robots_timeout');
}
if (!Number.isInteger(statusCode) || statusCode < 100 || statusCode > 599) {
discardBody(response.body);
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, 'robots_protocol_error');
}
if (statusCode === 429 && attempt < retries) {
discardBody(response.body);
const delayMs = retryAfterMilliseconds(response.headers, nowMilliseconds(clock));
if (delayMs >= timeoutMs || controller.signal.aborted) {
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, 'robots_rate_limited');
}
try {
await sleep(delayMs, { signal: controller.signal });
} catch {
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, 'robots_timeout');
}
continue;
}
if (statusCode === 404 || (statusCode >= 400 && statusCode < 500
&& ![401, 403, 429].includes(statusCode))) {
discardBody(response.body);
const entry = { kind: 'allow_all', reason: statusCode === 404 ? 'robots_not_found' : 'robots_unavailable' };
remember(origin, entry, nowMilliseconds(clock));
return decide(entry, targetUrl, 'miss');
}
if ([401, 403, 429].includes(statusCode)) {
discardBody(response.body);
const reason = statusCode === 429 ? 'robots_rate_limited' : 'robots_access_denied';
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, reason, { statusCode });
}
if (statusCode >= 500 || statusCode < 200 || statusCode >= 300) {
discardBody(response.body);
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, 'robots_unreachable', { statusCode });
}
const contentLength = singleHeader(response.headers, 'content-length');
if (contentLength !== null
&& (!/^\d+$/u.test(contentLength.trim()) || Number(contentLength) > maxBodyBytes)) {
discardBody(response.body);
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, 'robots_body_limit');
}
let parsed;
try {
const bytes = await readBoundedBody(response.body, maxBodyBytes, controller.signal);
const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
parsed = parseRobots(text, { userAgent: ROBOTS_USER_AGENT, maxBytes: maxBodyBytes });
} catch {
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, 'robots_parse_failed');
}
const entry = { kind: 'parsed', parsed };
remember(origin, entry, nowMilliseconds(clock));
return decide(entry, targetUrl, 'miss');
}
return terminal(ATTEMPT_CODE.ROBOTS_DENIED, 'robots_rate_limited');
} finally {
clearTimer(timer);
signal?.removeEventListener?.('abort', onAbort);
}
}
return Object.freeze({
check,
ttlMs: effectiveTtlMs,
clearCache: () => cache.clear(),
cacheInfo: () => Object.freeze({ size: cache.size, maxEntries: maxCacheEntries }),
});
}
+433
View File
@@ -0,0 +1,433 @@
import {
ATTEMPT_CODE,
ATTEMPT_KIND,
CAPABILITY_STATE,
RUN_STATUS,
createResultEnvelope,
deepFreeze,
} from './contracts.mjs';
import { authorizeCost } from './policy.mjs';
const COMMANDS = new Set(['url', 'crawl', 'extract', 'search', 'health']);
const STATES = new Set(Object.values(CAPABILITY_STATE));
const NETWORK_MODELS = new Set(['core-http', 'guard-proxy', 'provider-managed', 'none']);
const ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
function assertDescriptor(descriptor) {
if (!descriptor || typeof descriptor !== 'object' || !ID.test(descriptor.id ?? '')) {
throw new TypeError('capability descriptor has invalid id');
}
if (!STATES.has(descriptor.state)) throw new TypeError('capability descriptor has invalid state');
if (descriptor.version !== null && typeof descriptor.version !== 'string') {
throw new TypeError('capability descriptor has invalid version');
}
if (typeof descriptor.reason !== 'string' || descriptor.reason.length === 0) {
throw new TypeError('capability descriptor has invalid reason');
}
if (typeof descriptor.automatic !== 'boolean') throw new TypeError('capability descriptor has invalid routing flag');
if (!Array.isArray(descriptor.commands) || descriptor.commands.some((command) => !COMMANDS.has(command))) {
throw new TypeError('capability descriptor has invalid commands');
}
if (typeof descriptor.cost !== 'string' || !NETWORK_MODELS.has(descriptor.networkModel)) {
throw new TypeError('capability descriptor has invalid boundary');
}
if (descriptor.proofFingerprint !== undefined && descriptor.proofFingerprint !== null
&& typeof descriptor.proofFingerprint !== 'string') {
throw new TypeError('capability descriptor has invalid proof fingerprint');
}
if (descriptor.enable_with !== undefined && descriptor.enable_with !== null
&& typeof descriptor.enable_with !== 'string') {
throw new TypeError('capability descriptor has invalid enable hint');
}
}
export function createCapabilitySnapshot(registry) {
if (!Array.isArray(registry)) throw new TypeError('registry must be an array');
const seen = new Set();
const snapshot = registry.map((descriptor) => {
assertDescriptor(descriptor);
if (seen.has(descriptor.id)) throw new TypeError('registry contains duplicate adapter id');
seen.add(descriptor.id);
return {
id: descriptor.id,
version: descriptor.version,
state: descriptor.state,
reason: descriptor.reason,
automatic: descriptor.automatic,
commands: [...descriptor.commands],
cost: descriptor.cost,
price: Number.isFinite(descriptor.price) ? descriptor.price : null,
networkModel: descriptor.networkModel,
...(descriptor.proofFingerprint === undefined
? {} : { proofFingerprint: descriptor.proofFingerprint }),
...(descriptor.enable_with === undefined ? {} : { enable_with: descriptor.enable_with }),
};
});
return deepFreeze(snapshot);
}
function candidateFor(job, capability) {
const supported = capability.commands.includes(job.kind);
const cost = authorizeCost(capability);
const renderedAllowed = capability.networkModel !== 'guard-proxy' || job.policy.allowRendered;
const cloudAllowed = capability.networkModel !== 'provider-managed' || job.policy.allowFreeCloud;
const eligible = supported
&& capability.state === CAPABILITY_STATE.READY
&& cost.allowed
&& renderedAllowed
&& cloudAllowed;
let reason = 'eligible';
if (!supported) reason = 'unsupported_command';
else if (capability.state !== CAPABILITY_STATE.READY) reason = capability.reason;
else if (!cost.allowed) reason = cost.state;
else if (!renderedAllowed) reason = 'rendered_not_allowed';
else if (!cloudAllowed) reason = 'free_cloud_not_allowed';
return {
id: capability.id,
version: capability.version,
state: capability.state,
reason,
automatic: capability.automatic,
cost: capability.cost,
costState: cost.state,
networkModel: capability.networkModel,
eligible,
...(capability.proofFingerprint === undefined
? {} : { proofFingerprint: capability.proofFingerprint }),
...(capability.enable_with === undefined ? {} : { enable_with: capability.enable_with }),
};
}
export function buildRoutePlan(job, capabilitySnapshot, options = {}) {
if (!job || !COMMANDS.has(job.kind) || !Array.isArray(capabilitySnapshot)) {
throw new TypeError('cannot build route for invalid input');
}
const forcedEngine = options.forcedEngine ?? job.routing?.forcedEngine ?? null;
const selected = forcedEngine === null
? capabilitySnapshot.filter((entry) => entry.automatic && entry.commands.includes(job.kind))
: capabilitySnapshot.filter((entry) => entry.id === forcedEngine);
return deepFreeze({
schemaVersion: 1,
kind: job.kind,
goal: job.goal,
forcedEngine,
candidates: selected.map((entry) => candidateFor(job, entry)),
});
}
function decision(action, delayMs, status, code) {
return deepFreeze({ action, delayMs, status, code });
}
function invalidOutcome() {
return decision('stop', 0, RUN_STATUS.INTERNAL_ERROR, 'unknown_attempt_code');
}
function nextOrExhausted(code, hasNext) {
return hasNext
? decision('next', 0, null, code)
: decision('stop', 0, RUN_STATUS.EXHAUSTED, 'exhausted');
}
export function decideTransition(outcome, context = {}) {
if (!outcome || typeof outcome !== 'object') return invalidOutcome();
const hasNext = context.hasNext === true;
const retriesUsed = Number.isInteger(context.retriesUsed) && context.retriesUsed >= 0
? context.retriesUsed
: 0;
const retriesLimit = Number.isInteger(context.retriesLimit) && context.retriesLimit >= 0
? context.retriesLimit
: 0;
const maxRetryAfterMs = Number.isFinite(context.maxRetryAfterMs) && context.maxRetryAfterMs >= 0
? context.maxRetryAfterMs
: 15_000;
switch (outcome.code) {
case ATTEMPT_CODE.OK:
return outcome.kind === ATTEMPT_KIND.SUCCESS
? decision('stop', 0, RUN_STATUS.OK, ATTEMPT_CODE.OK)
: invalidOutcome();
case ATTEMPT_CODE.UNAVAILABLE:
case ATTEMPT_CODE.UNSUPPORTED:
case ATTEMPT_CODE.CLOUD_DISABLED:
case ATTEMPT_CODE.POLICY_UNENFORCEABLE:
return outcome.kind === ATTEMPT_KIND.SKIP
? nextOrExhausted(outcome.code, hasNext)
: invalidOutcome();
case ATTEMPT_CODE.TIMEOUT:
case ATTEMPT_CODE.NETWORK:
case ATTEMPT_CODE.HTTP_5XX:
if (outcome.kind !== ATTEMPT_KIND.RETRYABLE) return invalidOutcome();
if (retriesUsed < retriesLimit) return decision('retry_same', 0, null, outcome.code);
return nextOrExhausted(outcome.code, hasNext);
case ATTEMPT_CODE.RATE_LIMITED: {
if (outcome.kind !== ATTEMPT_KIND.RETRYABLE) return invalidOutcome();
if (retriesUsed >= retriesLimit) {
return decision('stop', 0, RUN_STATUS.BLOCKED, ATTEMPT_CODE.RATE_LIMITED);
}
const requested = Number.isFinite(outcome.retryAfterMs) && outcome.retryAfterMs > 0
? outcome.retryAfterMs
: 0;
return decision(
'retry_same',
Math.min(requested, maxRetryAfterMs),
null,
ATTEMPT_CODE.RATE_LIMITED,
);
}
case ATTEMPT_CODE.JS_SHELL:
case ATTEMPT_CODE.EMPTY:
case ATTEMPT_CODE.WRONG_MIME:
case ATTEMPT_CODE.PARSE_FAILED:
return outcome.kind === ATTEMPT_KIND.INADEQUATE
? nextOrExhausted(outcome.code, hasNext)
: invalidOutcome();
case ATTEMPT_CODE.POLICY_DENIED:
case ATTEMPT_CODE.ROBOTS_DENIED:
case ATTEMPT_CODE.ACCESS_DENIED:
case ATTEMPT_CODE.AUTH_REQUIRED:
case ATTEMPT_CODE.CAPTCHA:
case ATTEMPT_CODE.PAYWALL:
case ATTEMPT_CODE.PAID_REQUIRED:
case ATTEMPT_CODE.HARD_LIMIT:
return outcome.kind === ATTEMPT_KIND.TERMINAL
? decision('stop', 0, RUN_STATUS.BLOCKED, outcome.code)
: invalidOutcome();
case ATTEMPT_CODE.NOT_FOUND:
case ATTEMPT_CODE.GONE:
return outcome.kind === ATTEMPT_KIND.TERMINAL
? decision('stop', 0, RUN_STATUS.EXHAUSTED, outcome.code)
: invalidOutcome();
case ATTEMPT_CODE.ADAPTER_CRASH:
case ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR:
case ATTEMPT_CODE.HASH_MISMATCH:
return outcome.kind === ATTEMPT_KIND.BROKEN
? decision('stop', 0, RUN_STATUS.INTERNAL_ERROR, outcome.code)
: invalidOutcome();
default:
return invalidOutcome();
}
}
function inadequate(code, reason, fields = {}) {
return deepFreeze({
kind: ATTEMPT_KIND.INADEQUATE,
code,
details: { reason, ...fields },
});
}
export function acceptRepresentation({ goal, representation } = {}) {
if (!representation || typeof representation !== 'object' || Array.isArray(representation)) {
return inadequate(ATTEMPT_CODE.PARSE_FAILED, 'invalid_representation');
}
const missing = representation.requiredMissing ?? representation.missingRequired;
if (Array.isArray(missing) && missing.length > 0) {
return inadequate(ATTEMPT_CODE.PARSE_FAILED, 'required_fields_missing', {
missing: [...new Set(missing.filter((name) => typeof name === 'string'))].sort(),
});
}
const text = typeof representation.text === 'string'
? representation.text.trim()
: typeof representation.markdown === 'string'
? representation.markdown.trim()
: '';
const scriptCount = Number.isSafeInteger(representation.scriptCount)
? representation.scriptCount
: representation.jsShell === true ? 1 : 0;
if (['markdown', 'text'].includes(goal) && text.length === 0) {
return scriptCount > 0
? inadequate(ATTEMPT_CODE.JS_SHELL, 'proven_js_shell')
: inadequate(ATTEMPT_CODE.EMPTY, 'empty_main_content');
}
if (goal === 'json') {
const validJson = ['json', 'jsonld', 'schema'].includes(representation.kind)
|| (representation.data !== null && typeof representation.data === 'object');
if (!validJson) return inadequate(ATTEMPT_CODE.WRONG_MIME, 'wrong_representation');
}
if (goal === 'links' && !Array.isArray(representation.links)) {
return inadequate(ATTEMPT_CODE.WRONG_MIME, 'wrong_representation');
}
if (goal === 'metadata' && (!representation.metadata || typeof representation.metadata !== 'object')) {
return inadequate(ATTEMPT_CODE.WRONG_MIME, 'wrong_representation');
}
if (goal === 'raw') {
const length = representation.bytes?.length ?? representation.body?.length ?? representation.byteLength;
if (!Number.isSafeInteger(length) || length <= 0) {
return inadequate(ATTEMPT_CODE.EMPTY, 'empty_main_content');
}
}
if (!['raw', 'markdown', 'text', 'metadata', 'links', 'json'].includes(goal)) {
return inadequate(ATTEMPT_CODE.WRONG_MIME, 'wrong_representation');
}
return deepFreeze({ kind: ATTEMPT_KIND.SUCCESS, code: ATTEMPT_CODE.OK });
}
export function healthReport(capabilitySnapshot) {
if (!Array.isArray(capabilitySnapshot)) throw new TypeError('capability snapshot must be an array');
return deepFreeze(capabilitySnapshot.map((entry) => ({
id: entry.id,
state: entry.state,
version: entry.version,
reason: entry.reason,
automatic: entry.automatic,
commands: [...entry.commands],
cost: entry.cost,
networkModel: entry.networkModel,
...(entry.proofFingerprint === undefined ? {} : { proofFingerprint: entry.proofFingerprint }),
...(entry.enable_with === undefined ? {} : { enable_with: entry.enable_with }),
})));
}
const RENDERABLE_INADEQUATE = new Set([
ATTEMPT_CODE.JS_SHELL,
ATTEMPT_CODE.EMPTY,
ATTEMPT_CODE.PARSE_FAILED,
]);
export function renderedFallbackSkip(job, route, outcome) {
if (job?.policy?.allowRendered !== true || !Array.isArray(route)
|| outcome?.kind !== ATTEMPT_KIND.INADEQUATE || !RENDERABLE_INADEQUATE.has(outcome.code)) {
return null;
}
const candidate = route.find((entry) => entry?.id === 'playwright');
if (!candidate || candidate.eligible === true) return null;
return deepFreeze({
kind: ATTEMPT_KIND.SKIP,
code: ATTEMPT_CODE.POLICY_UNENFORCEABLE,
details: {
reason: candidate.reason || 'browser_security_gate_unavailable',
...(candidate.proofFingerprint ? { proofFingerprint: candidate.proofFingerprint } : {}),
},
});
}
function resultMessage(status) {
switch (status) {
case RUN_STATUS.OK: return 'Route completed';
case RUN_STATUS.BLOCKED: return 'Route stopped by policy';
case RUN_STATUS.EXHAUSTED: return 'No eligible route completed';
default: return 'Route contract failed';
}
}
function modelResult(job, plan, capabilities, status, code) {
return createResultEnvelope({
command: job.kind,
status,
code,
message: resultMessage(status),
route: plan.candidates,
capabilities,
warnings: [],
});
}
function adapterFrom(adapters, id) {
return adapters instanceof Map ? adapters.get(id) : adapters?.[id];
}
export async function runModelRoute(job, capabilitySnapshot, {
adapters = new Map(),
sleep = async () => {},
} = {}) {
const plan = buildRoutePlan(job, capabilitySnapshot);
const capabilities = healthReport(capabilitySnapshot);
const eligible = plan.candidates.filter((candidate) => candidate.eligible);
if (eligible.length === 0) {
return modelResult(job, plan, capabilities, RUN_STATUS.EXHAUSTED, 'no_eligible_engine');
}
for (let index = 0; index < eligible.length; index += 1) {
const candidate = eligible[index];
const adapter = adapterFrom(adapters, candidate.id);
if (!adapter || typeof adapter.run !== 'function') {
return modelResult(
job,
plan,
capabilities,
RUN_STATUS.INTERNAL_ERROR,
ATTEMPT_CODE.ADAPTER_PROTOCOL_ERROR,
);
}
let retriesUsed = 0;
while (true) {
let outcome;
try {
outcome = await adapter.run(job);
} catch {
outcome = { kind: ATTEMPT_KIND.BROKEN, code: ATTEMPT_CODE.ADAPTER_CRASH };
}
const transition = decideTransition(outcome, {
hasNext: index < eligible.length - 1,
retriesUsed,
retriesLimit: job.limits.retriesPerAdapter,
maxRetryAfterMs: job.limits.maxRetryAfterMs,
});
if (transition.action === 'retry_same') {
retriesUsed += 1;
try {
await sleep(transition.delayMs);
} catch {
return modelResult(job, plan, capabilities, RUN_STATUS.INTERNAL_ERROR, 'internal_error');
}
continue;
}
if (transition.action === 'next') break;
return modelResult(job, plan, capabilities, transition.status, transition.code);
}
}
return modelResult(job, plan, capabilities, RUN_STATUS.EXHAUSTED, 'exhausted');
}
export function createDefaultRegistry(nodeVersion) {
if (typeof nodeVersion !== 'string' || nodeVersion.length === 0) {
throw new TypeError('node version is required');
}
return deepFreeze([
{
id: 'core', version: nodeVersion, state: 'ready', reason: 'node_runtime', automatic: false,
commands: ['health'], cost: 'local-zero', price: 0, networkModel: 'none',
},
{
id: 'native', version: null, state: 'disabled', reason: 'phase_2_not_connected', automatic: true,
commands: ['url', 'crawl', 'extract'], cost: 'local-zero', price: 0, networkModel: 'core-http',
},
{
id: 'beautifulsoup', version: null, state: 'missing', reason: 'optional_parser_not_probed', automatic: false,
commands: ['extract'], cost: 'local-zero', price: 0, networkModel: 'none',
},
{
id: 'playwright', version: null, state: 'unavailable_security_gate',
reason: process.platform === 'darwin'
? 'hostile_egress_proof_missing:sandbox_loopback_scope_unproven'
: 'hostile_egress_proof_missing:sandbox_platform_unsupported',
proofFingerprint: null, enable_with: null, automatic: true,
commands: ['url', 'crawl', 'extract'], cost: 'local-zero', price: 0, networkModel: 'guard-proxy',
},
{
id: 'crawl4ai', version: null, state: 'unavailable_security_gate', reason: 'independent_security_proof_missing', automatic: true,
commands: ['url', 'crawl', 'extract'], cost: 'local-zero', price: 0, networkModel: 'guard-proxy',
},
{
id: 'browser-use', version: null, state: 'disabled', reason: 'automatic_path_forbidden', automatic: false,
commands: ['url', 'crawl', 'extract'], cost: 'local-zero', price: 0, networkModel: 'guard-proxy',
},
{
id: 'firecrawl', version: null, state: 'disabled', reason: 'free_cloud_not_allowed', automatic: true,
commands: ['url', 'crawl', 'extract', 'search'], cost: 'free-credit', price: null, networkModel: 'provider-managed',
},
{
id: 'scrapegraphai', version: null, state: 'disabled', reason: 'free_cloud_not_allowed', automatic: true,
commands: ['url', 'extract', 'search'], cost: 'free-credit', price: null, networkModel: 'provider-managed',
},
]);
}
+227
View File
@@ -0,0 +1,227 @@
// Bounded free-search model (CAP-05/06, DATA-05).
//
// A search run is discovery-then-scrape: one free provider returns candidate
// links, we normalize them through the same public-only policy every URL job
// obeys, then hand the first N permitted unique candidates to the shared URL
// runner. The provider's snippet is discovery metadata only — it never becomes
// captured evidence, and its body is never a top-level source hash. Everything
// fails closed: an empty registry, an ineligible/paid provider, or an
// out-of-bounds provider response all stop before any child or manifest.
import { RUN_STATUS, deepFreeze } from './contracts.mjs';
import { authorizeCost, parsePublicUrl } from './policy.mjs';
const MAX_RESULTS = 100;
const MAX_TEXT = 100_000;
function isObject(value) {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
// A search provider may be auto-selected only when it is ready, free, and proven
// zero-cost. Credentials or a binary never grant authority — a paid or disabled
// provider is filtered out even if present.
function isEligibleSearchProvider(provider) {
return isObject(provider)
&& provider.state === 'ready'
&& provider.automatic === true
&& Array.isArray(provider.commands)
&& provider.commands.includes('search')
&& typeof provider.search === 'function'
&& authorizeCost(provider).allowed;
}
export function createSearchRegistry(providers) {
const eligible = Array.isArray(providers) ? providers.filter(isEligibleSearchProvider) : [];
const frozen = Object.freeze([...eligible]);
return Object.freeze({
providers: frozen,
select() {
return frozen[0] ?? null;
},
});
}
class AdapterProtocolError extends Error {}
// The provider response is a trust boundary: exactly the four expected fields,
// each result exactly {url,title,snippet}, at least one and at most 100 results,
// no unbounded text. Any deviation is a broken adapter contract, not data.
function validateProviderResponse(raw) {
if (!isObject(raw) || Object.keys(raw).length !== 4) throw new AdapterProtocolError();
for (const key of ['requestUrl', 'evidenceUrl', 'accessedAt']) {
const value = raw[key];
if (typeof value !== 'string' || value.length === 0 || value.length > MAX_TEXT) {
throw new AdapterProtocolError();
}
}
const { results } = raw;
if (!Array.isArray(results) || results.length === 0 || results.length > MAX_RESULTS) {
throw new AdapterProtocolError();
}
for (const result of results) {
if (!isObject(result) || Object.keys(result).length !== 3) throw new AdapterProtocolError();
if (typeof result.url !== 'string' || result.url.length === 0 || result.url.length > MAX_TEXT) {
throw new AdapterProtocolError();
}
for (const key of ['title', 'snippet']) {
if (typeof result[key] !== 'string' || result[key].length > MAX_TEXT) {
throw new AdapterProtocolError();
}
}
}
return results;
}
// Drop private/invalid candidates, dedup by canonical URL (fragment already
// stripped by parsePublicUrl), and count each rejection reason for the warnings.
function normalizeCandidates(results) {
const seen = new Set();
const allowed = [];
let invalid = 0;
let duplicate = 0;
for (const result of results) {
let parsed;
try {
parsed = parsePublicUrl(result.url);
} catch {
invalid += 1;
continue;
}
if (seen.has(parsed.canonicalUrl)) {
duplicate += 1;
continue;
}
seen.add(parsed.canonicalUrl);
allowed.push({ url: parsed.canonicalUrl, title: result.title, snippet: result.snippet });
}
const warnings = [];
if (invalid > 0) warnings.push(`search_candidate_private_or_invalid:${invalid}`);
if (duplicate > 0) warnings.push(`search_candidate_duplicate:${duplicate}`);
return { allowed, warnings };
}
// Each scraped candidate is its own URL JobSpec: same shared run id, but its own
// per-attempt limits object so a child never mutates the search-level limits.
function childScrapeJob(job, run, canonicalUrl) {
return deepFreeze({
schemaVersion: 1,
kind: 'url',
target: { url: canonicalUrl },
goal: 'markdown',
limits: { ...job.limits },
policy: job.policy,
output: {
json: Boolean(job.output?.json),
format: 'markdown',
path: null,
dataRoot: job.output?.dataRoot ?? null,
},
routing: { explain: false, forcedEngine: null },
scope: { include: ['/**'], exclude: [] },
discovery: { sources: [], preferDiscoveredSource: false },
cache: { mode: 'use', ttlMs: 3_600_000 },
runId: run.id,
});
}
function modelResult(fields) {
return Object.freeze({ warnings: Object.freeze([]), ...fields });
}
export async function runSearchJob(job, {
registry,
storage,
clock = () => new Date(),
runUrlJob,
sharedRunContext,
} = {}) {
const selected = registry?.select?.() ?? registry?.providers?.[0] ?? null;
if (!selected) {
return modelResult({
status: RUN_STATUS.EXHAUSTED,
code: 'unavailable_no_free_search_provider',
message: 'no free search provider is configured',
});
}
const signal = sharedRunContext?.signal;
const budget = sharedRunContext?.budget;
if (signal?.aborted) {
return modelResult({
status: RUN_STATUS.INTERRUPTED,
code: 'interrupted',
message: 'search aborted before the provider was queried',
});
}
let results;
let providerEvidence;
try {
providerEvidence = await selected.search(job, { signal });
results = validateProviderResponse(providerEvidence);
} catch (error) {
return modelResult({
status: RUN_STATUS.INTERNAL_ERROR,
code: error instanceof AdapterProtocolError ? 'adapter_protocol_error' : 'adapter_crash',
message: 'search provider returned an out-of-contract response',
});
}
const { allowed, warnings } = normalizeCandidates(results);
const scrapePlan = allowed.slice(0, job.search.scrapeResults);
const run = await storage.beginRun(job);
const runContext = { ...sharedRunContext, run, runId: run.id };
const scraped = [];
const evidence = [];
for (const candidate of scrapePlan) {
if (signal?.aborted) break;
if (Number.isFinite(budget?.deadline) && clock().getTime() >= budget.deadline) break;
const childResult = await runUrlJob(childScrapeJob(job, run, candidate.url), runContext);
scraped.push({ url: candidate.url, status: childResult.status });
if (childResult.status === RUN_STATUS.OK && typeof childResult.source_hash === 'string') {
evidence.push({
url: candidate.url,
status: 'destination_source_captured',
source_hash: childResult.source_hash,
});
}
}
const commit = await storage.commitManifest(run, {
schema_version: 1,
run_id: run.id,
status: 'partial',
artifacts: [],
provider: {
id: selected.id,
version: selected.version,
request_url: providerEvidence.requestUrl,
evidence_url: providerEvidence.evidenceUrl,
accessed_at: providerEvidence.accessedAt,
},
cost_money: 0,
search: {
results: scrapePlan.map((candidate, index) => ({
rank: index + 1,
url: candidate.url,
title: candidate.title,
snippet: candidate.snippet,
snippet_kind: 'discovery_metadata',
})),
scraped,
},
evidence,
});
return modelResult({
status: RUN_STATUS.PARTIAL,
code: 'partial',
message: `discovered ${allowed.length} candidate(s), scraped ${scraped.length}`,
warnings: Object.freeze(warnings),
manifest_path: commit.path,
search_limits: job.limits,
});
}
+1026
View File
File diff suppressed because it is too large Load Diff