// NETWORK EXITS AT RUN TIME (lane network-exits): which exit a channel's // listing leaves through, the exits that rest after a rate limit, the counts // the trial is judged by, the operator's reassignment and `get network`. // The rules and the pure parts are lib/networkExits.ts; the proxy client is // lib/networkProxy-server.ts; the one caller that sends requests is the // listing in ytdlp/runYtdlp.ts. // // STATE, all small JSON: // channels//network-exit.json the channel's sticky exit (who chose it, when) // /.network/rests.json per `/`: until, fails // /.network/usage.json per day per `/`: counts // /.network/probe.json the last probe's answer per exit // None of them ever holds a proxy URL — only exit ids. import path from "node:path"; import { readdir } from "node:fs/promises"; import { readJsonFile, readJsonFileSync, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; import { getPaths, type Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import { alwaysCookies, cookieArgs, resolveCookiePolicy, type CookieMode } from "../lib/cookiePolicy"; import { platformArgs } from "../ytdlp/platformArgs.mjs"; import { readExitCredentials } from "../lib/networkCredentials-server"; import { getSettings } from "../lib/settings"; import { detectPlatform } from "../lib/platform"; import { DIRECT_EXIT, TRIAL_SCOPE, TRIAL_SCOPE_SENTENCE, exitById, exitPool, NetworkExitError, defaultNetworkSettings, ownProxy, exitDisplay, isRoutable, networkSettingsProblems, proxyUrlOf, requestJar, sanitizeNetwork, secretFragmentsOf, stickyExitFor, type NetworkExit, type NetworkSettings, } from "../lib/networkExits"; import { getThroughProxy, addressInEcho, preflightProxy } from "../lib/networkProxy-server"; import { nextBackoff, pruneExpired, type PlatformBackoffEntry } from "../jobs/platformBackoff"; import { platformCooldownRemainingMs } from "../jobs/downloadBackoff"; import { readChannelConfig } from "./channels"; export const NETWORK_STATE_DIRNAME = ".network"; export const CHANNEL_EXIT_FILENAME = "network-exit.json"; export const NETWORK_LIMITS_SENTENCE = "Network exits spread logged-out listing load across addresses and let the archive list a site that does " + "not answer the home address. They are not a disguise: no fingerprint or user-agent spoofing is added, and " + "a login is never moved between addresses."; export function networkStateDir(paths: Paths): string { return path.join(paths.transcriptsDir, NETWORK_STATE_DIRNAME); } function stateFile(paths: Paths, name: string): string { return path.join(networkStateDir(paths), name); } export function channelExitPath(paths: Paths, slug: string): string { return path.join(paths.channelsDir, slug, CHANNEL_EXIT_FILENAME); } function settingsNetwork(): NetworkSettings | undefined { try { return getSettings().network; } catch { return undefined; } } function isObject(v: unknown): v is Record { return typeof v === "object" && v !== null && !Array.isArray(v); } const key = (platform: string, exit: string) => `${platform}/${exit}`; // --------------------------------------------------------------------------- // THE CHANNEL'S STICKY EXIT export type ChannelExitRecord = { platform: string; exit: string; // "hash": stickyExitFor chose it; "operator": `pnpm ops network-exit`. by: "hash" | "operator"; at: string; previous?: string; reason?: string; }; export async function readChannelExitRecord( paths: Paths, slug: string, ): Promise { const r = await readJsonFile(channelExitPath(paths, slug)); if (!r.ok || !isObject(r.value)) return null; const v = r.value; if (typeof v.platform !== "string" || typeof v.exit !== "string") return null; return { platform: v.platform, exit: v.exit, by: v.by === "operator" ? "operator" : "hash", at: typeof v.at === "string" ? v.at : "", ...(typeof v.previous === "string" ? { previous: v.previous } : {}), ...(typeof v.reason === "string" ? { reason: v.reason } : {}), }; } // THE FIRST LISTING CHOOSES; NOTHING ELSE DOES (review 1, finding 5). With // no record for this platform the hash chooses over the pool and the choice // is written. A record is honoured while its exit is in the pool (or is the // operator's `direct`); a recorded exit that is disabled or removed FAILS the // listing — it is never re-chosen and never sent direct. Only // assignChannelExit (`pnpm ops network-exit`) moves a channel. async function stickyChannelExit( paths: Paths, slug: string, platform: string, pool: readonly string[], now: Date, ): Promise { const file = channelExitPath(paths, slug); return withJsonFileLock(file, async () => { const rec = await readChannelExitRecord(paths, slug); if (rec && rec.platform === platform) { if (pool.includes(rec.exit)) return rec.exit; if (rec.by === "operator" && rec.exit === DIRECT_EXIT) return rec.exit; throw new NetworkExitError( rec.exit, `this channel's recorded network exit "${rec.exit}" is no longer an enabled exit of ${platform} ` + `(enabled: ${pool.join(", ") || "none"}). The ${platform} listing was not sent; a channel is never moved by ` + `itself — reassign it: pnpm ops network-exit --json '{"slug":"${slug}","exit":""}'.`, ); } const exit = stickyExitFor(slug, pool); const next: ChannelExitRecord = { platform, exit, by: "hash", at: now.toISOString(), ...(rec ? { previous: rec.exit, reason: `the channel moved from ${rec.platform} to ${platform}` } : {}), }; await writeJsonAtomic(file, next, { mkdir: true }); return exit; }); } // --------------------------------------------------------------------------- // THE SETTINGS, READ STRICTLY FOR A ROUTE (review 1, finding 5) // // getSettings() answers defaults for a file it cannot read, which for a route // would mean "no policy": direct, silently. The listing reads the file itself: // absent = no policy; unreadable, not JSON, or a network block the writers // would refuse = the listing FAILS. export type StrictNetwork = { ok: true; network: NetworkSettings | undefined } | { ok: false; reason: string }; export function loadNetworkStrict(file: string = getPaths().settingsFile): StrictNetwork { const r = readJsonFileSync(file); if (!r.ok) { return r.reason === "absent" ? { ok: true, network: undefined } : { ok: false, reason: `settings.json could not be read (${r.reason})` }; } const raw = isObject(r.value) ? r.value.network : undefined; if (raw === undefined) return { ok: true, network: undefined }; const problems = networkSettingsProblems(raw); if (problems.length) return { ok: false, reason: `the network settings do not validate: ${problems.join("; ")}` }; return { ok: true, network: sanitizeNetwork(raw) }; } // --------------------------------------------------------------------------- // THE ROUTE OF ONE LISTING export type ListingRoute = // No policy for the platform (or the kind is outside the trial, or the // channel's own args carry a --proxy): today's request, untouched. | { kind: "none" } // Under a policy, and direct: a login is pinned, or the channel's exit is // `direct` (the hash chose it from a policy that names it, or the operator). | { kind: "direct"; why: "jar" | "assigned"; jar?: string } // Through an exit: its stored (secret-free) form, and — for the child only — // the proxy URL with its credentials and the exact values to scrub. | { kind: "exit"; exit: NetworkExit; proxyUrl: string; secrets: string[] }; // THE JAR'S EXIT. The trial never routes a login: whatever settings.json // says (the writers refuse an assignment; a hand edit fails validation), a // request carrying one goes direct. Widening this is one deliberate change. export const JAR_ROUTING_ALLOWED = false; export function jarExit(network: NetworkSettings | undefined, jar: string): string { if (!JAR_ROUTING_ALLOWED) return DIRECT_EXIT; return network?.jars[jar] ?? DIRECT_EXIT; } export async function resolveListingRoute(args: { paths: Paths; slug: string; platform: string; argv: readonly string[]; network?: NetworkSettings; now?: Date; env?: Readonly>; }): Promise { // Only the trial's platforms can be routed; every other listing is today's // without reading anything. if (!isRoutable(args.platform, "listing")) return { kind: "none" }; let network = args.network; if (!network) { const strict = loadNetworkStrict(args.paths.settingsFile); if (!strict.ok) { throw new NetworkExitError( DIRECT_EXIT, `${strict.reason}; the ${args.platform} listing was not sent — a listing never goes direct because its ` + `network settings could not be read.`, ); } network = strict.network; } const pool = exitPool(network, args.platform, "listing"); if (pool === null || ownProxy(args.argv)) return { kind: "none" }; const jar = requestJar(args.argv); if (jar && jarExit(network, jar) === DIRECT_EXIT) return { kind: "direct", why: "jar", jar }; // A POLICY WITH NO ENABLED EXIT FAILS (review 2, finding 3): `direct` is // used only when the policy NAMES it — never because every exit is off. if (pool.length === 0) { throw new NetworkExitError( DIRECT_EXIT, `network.platforms.${args.platform} has no enabled exit (${network!.platforms[args.platform]!.exits.join(", ")}) — ` + `the exits were turned off but the policy left in place. The ${args.platform} listing was not sent: enable an ` + `exit, list "direct" in the policy, or remove the policy ({"platforms":{"${args.platform}":null}}).`, ); } const id = await stickyChannelExit(args.paths, args.slug, args.platform, pool, args.now ?? new Date()); if (id === DIRECT_EXIT) return { kind: "direct", why: "assigned" }; const exit = exitById(network, id); if (!exit) throw new NetworkExitError(id, `network exit "${id}" is not defined; the ${args.platform} listing was not sent.`); const creds = readExitCredentials(exit, { file: network!.credentialsFile, ...(args.env ? { env: args.env } : {}) }); if (!creds.ok) { throw new NetworkExitError(id, `${creds.reason} The ${args.platform} listing was not sent — it never falls back to direct.`); } return { kind: "exit", exit, proxyUrl: proxyUrlOf(exit, creds.creds), secrets: secretFragmentsOf(creds.creds) }; } // WHETHER A CHANNEL'S LISTING CAN LEAVE THROUGH AN EXIT AT ALL: on a trial // platform and carrying no login (its cookies by the resolved policy, its own // args). A Rumble channel made with the defaults carries the Firefox // clearance cookie, so it cannot. `global` is settings' cookie pair. export function listingRoutable( config: ChannelConfig, global: { cookiesFromBrowser?: string; cookieMode?: CookieMode }, ): boolean { const platform = detectPlatform(config.url) ?? "unknown"; if (!isRoutable(platform, "listing")) return false; const argv = [ ...cookieArgs(alwaysCookies(resolveCookiePolicy(global, config))), ...platformArgs(detectPlatform(config.url)), ...(config.ytdlpExtraArgs ?? []), ]; return requestJar(argv) === null; } // --------------------------------------------------------------------------- // RESTS type RestState = Record; async function readRests(paths: Paths): Promise { const r = await readJsonFile(stateFile(paths, "rests.json")); const out: RestState = {}; if (!r.ok || !isObject(r.value)) return out; for (const [k, v] of Object.entries(r.value)) { if (!isObject(v)) continue; const until = Number(v.until); const fails = Number(v.fails); if (!Number.isFinite(until) || !Number.isFinite(fails)) continue; out[k] = { until, fails, since: Number.isFinite(Number(v.since)) ? Number(v.since) : until }; } return out; } export async function exitRestUntil( paths: Paths, platform: string, exit: string, now: number = Date.now(), ): Promise { if (exit === DIRECT_EXIT) return null; const e = (await readRests(paths))[key(platform, exit)]; return e && e.until > now ? e.until : null; } // A RATE LIMIT OR BOT CHECK THROUGH AN EXIT RESTS THAT EXIT for the // platform, on the platform cooldown's own curve (jobs/platformBackoff.ts // nextBackoff: 1 min doubling to 30, jittered). `allRest` — every exit of // the pool now rests (direct counting as resting while the platform cools // down) — is when the caller records the platform's own backoff, as today. export async function restExit( paths: Paths, platform: string, exit: string, pool: readonly string[], now: number = Date.now(), rand?: () => number, ): Promise<{ until: number; allRest: boolean }> { const file = stateFile(paths, "rests.json"); const until = await withJsonFileLock(file, async () => { const rests = await readRests(paths); pruneExpired(rests, now); const prev = rests[key(platform, exit)]; const next = nextBackoff(prev, now, rand); rests[key(platform, exit)] = { ...next, since: prev && prev.until > now ? prev.since : now }; await writeJsonAtomic(file, rests, { mkdir: true }); return next.until; }); return { until, allRest: await allExitsRest(paths, platform, pool, now) }; } export async function allExitsRest( paths: Paths, platform: string, pool: readonly string[], now: number = Date.now(), ): Promise { if (pool.length === 0) return false; const rests = await readRests(paths); for (const exit of pool) { if (exit === DIRECT_EXIT) { const ms = await platformCooldownRemainingMs(platform, paths).catch(() => 0); if (ms <= 0) return false; continue; } const e = rests[key(platform, exit)]; if (!e || e.until <= now) return false; } return true; } // A clean listing through the exit forgets its rest (and its escalation). export async function clearExitRest( paths: Paths, platform: string, exit: string, ): Promise { const file = stateFile(paths, "rests.json"); await withJsonFileLock(file, async () => { const rests = await readRests(paths); if (!rests[key(platform, exit)]) return; delete rests[key(platform, exit)]; await writeJsonAtomic(file, rests, { mkdir: true }); }); } function clock(ms: number): string { const d = new Date(ms); return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; } export function restingSentence(platform: string, exit: string, until: number): string { return ( `${platform} exit "${exit}" rests until ${clock(until)} after a rate limit; this channel's listing waits ` + `for it (a channel never moves to another exit on a failure).` ); } // The manual Sync gate's notice: the channel's recorded exit rests. Reads // only — never chooses or writes an exit. export async function listingRestRefusal( paths: Paths, slug: string, url: string | undefined, network: NetworkSettings | undefined = settingsNetwork(), now: number = Date.now(), ): Promise<{ sentence: string; until: number } | null> { const platform = detectPlatform(url) ?? "unknown"; const pool = exitPool(network, platform, "listing"); if (!pool) return null; const rec = await readChannelExitRecord(paths, slug); if (!rec || rec.platform !== platform || rec.exit === DIRECT_EXIT || !pool.includes(rec.exit)) return null; const until = await exitRestUntil(paths, platform, rec.exit, now); return until ? { sentence: restingSentence(platform, rec.exit, until), until } : null; } // --------------------------------------------------------------------------- // USAGE — the numbers the trial compares against `direct` export type NetworkUsageCounts = { requests: number; rateLimits: number; botChecks: number; rests: number; proxyFailures: number; }; const COUNT_KEYS: readonly (keyof NetworkUsageCounts)[] = ["requests", "rateLimits", "botChecks", "rests", "proxyFailures"]; const USAGE_KEEP_DAYS = 8; function zero(): NetworkUsageCounts { return { requests: 0, rateLimits: 0, botChecks: 0, rests: 0, proxyFailures: 0 }; } function dayOf(ms: number): string { return new Date(ms).toISOString().slice(0, 10); } type UsageFile = { days: Record> }; async function readUsage(paths: Paths): Promise { const r = await readJsonFile(stateFile(paths, "usage.json")); const out: UsageFile = { days: {} }; if (!r.ok || !isObject(r.value) || !isObject(r.value.days)) return out; for (const [day, rows] of Object.entries(r.value.days)) { if (!/^\d{4}-\d{2}-\d{2}$/.test(day) || !isObject(rows)) continue; out.days[day] = {}; for (const [k, v] of Object.entries(rows)) { if (!isObject(v)) continue; const c = zero(); for (const f of COUNT_KEYS) c[f] = Math.max(0, Math.floor(Number(v[f]) || 0)); out.days[day]![k] = c; } } return out; } export async function countNetworkUse( paths: Paths, platform: string, exit: string, delta: Partial, now: number = Date.now(), ): Promise { const file = stateFile(paths, "usage.json"); await withJsonFileLock(file, async () => { const usage = await readUsage(paths); const day = dayOf(now); const row = ((usage.days[day] ??= {})[key(platform, exit)] ??= zero()); for (const f of COUNT_KEYS) row[f] += delta[f] ?? 0; const keep = new Set(Array.from({ length: USAGE_KEEP_DAYS }, (_, i) => dayOf(now - i * 86_400_000))); for (const d of Object.keys(usage.days)) if (!keep.has(d)) delete usage.days[d]; await writeJsonAtomic(file, usage, { mkdir: true }); }); } export async function usageOver( paths: Paths, days: number, now: number = Date.now(), ): Promise> { const usage = await readUsage(paths); const out: Record = {}; for (let i = 0; i < days; i++) { for (const [k, c] of Object.entries(usage.days[dayOf(now - i * 86_400_000)] ?? {})) { const row = (out[k] ??= zero()); for (const f of COUNT_KEYS) row[f] += c[f]; } } return out; } // --------------------------------------------------------------------------- // THE OPERATOR'S REASSIGNMENT — `pnpm ops network-exit {slug, exit}` export class NetworkInputError extends Error {} export async function assignChannelExit(args: { paths: Paths; slug: string; exit: string; network?: NetworkSettings; now?: Date; }): Promise<{ slug: string; platform: string; exit: string; previous: string | null }> { const network = args.network ?? settingsNetwork(); const config = await readChannelConfig(args.paths, args.slug); if (!config) throw new NetworkInputError(`Channel "${args.slug}" not found`); const platform = detectPlatform(config.url) ?? config.platform ?? "unknown"; const pool = exitPool(network, platform, "listing"); if (pool === null) { throw new NetworkInputError( `"${args.slug}" is a ${platform} channel, and ${platform} has no network policy` + (isRoutable(platform, "listing") ? " — set network.platforms." + platform + " first" : ` — ${TRIAL_SCOPE_SENTENCE}`), ); } if (args.exit !== DIRECT_EXIT && !pool.includes(args.exit)) { const known = exitById(network, args.exit); throw new NetworkInputError( known ? `exit "${args.exit}" is ${known.enabled ? `not in ${platform}'s policy` : "disabled"} — ${platform}'s enabled exits: ${pool.join(", ") || "none"}` : `no exit "${args.exit}" — ${platform}'s enabled exits: ${pool.join(", ") || "none"} (and "direct")`, ); } const file = channelExitPath(args.paths, args.slug); return withJsonFileLock(file, async () => { const rec = await readChannelExitRecord(args.paths, args.slug); const next: ChannelExitRecord = { platform, exit: args.exit, by: "operator", at: (args.now ?? new Date()).toISOString(), ...(rec && rec.exit !== args.exit ? { previous: rec.exit, reason: "reassigned by the operator" } : {}), }; await writeJsonAtomic(file, next, { mkdir: true }); return { slug: args.slug, platform, exit: args.exit, previous: rec?.exit ?? null }; }); } // --------------------------------------------------------------------------- // THE PROBE AND THE REPORT — `pnpm ops get network [--probe]` export type ExitProbe = { at: string; reachable: boolean; reason?: string; ms?: number; // The address the echo URL saw through this exit (only with echoUrl set). address?: string | null; echoError?: string; }; type ProbeFile = { at: string; exits: Record }; async function readProbe(paths: Paths): Promise { const r = await readJsonFile(stateFile(paths, "probe.json")); if (!r.ok || !isObject(r.value) || !isObject(r.value.exits)) return null; return r.value as unknown as ProbeFile; } // EACH ENABLED EXIT'S PROXY is asked to answer. Two depths (review 1, // finding 6): // - the startup probe (`explicit` false): a TCP (or TLS) connect only — no // greeting, no login, no destination, no echo; // - the operator's `get network --probe` (`explicit` true): the preflight a // listing makes (connect, SOCKS greeting and login) and, only when // `echoUrl` is set, that URL fetched through each exit and once direct to // name the address each presents. export async function probeNetworkExits( paths: Paths, network: NetworkSettings | undefined = settingsNetwork(), now: Date = new Date(), deps: { explicit?: boolean; preflight?: typeof preflightProxy; get?: typeof getThroughProxy; getDirect?: (url: string) => Promise<{ ok: true; body: string } | { ok: false; reason: string }>; env?: Readonly>; } = {}, ): Promise { const preflight = deps.preflight ?? preflightProxy; const get = deps.get ?? getThroughProxy; const explicit = deps.explicit === true; const out: ProbeFile = { at: now.toISOString(), exits: {} }; for (const e of network?.exits ?? []) { if (!e.enabled) continue; let url = proxyUrlOf(e, null); if (explicit) { const creds = readExitCredentials(e, { file: network!.credentialsFile, ...(deps.env ? { env: deps.env } : {}) }); if (!creds.ok) { out.exits[e.id] = { at: now.toISOString(), reachable: false, reason: creds.reason }; continue; } url = proxyUrlOf(e, creds.creds); } const pf = await preflight(url, undefined, { connectOnly: !explicit }); const probe: ExitProbe = { at: now.toISOString(), reachable: pf.ok }; if (pf.ok) probe.ms = pf.ms; else probe.reason = pf.reason; if (explicit && pf.ok && network?.echoUrl) { const r = await get(url, network.echoUrl); if (r.ok) probe.address = addressInEcho(r.body); else probe.echoError = r.reason; } out.exits[e.id] = probe; } if (explicit && network?.echoUrl && deps.getDirect) { const r = await deps.getDirect(network.echoUrl); out.exits[DIRECT_EXIT] = { at: now.toISOString(), reachable: true, ...(r.ok ? { address: addressInEcho(r.body) } : { echoError: r.reason }), }; } await writeJsonAtomic(stateFile(paths, "probe.json"), out, { mkdir: true }); return out; } export type NetworkReportView = { limits: string; trialScope: { platforms: typeof TRIAL_SCOPE; sentence: string }; // Built from the stored form: there is no secret in it to mask. exits: Array<{ id: string; label: string; display: string; scheme: string | null; host: string | null; port: number | null; credentials: boolean; enabled: boolean; probe: ExitProbe | null; channels: number; }>; platforms: Record< string, NetworkSettings["platforms"][string] & { pool?: string[]; allRest?: boolean; ignored?: string } >; jars: Record; echoUrl: string; credentialsFile: string; startupProbe: boolean; settingsProblem: string | null; rests: Array<{ platform: string; exit: string; until: string; fails: number }>; usage: { "1d": Record; "7d": Record }; lastProbeAt: string | null; }; // How many channels are recorded on each exit (a disabled exit's channels // fail their listings until reassigned — the report says how many). async function channelsByExit(paths: Paths): Promise> { const out: Record = {}; let slugs: string[] = []; try { slugs = await readdir(paths.channelsDir); } catch { return out; } for (const slug of slugs) { const rec = await readChannelExitRecord(paths, slug); if (rec) out[rec.exit] = (out[rec.exit] ?? 0) + 1; } return out; } export async function networkReport( paths: Paths, network?: NetworkSettings, now: number = Date.now(), ): Promise { let settingsProblem: string | null = null; if (!network) { const strict = loadNetworkStrict(paths.settingsFile); if (strict.ok) network = strict.network; else { settingsProblem = strict.reason; network = settingsNetwork(); } } const rests = await readRests(paths); const probe = await readProbe(paths); const counts = await channelsByExit(paths); const platforms: NetworkReportView["platforms"] = {}; for (const [platform, policy] of Object.entries(network?.platforms ?? {})) { const pool = exitPool(network, platform, "listing"); platforms[platform] = { ...policy, ...(pool === null ? { ignored: TRIAL_SCOPE_SENTENCE } : { pool, allRest: await allExitsRest(paths, platform, pool, now) }), }; } const d = defaultNetworkSettings(); return { limits: NETWORK_LIMITS_SENTENCE, trialScope: { platforms: TRIAL_SCOPE, sentence: TRIAL_SCOPE_SENTENCE }, exits: [ { id: DIRECT_EXIT, label: "Direct (no proxy)", display: "no proxy", scheme: null, host: null, port: null, credentials: false, enabled: true, probe: probe?.exits[DIRECT_EXIT] ?? null, channels: counts[DIRECT_EXIT] ?? 0, }, ...(network?.exits ?? []).map((e) => ({ id: e.id, label: e.label, display: exitDisplay(e), scheme: e.scheme, host: e.host, port: e.port, credentials: e.credentials, enabled: e.enabled, probe: probe?.exits[e.id] ?? null, channels: counts[e.id] ?? 0, })), ], platforms, jars: network?.jars ?? {}, echoUrl: network?.echoUrl ?? "", credentialsFile: network?.credentialsFile ?? d.credentialsFile, startupProbe: network?.startupProbe ?? d.startupProbe, settingsProblem, rests: Object.entries(rests) .filter(([, e]) => e.until > now) .map(([k, e]) => { const [platform = "", exit = ""] = k.split("/"); return { platform, exit, until: new Date(e.until).toISOString(), fails: e.fails }; }), usage: { "1d": await usageOver(paths, 1, now), "7d": await usageOver(paths, 7, now) }, lastProbeAt: probe?.at ?? null, }; } // THE STARTUP PROBE: once, a minute after the editor boots, when an exit is // enabled and `network.startupProbe` is on — a TCP connect to each proxy and // nothing else (no greeting, no destination, no echo). One line per exit in // the server log; the answers land in probe.json. Never throws; armed below // the idle gate (editor/instrumentation.ts). export function startupNetworkProbe(opts: { log: (line: string) => void; delayMs?: number; paths?: Paths }): void { const t = setTimeout(() => { void (async () => { try { const paths = opts.paths ?? getPaths(); const strict = loadNetworkStrict(paths.settingsFile); if (!strict.ok) return opts.log(`network exits: no startup probe — ${strict.reason}`); const network = strict.network; if (!network?.startupProbe || !network.exits.some((e) => e.enabled)) return; const probe = await probeNetworkExits(paths, network, new Date(), { explicit: false }); for (const [id, p] of Object.entries(probe.exits)) { opts.log(`network exit "${id}": ${p.reachable ? "accepts a connection" : `unreachable — ${p.reason ?? "?"}`}`); } } catch (e) { opts.log(`network exits: the startup probe failed — ${(e as Error).message}`); } })(); }, opts.delayMs ?? 60_000); t.unref?.(); } // What the listing needs to send a request through an exit, read once per // listing: the pool (for the all-rest check). export function listingPool(network: NetworkSettings | undefined, platform: string): string[] | null { return exitPool(network ?? settingsNetwork(), platform, "listing"); } export { TRIAL_SCOPE };