Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 15584ab0a88ad252a574204a5cad152fcfd5ee0c
parent 3be0f116f451b0977fcf0ff318f8a1476ba7dd7e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 13:11:08 -0500

editor: network exits — ops network / network-exit / get network, /settings section, masked answers

`pnpm ops network` and /settings → Network exits write through one writer that keeps a
masked proxy's stored credentials and refuses what the trial does not route; `network`
is an owned key for `pnpm ops settings` and the settings writer's floor refuses it too.
`pnpm ops network-exit {slug, exit}` reassigns one channel. `pnpm ops get network
[--probe]` reports exits, rests and 1/7-day counts. Every ops answer masks a URL's
credentials; /settings never sends the raw block to the browser. A manual Sync on a
resting exit answers its sentence. OPERATING.md recipe, SETTINGS.md and COMMANDS.md
regenerated, integration tests against in-process fake SOCKS5 proxies.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 5++++-
MOPERATING.md | 43+++++++++++++++++++++++++++++++++++++++++++
MSETTINGS.md | 46++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/networkExits.ts | 21++++++++++++++++++---
Acommon/ytdlp/networkExitListing.test.ts | 331+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/CHANGELOG.md | 13+++++++++++++
Meditor/app/api/ops/_read.ts | 6++++++
Aeditor/app/api/ops/network-exit/route.ts | 25+++++++++++++++++++++++++
Aeditor/app/api/ops/network/route.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/settings/patch.ts | 4++++
Aeditor/app/settings/components/NetworkExitsSection.tsx | 261+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/settings/components/SettingsForm.tsx | 4+++-
Aeditor/app/settings/networkActions.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/settings/networkProbe.ts | 12++++++++++++
Aeditor/app/settings/networkSave.test.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/settings/networkSave.ts | 35+++++++++++++++++++++++++++++++++++
Meditor/app/settings/page.tsx | 12+++++++++++-
Meditor/app/settings/saveSettings.ts | 8++++++++
Mscripts/archilyzer-ops.mjs | 49+++++++++++++++++++++++++++++++++++++++++++++++--
Msettings.json.example | 6++++++
20 files changed, 1069 insertions(+), 8 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -196,8 +196,10 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). Orpheus also takes "tuning" ({"temperature": 0.1-1.5, "top\_p": 0.05-1, "top\_k": 0-200, "min\_p": 0-0.5, "repeat\_penalty": 1-2, "takes": 1-6}, any of them; the rest its defaults) and "reading" (0-99999; 0 = the first): the same words read again differently, a new cached file; kokoro and espeak-ng ignore both and say so in the result's "note". The expressive tags &lt;laugh&gt; &lt;chuckle&gt; &lt;sigh&gt; &lt;cough&gt; &lt;sniffle&gt; &lt;groan&gt; &lt;yawn&gt; &lt;gasp&gt; are performed by orpheus and stripped for the others; any other &lt;...&gt; is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure} (orpheus: also tuning, reading and seedBase, every value it was made with): wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait`<br>`pnpm ops tts --json '{"text":"Read it again.","engine":"orpheus","reading":1,"tuning":{"temperature":0.7}}' --wait` | | `voice-enhance` | voice-enhance cleans a speech recording up (denoise, soften the room, level it) as a job on the `voice` queue, behind the heavy slot: {"file": "/abs/take.wav", "out": "/abs/clean.wav"} (never inside the corpus; 48 kHz mono, exactly as long as the input), "engine" (deepfilternet \| rnnoise; settings.voice), "params" (the engine's knobs: lufs, highpass, attenLimDb, postFilter, mix), "parts" (\[{file, out}\], a take recorded part by part). deepfilternet needs `archilyzer voice setup --engine deepfilternet`; rnnoise needs nothing. The result is {op, engine, wav, seconds, samples, sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?, synthetic}; with --wait it is printed on stdout. | | | `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "&lt;tts engine&gt;:&lt;stock voice&gt;" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). "pitch" is where the result's pitch comes from (settings.voice.convert.pitch): "target" — the stock voice's own, the read's intonation flattened to it; "source" — the pitch the take was read at (raise your voice and it rises); "contour" — the read's rises and falls, moved as a whole to the stock voice's register. "semitones" (-12 to 12) then moves a followed pitch; left out, a followed pitch takes settings.voice.convert.semitones (0 unless set). source and contour are seed-vc's, on its optional f0 model (`archilyzer voice setup --engine seed-vc --with f0`; slower, 44.1 kHz); openvoice refuses them. The target's reference is synthesized once through the tts op and kept. The result adds target, voice, pitch (semitones and f0 — the medians heard and the move applied — when followed), synthetic: true and the disclosure line. | | -| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | +| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage, network — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | +| `network` | network writes the named network exits (settings.network) through their one writer, as /settings → Network exits: {"upsertExit": {"id", "label"?, "proxy"?, "enabled"?}}, {"removeExit": "&lt;id&gt;"} (also out of every policy), {"exits": \[...\]} (the whole list), {"platforms": {"&lt;platform&gt;": {"exits": \[ids, "direct" allowed\], "mode": "sticky"} \| null}}, {"jars": {...}}, {"echoUrl": "&lt;url&gt;" \| ""}. Proxy URLs: socks5h://, socks5://, http://, https:// with a port; credentials are secrets, answered as &lt;redacted&gt;@, and a masked proxy sent back keeps the stored one. THE TRIAL routes only rumble and twitch LISTINGS: any other platform or request kind, and any cookie jar given an exit, is refused whole, every problem named. A channel's exit is a stable hash of its slug over the enabled exits, recorded once; a listing that carries a login goes direct; a 429 or bot check rests that exit (its channels wait); a proxy that does not answer fails the listing naming the exit, never falling back to direct. Not a disguise: no fingerprint or user-agent changes, and a login never moves. get network \[--probe\] reports each exit, the rests and the 1- and 7-day counts; --probe asks each proxy to answer (and fetches network.echoUrl through it only when set). | `pnpm ops network --json '{"upsertExit":{"id":"exit-a","proxy":"socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080"}}'`<br>`pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","exit-a","exit-b"],"mode":"sticky"}}}'` | +| `network-exit` | network-exit reassigns one channel's exit: {"slug", "exit"} (an enabled exit of its platform's policy, or "direct"). The only way a channel moves besides its exit being removed or disabled. | `pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"exit-b"}'` | | `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /cookies) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The For "instagram" it sends Instagram NO request either and is the operator's word that its check is passed: it clears the alert, and the next Instagram job raises it again if it was not. The timer never asks Instagram. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). Asked while a recheck or another press for the service runs (a click, the dashboard's, the timer's): refused, 409 {busy: true}, never queued. dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -&gt; {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` | | `dismiss-service` | — | | | `rerun-service-jobs` | — | | @@ -266,6 +268,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] pnpm ops job wait <id>... [--wait-timeout <seconds>] pnpm ops get settings [<key>] pnpm ops get storage | sites | workers | auto-queue | scheduler + pnpm ops get network [--probe] pnpm ops get saved-alternates [<slug>] pnpm ops get compaction-review [<slug>] pnpm ops get kept-originals [<slug>] diff --git a/OPERATING.md b/OPERATING.md @@ -235,6 +235,49 @@ pnpm ops dismiss-service --json '{"service":"rumble"}' Recheck on the dashboard.` `archilyzer doctor` lists it under "service cookies". - The state is `transcripts/.service-cookies.json` (`common/lib/serviceCookies.ts`); never hand-edit it. +### Network exits: list through other addresses (trial) + +```sh +# two exits (worked example: Mullvad — while this machine is connected to the VPN, each WireGuard relay +# offers a SOCKS5 proxy on port 1080 at its own hostname, resolvable only inside the tunnel) +pnpm ops network --json '{"upsertExit":{"id":"nl-ams-1","proxy":"socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080"}}' +pnpm ops network --json '{"upsertExit":{"id":"se-sto-1","proxy":"socks5h://se-sto-wg-socks5-001.relays.mullvad.net:1080"}}' +# spread rumble's listings over them, direct kept in the pool as the comparison +pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","nl-ams-1","se-sto-1"],"mode":"sticky"}}}' +pnpm ops get network --probe # each proxy answers? (+ the address, with echoUrl set) +pnpm ops get network # rests and the 1/7-day counts per platform and exit +pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"se-sto-1"}' # move one channel by hand +pnpm ops network --json '{"platforms":{"rumble":null}}' # back to direct +``` + +- **What it is for**: spreading logged-out listing load over several addresses, and listing a site that + does not answer the home address. **Not a disguise**: no fingerprint or user-agent spoofing is added, + and a login is never moved between addresses. Sources: https://mullvad.net/en/help/socks5-proxy and + https://mullvad.net/en/help/different-entryexit-node-using-wireguard-and-socks5-proxy . +- **The trial routes only the LISTING (flat-playlist) requests of rumble and twitch.** Downloads, + metadata, subtitles, clips, live recordings and every other platform go direct; a policy for anything + else, or a cookie jar given an exit, is refused when saved (`TRIAL_SCOPE`, `common/lib/networkExits.ts`). +- **Sticky**: a channel's exit is a stable hash of its slug over the platform's enabled exits, chosen on its + first listing and recorded in `channels/<slug>/network-exit.json`. It moves only when that exit is removed + or disabled, or by `network-exit` — never per request, never on a failure. +- **A listing that carries a login goes direct** — cookies (`cookieMode` "always" with `cookiesFromBrowser`, + a cookie file, a Cookie header) or an account. A Rumble channel with its Firefox clearance jar therefore + stays direct: a clearance is bound to the address it was earned from. +- **Pacing is unchanged**: the queue gap, the pace, the cooldown and the hold count every exit together — + more exits never means more requests per hour. +- **A 429 or bot check through an exit rests that exit** for the platform, on the platform cooldown's curve; + the channels on it wait (their sync ends *deferred* until the rest ends) and never hop. When every exit of + the platform rests, the platform cools down as before. A clean listing through the exit ends its rest. +- **Fail closed**: a proxy that does not answer, refuses, or cannot log in fails the listing with + `network exit "<id>" (…) did not answer: … — a listing never falls back to direct`. `socks5h://` has the + proxy resolve the hostname; `socks5://` resolves it here. +- **Secrets**: credentials in a proxy URL (`socks5h://user:pass@host:port`) are never logged or recorded; + every answer shows `<redacted>@`, and the URL reaches yt-dlp on its stdin, not its command line. Records + store the exit id only (the roster's `lastSweep.exit`, the counts in `transcripts/.network/`). +- **Live recordings** (not built): a recording would take its channel's exit once at its start and keep it + for every part and reconnect; a dead proxy would end it failed, never continue direct. +- /settings → **Network exits** has every control above. + ## Import from archive.org, Odysee, BitChute and the Wayback Machine ```sh diff --git a/SETTINGS.md b/SETTINGS.md @@ -24,6 +24,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`livePreclip`](#livepreclip) | object — see below | | [`liveRecording`](#liverecording) | object — see below | | [`pacing`](#pacing) | object — see below | +| [`network`](#network) | object — see below | | [`downloadFormat`](#downloadformat) | `"auto"` | | [`sourceVideoQuality`](#sourcevideoquality) | `"original"` | | [`minFreeDiskGB`](#minfreediskgb) | `5` | @@ -300,6 +301,51 @@ Default: } ``` +## `network` + +NAMED NETWORK EXITS (lane network-exits): proxies a listing may leave through, a policy per platform queue, and which exit a logged-in request (a cookie jar) is pinned to. Absent or empty = every request goes direct, exactly as before. The trial routes only the listing requests of rumble and twitch, and no cookie jar may leave direct. Written by `pnpm ops network` / `pnpm ops network-exit` and /settings → Network exits, never by `pnpm ops settings`; `pnpm ops get network` reports each exit, its rests and its counts. Proxy credentials are secrets: redacted in every answer, log and record. See common/lib/networkExits.ts and controller/networkExits.ts. + +#### `network` + +| Key | Default | Description | +|---|---|---| +| `exits` | `[]` | NAMED NETWORK EXITS: proxies a fetch may leave through, `[{id, label, proxy, enabled}]` (table below). The exit `direct` (no proxy) always exists and is reserved. Written by `pnpm ops network` and /settings → Network exits, never by `pnpm ops settings`. It spreads logged-out listing load over addresses and lets the archive list a site that does not answer the home address; it is not a disguise — no fingerprint or user-agent spoofing is added, and a login never moves between addresses. Worked example, Mullvad: while the machine is connected to the VPN, each WireGuard relay offers a SOCKS5 proxy at its own hostname on port 1080 (`socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080`), resolvable only inside the tunnel — https://mullvad.net/en/help/socks5-proxy and https://mullvad.net/en/help/different-entryexit-node-using-wireguard-and-socks5-proxy . | +| `platforms` | `{}` | Which exits a platform queue's requests may use, keyed by platform: `{exits: [ids], mode: "sticky", kinds: ["listing"]}` (table below). Absent = every request goes direct, exactly as before. THE TRIAL routes only the LISTING (flat-playlist) requests of `rumble` and `twitch`; any other platform or kind is refused when saved, and ignored if written by hand. Each channel's exit is chosen once by a stable hash of its slug over the platform's enabled exits and recorded in `channels/<slug>/network-exit.json`; it changes only when that exit is removed or disabled, or by `pnpm ops network-exit`. Pacing stays per platform: the job gap, the pace, the cooldown and the hold count every exit together. A rate limit or bot check through an exit rests that exit for the platform (the platform cooldown's length); its channels' listings wait (the job ends deferred) and never move to another exit; when every exit rests the platform cools down as before. A proxy that does not answer fails the listing naming the exit — never a fallback to direct. | +| `jars` | `{}` | A cookie jar's one fixed exit, keyed by jar id (`browser:<spec>`, `file:<path>`, `login:<option>`, `header:<name>`). A request that carries a login is pinned: this exit, else direct — never the platform's pool, and a jar's exit is not changed while the jar is fresh. In the trial every assignment is refused: logged-in requests go direct (a Rumble channel listing with its Firefox clearance jar stays direct). | +| `echoUrl` | `""` | An address-echo URL (`http(s)://…`, answering the caller's public address as text) that `pnpm ops get network --probe` fetches through each exit to show the address it presents. Blank (the default) = the probe only checks that each proxy answers, and nothing else is requested. | + +#### `network.exits[]` + +Per entry — each entry spells its own values. + +| Key | Description | +|---|---| +| `id` | The exit's name in policies, records and `pnpm ops`: lowercase letters, digits and `-`, up to 40, not `direct`. Records store this, never the proxy URL. | +| `label` | A display name (defaults to the id). | +| `proxy` | The proxy URL with its port: `socks5h://host:port` (the hostname is resolved by the proxy), `socks5://host:port` (resolved here), `http://host:port` or `https://host:port`. Credentials (`socks5h://user:pass@host:port`) are a SECRET: never logged, never in an argv echo, a record or an ops answer — shown as `<redacted>@`. The URL reaches yt-dlp on its stdin, not its command line. | +| `enabled` | Off = the exit is out of every pool; channels recorded on it are re-chosen over the remaining exits on their next listing. | + +#### `network.platforms.<platform>` + +Per entry — each entry spells its own values. + +| Key | Description | +|---|---| +| `exits` | The exit ids the platform's channels are spread over, `direct` allowed. Disabled exits are skipped. | +| `mode` | `sticky` (the only mode): a channel keeps its exit; never chosen per request, never moved on a failure. | +| `kinds` | The request kinds routed (default `["listing"]`). The trial allows `listing` only. | + +Default: + +```json +{ + "exits": [], + "platforms": {}, + "jars": {}, + "echoUrl": "" +} +``` + ## `downloadFormat` Default yt-dlp `-f` download format for every channel that doesn't set its own (ChannelConfig.downloadFormat). "auto" picks per-source: `original` for Odysee (whose HLS rungs are CDN-truncated), `bestaudio/worst` elsewhere. See common/ytdlp/downloadFormat.ts. diff --git a/common/controller/networkExits.ts b/common/controller/networkExits.ts @@ -500,14 +500,29 @@ export async function probeNetworkExits( return out; } +export type NetworkReportView = { + limits: string; + trialScope: { platforms: typeof TRIAL_SCOPE; sentence: string }; + exits: Array<{ id: string; label: string; proxy: string | null; enabled: boolean; probe: ExitProbe | null }>; + platforms: Record< + string, + NetworkSettings["platforms"][string] & { pool?: string[]; allRest?: boolean; ignored?: string } + >; + jars: Record<string, string>; + echoUrl: string; + rests: Array<{ platform: string; exit: string; until: string; fails: number }>; + usage: { "1d": Record<string, NetworkUsageCounts>; "7d": Record<string, NetworkUsageCounts> }; + lastProbeAt: string | null; +}; + export async function networkReport( paths: Paths, network: NetworkSettings | undefined = settingsNetwork(), now: number = Date.now(), -): Promise<Record<string, unknown>> { +): Promise<NetworkReportView> { const rests = await readRests(paths); const probe = await readProbe(paths); - const platforms: Record<string, unknown> = {}; + const platforms: NetworkReportView["platforms"] = {}; for (const [platform, policy] of Object.entries(network?.platforms ?? {})) { const pool = exitPool(network, platform, "listing"); platforms[platform] = { @@ -536,7 +551,7 @@ export async function networkReport( rests: Object.entries(rests) .filter(([, e]) => e.until > now) .map(([k, e]) => { - const [platform, exit] = k.split("/"); + 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) }, diff --git a/common/ytdlp/networkExitListing.test.ts b/common/ytdlp/networkExitListing.test.ts @@ -0,0 +1,331 @@ +import { test, after, beforeEach } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, writeFileSync, chmodSync, mkdirSync, readFileSync, readdirSync, statSync, existsSync, rmSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/networkExitListing.test.ts +// +// THE LISTING THROUGH NAMED NETWORK EXITS (lane network-exits), end to end +// below yt-dlp: a stand-in yt-dlp records its argv and its stdin, and the +// exits are in-process fake SOCKS5 proxies on loopback. No request leaves +// 127.0.0.1. getPaths() memoizes, so the env is set before anything imports it. +const ROOT = mkdtempSync(path.join(os.tmpdir(), "network-exits-")); +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +writeFileSync(process.env.SETTINGS_FILE, "{}\n"); + +const { fetchFlatPlaylistUrls, EnumerationIncompleteError, NetworkExitError } = await import("./runYtdlp"); +const { getPaths } = await import("../lib/paths"); +const { JobDeferredError } = await import("../jobs/jobDeferred"); +const { platformCooldownRemainingMs } = await import("../jobs/downloadBackoff"); +const { stickyExitFor } = await import("../lib/networkExits"); +const NE = await import("../controller/networkExits"); +const { downloadQueueKey } = await import("../lib/queueKeys"); +const { waitForQueueGap, noteQueueJobEnd, clearQueueGaps } = await import("../jobs/queueGap"); +const { closedPort, startCountingServer, startFakeSocks5 } = await import("../testing/fakeProxy"); + +const SECRET = "hunter2-very-secret"; +const target = await startCountingServer(); +// The fakes tunnel nowhere: a listing's stand-in yt-dlp never really uses them. +const proxyA = await startFakeSocks5({ username: "user-a", password: SECRET, route: () => null }); +const proxyB = await startFakeSocks5({ route: () => null }); +after(async () => { + await Promise.all([target.close(), proxyA.close(), proxyB.close()]); + rmSync(ROOT, { recursive: true, force: true }); +}); + +const PROXY_A = `socks5h://user-a:${SECRET}@127.0.0.1:${proxyA.port}`; +const PROXY_B = `socks5h://127.0.0.1:${proxyB.port}`; + +// A stand-in yt-dlp: appends {argv, stdin} to $FAKE_RECORD, then answers per $FAKE_MODE. +const RECORD = path.join(ROOT, "spawns.jsonl"); +const BIN = path.join(ROOT, "fake-listing.mjs"); +writeFileSync( + BIN, + `#!/usr/bin/env node +import { appendFileSync, readFileSync } from "node:fs"; +const argv = process.argv.slice(2); +const stdin = argv.includes("--config-locations") ? readFileSync(0, "utf8") : null; +appendFileSync(process.env.FAKE_RECORD, JSON.stringify({ argv, stdin }) + "\\n"); +const mode = process.env.FAKE_MODE ?? "ok"; +if (mode === "verbose") process.stderr.write("[debug] | Stdin config: " + JSON.stringify(stdin) + "\\n"); +if (mode === "429") { + process.stdout.write("https://rumble.com/v1-a.html\\n"); + process.stderr.write("[RumbleChannel] x: Downloading page 2\\nERROR: [RumbleChannel] x: Unable to download webpage: HTTP Error 429: Too Many Requests\\n"); + process.exit(1); +} +process.stdout.write("https://rumble.com/v1-a.html\\nhttps://rumble.com/v2-b.html\\n"); +`, +); +chmodSync(BIN, 0o755); +process.env.FAKE_RECORD = RECORD; + +function settings(network?: unknown) { + writeFileSync( + process.env.SETTINGS_FILE!, + JSON.stringify({ pacing: { jitter: 0 }, ...(network ? { network } : {}) }) + "\n", + ); +} + +const EXITS = [ + { id: "exit-a", label: "A", proxy: PROXY_A, enabled: true }, + { id: "exit-b", label: "B", proxy: PROXY_B, enabled: true }, +]; +const RUMBLE_POLICY = { exits: EXITS, platforms: { rumble: { exits: ["exit-a", "exit-b"], mode: "sticky" } } }; + +// Two slugs, one on each exit of [exit-a, exit-b]. +const SLUGS = Array.from({ length: 40 }, (_, i) => `demo-rumble-${i}`); +const ON_A = SLUGS.find((s) => stickyExitFor(s, ["exit-a", "exit-b"]) === "exit-a")!; +const ON_B = SLUGS.find((s) => stickyExitFor(s, ["exit-a", "exit-b"]) === "exit-b")!; + +function spawns(): Array<{ argv: string[]; stdin: string | null }> { + if (!existsSync(RECORD)) return []; + return readFileSync(RECORD, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)); +} + +async function list(slug: string, config: Record<string, unknown> = {}, log: string[] = []) { + mkdirSync(path.join(ROOT, "channels", slug), { recursive: true }); + writeFileSync( + path.join(ROOT, "channels", slug, "config.json"), + JSON.stringify({ handling: "transcribe", url: "https://rumble.com/c/demo", ...config }), + ); + return fetchFlatPlaylistUrls({ + channelConfig: { handling: "transcribe", url: "https://rumble.com/c/demo", ...config } as never, + paths: { ...getPaths(), ytdlpBin: BIN }, + channelSlug: slug, + onLog: (s) => log.push(s), + signal: new AbortController().signal, + }); +} + +// Today's rumble listing argv (main a0ef2b1ae), pacing jitter off. +const MAIN_ARGV = ["--flat-playlist", "--skip-download", "--print", "url", "--impersonate", "chrome", "--sleep-requests", "1", "https://rumble.com/c/demo"]; + +beforeEach(() => { + rmSync(RECORD, { force: true }); + rmSync(path.join(ROOT, ".network"), { recursive: true, force: true }); + rmSync(path.join(ROOT, ".auto-queue"), { recursive: true, force: true }); + for (const d of existsSync(path.join(ROOT, "channels")) ? readdirSync(path.join(ROOT, "channels")) : []) { + rmSync(path.join(ROOT, "channels", d, "network-exit.json"), { force: true }); + } + process.env.FAKE_MODE = "ok"; +}); + +test("no policy: the argv, the echo and the files are today's, byte for byte", async () => { + settings(); + const log: string[] = []; + assert.deepEqual(await list(ON_A, {}, log), ["https://rumble.com/v1-a.html", "https://rumble.com/v2-b.html"]); + assert.deepEqual(spawns(), [{ argv: MAIN_ARGV, stdin: null }]); + assert.deepEqual(log, [`$ ${BIN} ${MAIN_ARGV.join(" ")}\n`]); + assert.ok(!existsSync(path.join(ROOT, ".network"))); + assert.ok(!existsSync(NE.channelExitPath(getPaths(), ON_A))); + // A policy for ANOTHER platform changes nothing here either. + settings({ exits: EXITS, platforms: { twitch: { exits: ["exit-a"] } } }); + rmSync(RECORD, { force: true }); + await list(ON_A); + assert.deepEqual(spawns(), [{ argv: MAIN_ARGV, stdin: null }]); +}); + +test("through an exit: the proxy reaches yt-dlp on stdin only; the rest of the argv is unchanged", async () => { + settings(RUMBLE_POLICY); + const log: string[] = []; + await list(ON_A, {}, log); + const [s] = spawns(); + assert.deepEqual(s!.argv, ["--config-locations", "-", ...MAIN_ARGV]); + assert.equal(s!.stdin, `--proxy '${PROXY_A}'\n`); + const text = log.join(""); + assert.ok(!text.includes(SECRET), text); + assert.match(text, new RegExp(`Network exit: "exit-a" \\(socks5h://127\\.0\\.0\\.1:${proxyA.port}\\)`)); + assert.equal(proxyA.greetings > 0, true, "the proxy was preflighted"); +}); + +test("sticky: chosen once by the hash, recorded, and kept on every later listing", async () => { + settings(RUMBLE_POLICY); + await list(ON_B); + const rec = await NE.readChannelExitRecord(getPaths(), ON_B); + assert.equal(rec!.exit, "exit-b"); + assert.equal(rec!.by, "hash"); + for (let i = 0; i < 3; i++) await list(ON_B); + assert.equal(spawns().every((s) => s.argv[0] === "--config-locations" && s.stdin!.includes(`:${proxyB.port}`)), true); + // Adding an exit does not move a recorded channel. + settings({ ...RUMBLE_POLICY, exits: [...EXITS, { id: "exit-c", proxy: PROXY_B }], platforms: { rumble: { exits: ["exit-c", "exit-a", "exit-b"] } } }); + await list(ON_B); + assert.equal((await NE.readChannelExitRecord(getPaths(), ON_B))!.exit, "exit-b"); +}); + +test("a removed or disabled exit re-chooses the channel; nothing else moves it", async () => { + settings(RUMBLE_POLICY); + await list(ON_A); + settings({ ...RUMBLE_POLICY, exits: [{ ...EXITS[0], enabled: false }, EXITS[1]] }); + await list(ON_A); + const rec = await NE.readChannelExitRecord(getPaths(), ON_A); + assert.equal(rec!.exit, "exit-b"); + assert.equal(rec!.previous, "exit-a"); + assert.match(rec!.reason!, /no longer an enabled exit/); +}); + +test("reassign only by the action: network-exit {slug, exit}", async () => { + settings(RUMBLE_POLICY); + await list(ON_A); + const r = await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-b" }); + assert.deepEqual(r, { slug: ON_A, platform: "rumble", exit: "exit-b", previous: "exit-a" }); + await list(ON_A); + assert.ok(spawns().at(-1)!.stdin!.includes(`:${proxyB.port}`)); + await NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "direct" }); + await list(ON_A); + assert.deepEqual(spawns().at(-1), { argv: MAIN_ARGV, stdin: null }); + await assert.rejects(NE.assignChannelExit({ paths: getPaths(), slug: ON_A, exit: "exit-z" }), /no exit "exit-z"/); + await assert.rejects(NE.assignChannelExit({ paths: getPaths(), slug: "nope", exit: "exit-a" }), /not found/); +}); + +test("a cookie-bearing listing never gets a non-direct exit", async () => { + settings(RUMBLE_POLICY); + for (const config of [ + { cookiesFromBrowser: "firefox", cookieMode: "always" }, + { ytdlpExtraArgs: ["--cookies", "/tmp/jar.txt"] }, + { ytdlpExtraArgs: ["--add-headers", "Cookie: cf_clearance=x"] }, + ]) { + rmSync(RECORD, { force: true }); + const log: string[] = []; + await list(ON_A, config, log); + const [s] = spawns(); + assert.ok(!s!.argv.includes("--config-locations"), JSON.stringify(config)); + assert.equal(s!.stdin, null); + assert.match(log.join(""), /Network exit: direct \(this listing carries a login/); + } + // Even a hand-edited jar assignment is not honoured in the trial. + settings({ ...RUMBLE_POLICY, jars: { "browser:firefox": "exit-a" } }); + rmSync(RECORD, { force: true }); + await list(ON_A, { cookiesFromBrowser: "firefox", cookieMode: "always" }); + assert.ok(!spawns()[0]!.argv.includes("--config-locations")); +}); + +test("a 429 through an exit rests that exit only; its channels wait, the other exit's do not", async () => { + settings(RUMBLE_POLICY); + process.env.FAKE_MODE = "429"; + await assert.rejects(list(ON_A), (err: unknown) => { + assert.ok(err instanceof EnumerationIncompleteError); + assert.equal(err.exit, "exit-a"); + assert.equal(err.platformBackoffDue, false); + assert.equal(err.pagesReached, 2); + return true; + }); + assert.equal(await platformCooldownRemainingMs("rumble", getPaths()), 0, "the platform is not cooled for one exit"); + assert.ok((await NE.exitRestUntil(getPaths(), "rumble", "exit-a"))! > Date.now()); + // The channel on the resting exit WAITS: deferred, nothing spawned, no hop. + process.env.FAKE_MODE = "ok"; + const before = spawns().length; + await assert.rejects(list(ON_A), (err: unknown) => { + assert.ok(err instanceof JobDeferredError); + assert.ok(err.until > Date.now()); + assert.match(err.message, /rumble exit "exit-a" rests until \d\d:\d\d .* never moves to another exit/); + return true; + }); + assert.equal(spawns().length, before); + assert.equal((await NE.readChannelExitRecord(getPaths(), ON_A))!.exit, "exit-a"); + // The manual Sync gate says the same sentence. + assert.match((await NE.listingRestRefusal(getPaths(), ON_A, "https://rumble.com/c/demo"))!.sentence, /rests until/); + // A channel on the other exit lists. + assert.equal((await list(ON_B)).length, 2); + // When the second exit rests too, the platform's own cooldown is due. + process.env.FAKE_MODE = "429"; + await assert.rejects(list(ON_B), (err: unknown) => { + assert.ok(err instanceof EnumerationIncompleteError); + assert.equal(err.platformBackoffDue, true); + return true; + }); + const usage = await NE.usageOver(getPaths(), 1); + assert.equal(usage["rumble/exit-a"]!.rateLimits, 1); + assert.equal(usage["rumble/exit-a"]!.rests, 1); + assert.equal(usage["rumble/exit-b"]!.requests, 2); +}); + +test("a clean listing through the exit ends its rest", async () => { + settings(RUMBLE_POLICY); + await NE.restExit(getPaths(), "rumble", "exit-b", ["exit-a", "exit-b"], Date.now() - 31 * 60_000); + assert.equal(await NE.exitRestUntil(getPaths(), "rumble", "exit-b"), null); + await list(ON_B); + const rests = readFileSync(path.join(ROOT, ".network", "rests.json"), "utf8"); + assert.ok(!rests.includes("rumble/exit-b"), rests); +}); + +test("a dead proxy fails closed: named error, yt-dlp not spawned, no direct connection", async () => { + const dead = `socks5h://user-a:${SECRET}@127.0.0.1:${await closedPort()}`; + settings({ exits: [{ id: "exit-a", proxy: dead }], platforms: { rumble: { exits: ["exit-a"] } } }); + process.env.FAKE_DIRECT_PORT = String(target.port); + await assert.rejects(list(ON_A), (err: unknown) => { + assert.ok(err instanceof NetworkExitError); + assert.equal(err.exit, "exit-a"); + assert.match(err.message, /^network exit "exit-a" \(socks5h:\/\/127\.0\.0\.1:\d+\) did not answer: connection refused\. The rumble listing was not sent — a listing never falls back to direct\.$/); + assert.ok(!err.message.includes(SECRET)); + return true; + }); + assert.deepEqual(spawns(), []); + assert.equal(target.connections(), 0); + assert.equal((await NE.usageOver(getPaths(), 1))["rumble/exit-a"]!.proxyFailures, 1); +}); + +test("a credentialed proxy URL appears in no log, error, record or report", async () => { + settings({ ...RUMBLE_POLICY, echoUrl: "" }); + process.env.FAKE_MODE = "verbose"; + const log: string[] = []; + await list(ON_A, {}, log); + assert.ok(log.join("").includes("Stdin config"), "the stand-in echoed its stdin like -v"); + process.env.FAKE_MODE = "429"; + let message = ""; + await list(ON_A, {}, log).catch((e: Error) => (message = e.message)); + assert.ok(message.length > 0); + const report = JSON.stringify(await NE.networkReport(getPaths())); + const files: string[] = []; + const walk = (d: string) => { + for (const n of readdirSync(d)) { + const p = path.join(d, n); + if (statSync(p).isDirectory()) walk(p); + else if (p !== process.env.SETTINGS_FILE && p !== RECORD) files.push(readFileSync(p, "utf8")); + } + }; + walk(ROOT); + for (const [what, text] of [["log", log.join("")], ["error", message], ["report", report], ["files", files.join("\n")]] as const) { + assert.ok(!text.includes(SECRET), `${what} carries the secret`); + assert.ok(!text.includes("user-a:"), `${what} carries the userinfo`); + } + assert.match(report, /socks5h:\/\/<redacted>@127\.0\.0\.1/); +}); + +test("pacing is per platform: two exits make the same starts per hour as one", async () => { + // The queue a listing waits on and the pace in its argv know no exit. + settings(RUMBLE_POLICY); + await list(ON_A); + await list(ON_B); + const [a, b] = spawns(); + assert.deepEqual(a!.argv.slice(2), MAIN_ARGV); + assert.deepEqual(b!.argv.slice(2), MAIN_ARGV); + const config = { handling: "transcribe", url: "https://rumble.com/c/demo" } as never; + assert.equal(downloadQueueKey(config), "platform:rumble"); + // An hour of back-to-back listing jobs on rumble's queue, 5 s each, spread + // over one exit or over two: the queue gap admits the same number. + const startsPerHour = async (slugs: string[]) => { + clearQueueGaps(); + let now = 1_000_000; + const clock = { now: () => now, sleep: async (ms: number) => void (now += ms) }; + const pacing = () => ({ jobGapSeconds: { rumble: 120 }, jitter: 0 }); + const jobsDir = mkdtempSync(path.join(ROOT, "jobs-")); + let starts = 0; + for (let i = 0; now < 1_000_000 + 3_600_000; i++) { + const slug = slugs[i % slugs.length]!; + void slug; // the exit a slug is on never enters the queue key + await waitForQueueGap({ paths: { jobsDir }, queueKey: downloadQueueKey(config), pacing, clock }); + if (now >= 1_000_000 + 3_600_000) break; + starts++; + now += 5_000; + await noteQueueJobEnd({ jobsDir }, downloadQueueKey(config), now); + } + return starts; + }; + const one = await startsPerHour([ON_A]); + const two = await startsPerHour([ON_A, ON_B]); + assert.equal(two, one); + assert.equal(one, 29); +}); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,19 @@ # Changelog ## [Unreleased] +- **Network exits (trial): rumble and twitch listings through named proxies.** + - New `settings.network`: exits `{id, label, proxy, enabled}` (`socks5h://`, `socks5://`, `http://`, `https://`), a + policy per platform, and cookie-jar pins. Absent = every request direct, exactly as before. + - The trial routes only the listing requests of rumble and twitch. Any other platform or request kind, and any cookie jar + given an exit, is refused when saved. + - A channel's exit is a stable hash of its slug, recorded in `channels/<slug>/network-exit.json`. It changes only when + that exit is removed or disabled, or by `pnpm ops network-exit`. A listing that carries a login stays direct. + - Pacing is unchanged: gaps, pace, cooldowns and holds count every exit together. A 429 or bot check through an exit + rests that exit, and its channels wait (the sync ends deferred). The platform cools down only when every exit rests. + - A proxy that does not answer fails the listing and names the exit. It never falls back to direct. Proxy credentials + are never shown, logged or recorded; yt-dlp gets the URL on its stdin. + - `pnpm ops network`, `pnpm ops network-exit`, `pnpm ops get network [--probe]`, and /settings → Network exits. Not a + disguise: no fingerprint or user-agent changes. - **umtool: name a channel once for a whole cut.** - A cut made from two recordings of one channel showed two names for it, the older record's uploader name and the current one. Before, the only fix was to hand-edit `channelTitle` on every clip. diff --git a/editor/app/api/ops/_read.ts b/editor/app/api/ops/_read.ts @@ -1,6 +1,7 @@ import { NextResponse } from "next/server"; import { opsAuth, opsFail } from "./_lib"; import { withAttention } from "./_attention"; +import { redactUrlUserinfo } from "yt-dlp-transcript-common/lib/networkExits"; // THE READ SIDE'S DOOR (release 19, A3): `GET /api/ops/<noun>` routes that // answer what an existing builder already builds for a page — settings, the @@ -42,8 +43,13 @@ export async function readRoute( // "<redacted>" ("" stays "", so "unset" still reads as unset). const SECRET_KEY = /token|secret|password|passwd|api[-_]?key|credential/i; +// +// AND A URL'S CREDENTIALS, under any key (a network exit's `proxy`, +// lib/networkExits.ts): `scheme://user:pass@host` answers as +// `scheme://<redacted>@host`, so the host still reads. export function redactSecrets<T>(value: T): T { if (Array.isArray(value)) return value.map(redactSecrets) as T; + if (typeof value === "string") return redactUrlUserinfo(value) as T; if (typeof value !== "object" || value === null) return value; const out: Record<string, unknown> = {}; for (const [k, v] of Object.entries(value as Record<string, unknown>)) { diff --git a/editor/app/api/ops/network-exit/route.ts b/editor/app/api/ops/network-exit/route.ts @@ -0,0 +1,25 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { NetworkInputError, assignChannelExit } from "yt-dlp-transcript-common/controller/networkExits"; +import { OpsInputError, ops, reqSlug, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, exit } +// +// THE OPERATOR'S REASSIGNMENT of a channel's network exit (lane +// network-exits): the only way a channel's sticky exit changes besides its +// exit being removed or disabled. `exit` is one of the platform's enabled +// exits or "direct". Answers { ok, slug, platform, exit, previous }. Refused +// for a channel whose platform has no network policy. +export async function POST(request: Request) { + return ops(request, ["slug", "exit"], async (body) => { + try { + const r = await assignChannelExit({ paths: getPaths(), slug: reqSlug(body, "slug"), exit: reqString(body, "exit") }); + return NextResponse.json({ ok: true, ...r }); + } catch (e) { + if (e instanceof NetworkInputError) throw new OpsInputError(e.message); + throw e; + } + }); +} diff --git a/editor/app/api/ops/network/route.ts b/editor/app/api/ops/network/route.ts @@ -0,0 +1,47 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { NETWORK_REQUEST_KEYS } from "yt-dlp-transcript-common/lib/networkExits"; +import { networkReport, probeNetworkExits } from "yt-dlp-transcript-common/controller/networkExits"; +import { NetworkSaveError, saveNetworkRequest } from "../../../settings/networkSave"; +import { OpsInputError, ops } from "../_lib"; +import { readRoute, redactSecrets } from "../_read"; +import { directEcho } from "../../../settings/networkProbe"; + +export const dynamic = "force-dynamic"; + +// NAMED NETWORK EXITS (lane network-exits; common/lib/networkExits.ts). +// +// GET /api/ops/network[?probe=1] +// -> { ok, network: { limits, trialScope, exits: [{id, label, proxy (masked), +// enabled, probe}], platforms: {<p>: {exits, mode, kinds, pool, allRest} +// | {…, ignored}}, jars, echoUrl, rests: [{platform, exit, until, fails}], +// usage: {"1d": {"<platform>/<exit>": {requests, rateLimits, botChecks, +// rests, proxyFailures}}, "7d": …}, lastProbeAt } } +// Reads files only. `probe=1` first asks each enabled exit's proxy to answer +// (connect + SOCKS greeting/login; no destination) and, only when +// network.echoUrl is set, fetches it through each exit and once direct to +// name the address each presents. +// +// POST { exits? | upsertExit? | removeExit? | platforms? | jars? | echoUrl? } +// -> { ok, network: <the saved block, proxies masked> } +// One write through the network writer (settings/networkSave.ts): refused +// whole, every problem named, when it routes anything outside the trial +// (rumble and twitch listings) or gives a cookie jar an exit. +export async function GET(request: Request) { + return readRoute(request, ["probe"], async (q) => { + const paths = getPaths(); + if (q.get("probe") === "1") await probeNetworkExits(paths, undefined, new Date(), { getDirect: directEcho }); + return { network: redactSecrets(await networkReport(paths)) }; + }); +} + +export async function POST(request: Request) { + return ops(request, NETWORK_REQUEST_KEYS, async (body) => { + try { + return NextResponse.json({ ok: true, network: redactSecrets(await saveNetworkRequest(body)) }); + } catch (e) { + if (e instanceof NetworkSaveError) throw new OpsInputError(e.message); + throw e; + } + }); +} diff --git a/editor/app/api/ops/settings/patch.ts b/editor/app/api/ops/settings/patch.ts @@ -13,6 +13,8 @@ import { localOnlySettingsRefusal } from "yt-dlp-transcript-common/lib/llm/local // - remoteArchives: an archive's corpus.json is read when it is connected. // - storage: a location is probed and its volume recorded when added or // re-pointed (/storage); a raw root would skip both. +// - network: a proxy sent back masked must keep its stored credentials, +// which only the network writer knows to do (common/lib/networkExits.ts). export const OWNED_KEYS: Readonly<Record<string, string>> = { channelPriority: "it is written with the lanes' trees — use `pnpm ops channel-priority`", autoQueue: @@ -20,6 +22,8 @@ export const OWNED_KEYS: Readonly<Record<string, string>> = { workers: "workers are saved on /workers; `pnpm ops workers` enables and disables them", remoteArchives: "an archive is probed (its corpus.json read) when it is connected — use `pnpm ops archives` or /sites → Connect an archive", storage: "locations are added and re-pointed on /storage, which probes them; a channel's media moves with `pnpm ops relocate`", + network: + "network exits are written by `pnpm ops network` (or /settings → Network exits), which keeps a masked proxy's stored credentials and refuses what the trial does not route", }; function isObject(v: unknown): v is Record<string, unknown> { diff --git a/editor/app/settings/components/NetworkExitsSection.tsx b/editor/app/settings/components/NetworkExitsSection.tsx @@ -0,0 +1,261 @@ +"use client"; + +// NETWORK EXITS on /settings (lane network-exits). Every control is the twin +// of a `pnpm ops` call and gets the same refusals: +// Save exit / Enable / Disable network {"upsertExit": {...}} +// Remove network {"removeExit": "<id>"} +// a platform's Save / Clear network {"platforms": {"<p>": {...} | null}} +// Echo URL Save network {"echoUrl": "..."} +// Probe exits get network --probe +// Assign network-exit {"slug", "exit"} +// Proxies arrive masked; a masked proxy saved back keeps its credentials. + +import { useState, useTransition } from "react"; +import { + assignChannelExitAction, + probeNetworkAction, + saveNetworkAction, + type NetworkReport, +} from "../networkActions"; + +const BUTTON = "rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50"; +const INPUT = "rounded-md border border-border bg-background px-2 py-1 text-sm"; +const TRIAL_PLATFORMS = ["rumble", "twitch"] as const; + +function probeText(p: NetworkReport["exits"][number]["probe"]): string { + if (!p) return "not probed"; + if (!p.reachable) return `unreachable: ${p.reason ?? "?"}`; + const addr = p.address ? `, shows ${p.address}` : p.echoError ? `, echo failed: ${p.echoError}` : ""; + return `answers${p.ms !== undefined ? ` (${p.ms} ms)` : ""}${addr}`; +} + +export function NetworkExitsSection({ initial }: { initial: NetworkReport }) { + const [report, setReport] = useState(initial); + const [error, setError] = useState<string | null>(null); + const [pending, start] = useTransition(); + const [draft, setDraft] = useState({ id: "", label: "", proxy: "" }); + const [echoUrl, setEchoUrl] = useState(initial.echoUrl); + const [assign, setAssign] = useState({ slug: "", exit: "direct" }); + const exits = report.exits.filter((e) => e.id !== "direct"); + + const run = (fn: () => Promise<{ ok: true; report: NetworkReport } | { ok: false; error: string }>) => + start(async () => { + setError(null); + const r = await fn(); + if (r.ok) setReport(r.report); + else setError(r.error); + }); + const save = (body: Record<string, unknown>) => run(() => saveNetworkAction(body)); + + const policyExits = (p: string): string[] => report.platforms[p]?.exits ?? []; + const togglePolicy = (p: string, id: string, on: boolean) => { + const cur = policyExits(p); + const next = on ? [...cur, id] : cur.filter((x) => x !== id); + save({ platforms: { [p]: next.length ? { exits: next, mode: "sticky", kinds: ["listing"] } : null } }); + }; + + const counts = Object.entries(report.usage["7d"]).sort(([a], [b]) => a.localeCompare(b)); + + return ( + <div className="flex flex-col gap-4" aria-label="network exits"> + <div> + <h2 className="text-lg font-semibold">Network exits</h2> + <p className="text-xs text-muted-foreground"> + Trial: rumble and twitch listings only. Logged-in requests stay direct. Not a disguise: no fingerprint or + user-agent changes. + </p> + </div> + + <table className="text-sm w-full"> + <thead> + <tr className="border-b border-border text-left"> + <th className="py-1 pr-3 font-medium">Exit</th> + <th className="py-1 pr-3 font-medium">Proxy</th> + <th className="py-1 pr-3 font-medium">Probe</th> + <th className="py-1 font-medium" /> + </tr> + </thead> + <tbody> + {report.exits.map((e) => ( + <tr key={e.id} className="border-b border-border align-top"> + <td className="py-1 pr-3"> + <span className="font-mono">{e.id}</span> + {e.label !== e.id && <span className="text-muted-foreground"> {e.label}</span>} + {!e.enabled && <span className="text-muted-foreground"> (disabled)</span>} + </td> + <td className="py-1 pr-3 font-mono text-xs break-all">{e.proxy ?? "none"}</td> + <td className="py-1 pr-3 text-xs">{probeText(e.probe)}</td> + <td className="py-1 whitespace-nowrap"> + {e.id !== "direct" && ( + <span className="flex gap-1"> + <button + type="button" + className={BUTTON} + disabled={pending} + onClick={() => save({ upsertExit: { id: e.id, enabled: !e.enabled } })} + > + {e.enabled ? "Disable" : "Enable"} + </button> + <button + type="button" + className={BUTTON} + disabled={pending} + onClick={() => setDraft({ id: e.id, label: e.label, proxy: e.proxy ?? "" })} + > + Edit + </button> + <button type="button" className={BUTTON} disabled={pending} onClick={() => save({ removeExit: e.id })}> + Remove + </button> + </span> + )} + </td> + </tr> + ))} + </tbody> + </table> + + <form + className="flex flex-wrap items-end gap-2" + onSubmit={(ev) => { + ev.preventDefault(); + save({ upsertExit: { id: draft.id.trim(), label: draft.label.trim() || draft.id.trim(), proxy: draft.proxy.trim() } }); + }} + > + <label className="flex flex-col text-xs"> + Id + <input className={INPUT} value={draft.id} onChange={(e) => setDraft({ ...draft, id: e.target.value })} placeholder="nl-ams-1" /> + </label> + <label className="flex flex-col text-xs"> + Label + <input className={INPUT} value={draft.label} onChange={(e) => setDraft({ ...draft, label: e.target.value })} /> + </label> + <label className="flex flex-col text-xs grow"> + Proxy URL + <input + className={`${INPUT} font-mono`} + value={draft.proxy} + onChange={(e) => setDraft({ ...draft, proxy: e.target.value })} + placeholder="socks5h://host:1080" + autoComplete="off" + spellCheck={false} + /> + </label> + <button type="submit" className={BUTTON} disabled={pending || !draft.id.trim() || !draft.proxy.trim()}> + Save exit + </button> + </form> + + <div className="flex flex-col gap-2"> + {TRIAL_PLATFORMS.map((p) => ( + <div key={p} className="flex flex-wrap items-center gap-3 text-sm" aria-label={`${p} listing policy`}> + <span className="font-medium w-16">{p}</span> + {["direct", ...exits.map((e) => e.id)].map((id) => ( + <label key={id} className="flex items-center gap-1 text-xs"> + <input + type="checkbox" + disabled={pending} + checked={policyExits(p).includes(id)} + onChange={(ev) => togglePolicy(p, id, ev.target.checked)} + /> + <span className="font-mono">{id}</span> + </label> + ))} + {report.platforms[p] ? ( + <span className="text-xs text-muted-foreground"> + listings spread over {report.platforms[p]!.pool?.join(", ") || "no enabled exit (direct)"} + {report.platforms[p]!.allRest ? " — every exit rests" : ""} + </span> + ) : ( + <span className="text-xs text-muted-foreground">no policy: direct</span> + )} + </div> + ))} + </div> + + <form + className="flex flex-wrap items-end gap-2" + onSubmit={(ev) => { + ev.preventDefault(); + run(() => assignChannelExitAction(assign.slug.trim(), assign.exit)); + }} + > + <label className="flex flex-col text-xs"> + Channel + <input className={INPUT} value={assign.slug} onChange={(e) => setAssign({ ...assign, slug: e.target.value })} placeholder="slug" /> + </label> + <label className="flex flex-col text-xs"> + Exit + <select className={INPUT} value={assign.exit} onChange={(e) => setAssign({ ...assign, exit: e.target.value })}> + {["direct", ...exits.map((e) => e.id)].map((id) => ( + <option key={id} value={id}> + {id} + </option> + ))} + </select> + </label> + <button type="submit" className={BUTTON} disabled={pending || !assign.slug.trim()}> + Assign + </button> + </form> + + <div className="flex flex-wrap items-end gap-2"> + <label className="flex flex-col text-xs grow"> + Echo URL (probe only; blank = no request) + <input className={`${INPUT} font-mono`} value={echoUrl} onChange={(e) => setEchoUrl(e.target.value)} placeholder="https://…" /> + </label> + <button type="button" className={BUTTON} disabled={pending} onClick={() => save({ echoUrl: echoUrl.trim() })}> + Save echo URL + </button> + <button type="button" className={BUTTON} disabled={pending} onClick={() => run(() => probeNetworkAction())}> + Probe exits + </button> + </div> + + {report.rests.length > 0 && ( + <ul className="text-xs" aria-label="resting exits"> + {report.rests.map((r) => ( + <li key={`${r.platform}/${r.exit}`}> + {r.platform} exit <span className="font-mono">{r.exit}</span> rests until {r.until.slice(11, 16)} UTC ({r.fails} in a row) + </li> + ))} + </ul> + )} + + {counts.length > 0 && ( + <table className="text-xs w-full" aria-label="network exit counts"> + <thead> + <tr className="border-b border-border text-left"> + <th className="py-1 pr-3 font-medium">Platform / exit</th> + <th className="py-1 pr-3 font-medium">Requests 1d / 7d</th> + <th className="py-1 pr-3 font-medium">429s</th> + <th className="py-1 pr-3 font-medium">Bot checks</th> + <th className="py-1 pr-3 font-medium">Rests</th> + <th className="py-1 font-medium">Proxy failures</th> + </tr> + </thead> + <tbody> + {counts.map(([k, c]) => ( + <tr key={k} className="border-b border-border"> + <td className="py-1 pr-3 font-mono">{k}</td> + <td className="py-1 pr-3"> + {report.usage["1d"][k]?.requests ?? 0} / {c.requests} + </td> + <td className="py-1 pr-3">{c.rateLimits}</td> + <td className="py-1 pr-3">{c.botChecks}</td> + <td className="py-1 pr-3">{c.rests}</td> + <td className="py-1">{c.proxyFailures}</td> + </tr> + ))} + </tbody> + </table> + )} + + {error && ( + <p role="alert" aria-label="network exits error" className="text-xs text-destructive"> + {error} + </p> + )} + </div> + ); +} diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx @@ -42,7 +42,9 @@ import { type Props = { // The settings WITHOUT `autoQueue` (the lanes' policy trees): this form // reads none of it, and the page does not send it (settings/page.tsx). - initial: Omit<SiteSettings, "autoQueue">; + // `network` stays server-side: its proxies may carry credentials + // (NetworkExitsSection gets a masked view). + initial: Omit<SiteSettings, "autoQueue" | "network">; }; export function SettingsForm({ initial }: Props) { diff --git a/editor/app/settings/networkActions.ts b/editor/app/settings/networkActions.ts @@ -0,0 +1,62 @@ +"use server"; + +// /settings → Network exits (lane network-exits). Each action is the twin of a +// `pnpm ops` call: save → `pnpm ops network`, assign → `pnpm ops network-exit`, +// probe → `pnpm ops get network --probe`. Every answer is masked. + +import { revalidatePath } from "next/cache"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { + NetworkInputError, + assignChannelExit, + networkReport, + probeNetworkExits, + type NetworkReportView, +} from "yt-dlp-transcript-common/controller/networkExits"; +import { redactUrlUserinfo } from "yt-dlp-transcript-common/lib/networkExits"; +import { NetworkSaveError, saveNetworkRequest } from "./networkSave"; +import { directEcho } from "./networkProbe"; + +export type NetworkReport = NetworkReportView; +type Answer = { ok: true; report: NetworkReport } | { ok: false; error: string }; + +async function report(): Promise<NetworkReport> { + return JSON.parse(redactUrlUserinfo(JSON.stringify(await networkReport(getPaths())))) as NetworkReport; +} + +function refusal(e: unknown): { ok: false; error: string } { + if (e instanceof NetworkSaveError || e instanceof NetworkInputError) return { ok: false, error: e.message }; + return { ok: false, error: redactUrlUserinfo((e as Error).message ?? String(e)) }; +} + +export async function networkReportAction(): Promise<NetworkReport> { + return report(); +} + +export async function saveNetworkAction(body: Record<string, unknown>): Promise<Answer> { + try { + await saveNetworkRequest(body); + revalidatePath("/settings"); + return { ok: true, report: await report() }; + } catch (e) { + return refusal(e); + } +} + +export async function assignChannelExitAction(slug: string, exit: string): Promise<Answer> { + try { + await assignChannelExit({ paths: getPaths(), slug, exit }); + return { ok: true, report: await report() }; + } catch (e) { + return refusal(e); + } +} + +export async function probeNetworkAction(): Promise<Answer> { + try { + await probeNetworkExits(getPaths(), undefined, new Date(), { getDirect: directEcho }); + return { ok: true, report: await report() }; + } catch (e) { + return refusal(e); + } +} diff --git a/editor/app/settings/networkProbe.ts b/editor/app/settings/networkProbe.ts @@ -0,0 +1,12 @@ +// The probe's one DIRECT request (lane network-exits): the operator's +// address-echo URL fetched without a proxy, so `get network --probe` shows the +// home address beside each exit's. Made only when network.echoUrl is set. +export async function directEcho(url: string): Promise<{ ok: true; body: string } | { ok: false; reason: string }> { + try { + const res = await fetch(url, { signal: AbortSignal.timeout(8_000), headers: { accept: "text/plain, */*" } }); + const body = (await res.text()).slice(0, 4096); + return res.ok ? { ok: true, body } : { ok: false, reason: `HTTP ${res.status}` }; + } catch (e) { + return { ok: false, reason: (e as Error).message }; + } +} diff --git a/editor/app/settings/networkSave.test.ts b/editor/app/settings/networkSave.test.ts @@ -0,0 +1,87 @@ +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { test, after } from "node:test"; +import assert from "node:assert/strict"; + +// Run with: pnpm -C editor exec tsx --test app/settings/networkSave.test.ts +// +// THE NETWORK EXITS' ONE WRITER (lane network-exits): what `pnpm ops network` +// and /settings → Network exits save, what they refuse, and that a proxy's +// credentials never come back out. getPaths() memoizes, so SETTINGS_FILE is +// set before the module under test is imported. + +const ROOT = mkdtempSync(path.join(os.tmpdir(), "network-save-")); +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +writeFileSync(process.env.SETTINGS_FILE, "{}\n"); + +const { saveNetworkRequest, NetworkSaveError } = await import("./networkSave"); +const { saveSettings } = await import("./saveSettings"); +const { getSettings } = await import("yt-dlp-transcript-common/lib/settings"); +const { redactSecrets } = await import("../api/ops/_read"); +const { settingsPatchProblem, OWNED_KEYS } = await import("../api/ops/settings/patch"); + +after(() => rm(ROOT, { recursive: true, force: true })); + +const SECRET = "pw-not-for-logs"; +const PROXY = `socks5h://user-one:${SECRET}@exit-a.example.test:1080`; + +test("an exit and a rumble listing policy save; the answer is masked", async () => { + const a = await saveNetworkRequest({ upsertExit: { id: "exit-a", proxy: PROXY } }); + assert.equal(a.exits[0]!.proxy, "socks5h://<redacted>@exit-a.example.test:1080"); + await saveNetworkRequest({ upsertExit: { id: "exit-b", proxy: "socks5h://exit-b.example.test:1080" } }); + const b = await saveNetworkRequest({ platforms: { rumble: { exits: ["direct", "exit-a", "exit-b"], mode: "sticky" } } }); + assert.deepEqual(b.platforms.rumble, { exits: ["direct", "exit-a", "exit-b"], mode: "sticky", kinds: ["listing"] }); + // Stored whole (the file has the credentials; nothing else does). + assert.equal(getSettings().network.exits[0]!.proxy, PROXY); + assert.ok(!JSON.stringify(b).includes(SECRET)); +}); + +test("a masked proxy sent back keeps the stored credentials", async () => { + const shown = (await saveNetworkRequest({ upsertExit: { id: "exit-a", label: "Amsterdam" } })).exits[0]!; + await saveNetworkRequest({ exits: [{ ...shown }, ...getSettings().network.exits.slice(1)] }); + assert.equal(getSettings().network.exits[0]!.proxy, PROXY); + assert.equal(getSettings().network.exits[0]!.label, "Amsterdam"); +}); + +test("out-of-scope platforms and kinds, and jar assignments, are refused whole with the trial's sentence", async () => { + const before = readFileSync(process.env.SETTINGS_FILE!, "utf8"); + for (const [body, re] of [ + [{ platforms: { youtube: { exits: ["exit-a"] } } }, /network\.platforms\.youtube: refused — the network-exit trial routes only the listing requests of rumble and twitch/], + [{ platforms: { twitch: { exits: ["exit-a"], kinds: ["download"] } } }, /kinds: "download" refused/], + [{ jars: { "browser:firefox": "exit-a" } }, /network\.jars\.browser:firefox: refused — a request that carries a login/], + [{ platforms: { rumble: { exits: ["exit-z"] } } }, /"exit-z" is not a defined exit/], + [{ upsertExit: { id: "exit-c", proxy: `ftp://u:${SECRET}@h:1` } }, /scheme must be/], + ] as const) { + await assert.rejects(saveNetworkRequest(body as Record<string, unknown>), (e: unknown) => { + assert.ok(e instanceof NetworkSaveError); + assert.match(e.message, re); + assert.ok(!e.message.includes(SECRET)); + return true; + }); + } + assert.equal(readFileSync(process.env.SETTINGS_FILE!, "utf8"), before, "nothing written"); +}); + +test("the settings writer's floor refuses a raw out-of-scope network block too", async () => { + await assert.rejects( + saveSettings({ network: { exits: [], platforms: { youtube: { exits: ["direct", "x"], mode: "sticky", kinds: ["listing"] } }, jars: {}, echoUrl: "" } }), + /network: not saved — network\.platforms\.youtube: refused/, + ); +}); + +test("`pnpm ops settings` refuses the network key as owned; every ops answer masks a URL's credentials", () => { + assert.ok(OWNED_KEYS.network); + assert.match(settingsPatchProblem({ network: {} }, ["network"], {})!, /"network" is not patched here: network exits are written by `pnpm ops network`/); + const red = redactSecrets({ network: getSettings().network, note: `via ${PROXY}` }); + assert.ok(!JSON.stringify(red).includes(SECRET)); + assert.equal(red.note, "via socks5h://<redacted>@exit-a.example.test:1080"); +}); + +test("removing an exit takes it out of every policy", async () => { + const r = await saveNetworkRequest({ removeExit: "exit-a" }); + assert.deepEqual(r.platforms.rumble!.exits, ["direct", "exit-b"]); + assert.equal(r.exits.length, 1); +}); diff --git a/editor/app/settings/networkSave.ts b/editor/app/settings/networkSave.ts @@ -0,0 +1,35 @@ +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { + NetworkRequestError, + applyNetworkRequest, + maskedNetwork, + networkSettingsProblems, + sanitizeNetwork, + type NetworkSettings, +} from "yt-dlp-transcript-common/lib/networkExits"; +import { saveSettingsHeld, withSettingsLock } from "./saveSettings"; + +// THE NETWORK EXITS' ONE WRITER (lane network-exits): `pnpm ops network` and +// /settings → Network exits both send a request here. Applied to the stored +// block (a masked proxy keeps its stored credentials), refused whole with +// every problem named when the result is outside the trial +// (networkSettingsProblems), then saved. Answers the saved block MASKED. +// +// Not a "use server" module: the ops route and networkActions.ts call it. +export class NetworkSaveError extends Error {} + +export async function saveNetworkRequest(body: Record<string, unknown>): Promise<NetworkSettings> { + return withSettingsLock(async () => { + let next: Record<string, unknown>; + try { + next = applyNetworkRequest(getSettings().network, body); + } catch (e) { + if (e instanceof NetworkRequestError) throw new NetworkSaveError(e.message); + throw e; + } + const problems = networkSettingsProblems(next); + if (problems.length) throw new NetworkSaveError(`not saved — ${problems.join("; ")}`); + await saveSettingsHeld({ network: sanitizeNetwork(next) }); + return maskedNetwork(getSettings().network); + }); +} diff --git a/editor/app/settings/page.tsx b/editor/app/settings/page.tsx @@ -17,6 +17,8 @@ import { XSessionSection } from "./components/XSessionSection"; import { xMaxCookieAgeMinutes } from "yt-dlp-transcript-common/social/xCookieSource"; import { ArchiveSourcesSection } from "./components/ArchiveSessionSection"; import { readArchiveSessionStatus } from "yt-dlp-transcript-common/lib/archives/archiveTodaySession"; +import { NetworkExitsSection } from "./components/NetworkExitsSection"; +import { networkReportAction } from "./networkActions"; export const dynamic = "force-dynamic"; @@ -48,8 +50,12 @@ export default async function SettingsPage() { // payload). Leaving it out cannot lose it: the save builds its patch from // the submitted fields alone and merges it over the stored file // (settings/actions.ts; pinned in saveSettingsAction.test.ts). - const { autoQueue: _autoQueue, ...formSettings } = settings; + const { autoQueue: _autoQueue, network: _network, ...formSettings } = settings; void _autoQueue; + // NETWORK EXITS NEVER REACH THE BROWSER RAW: a proxy URL may carry + // credentials. The section below gets the masked report. + void _network; + const network = await networkReportAction(); return ( <div className="flex flex-col gap-8"> @@ -127,6 +133,10 @@ export default async function SettingsPage() { </section> <section className="flex flex-col gap-3 border-t border-border pt-6"> + <NetworkExitsSection initial={network} /> + </section> + + <section className="flex flex-col gap-3 border-t border-border pt-6"> <details> <summary className="cursor-pointer text-lg font-semibold"> System paths diff --git a/editor/app/settings/saveSettings.ts b/editor/app/settings/saveSettings.ts @@ -6,6 +6,7 @@ import { import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { withJsonFileLock } from "yt-dlp-transcript-common/lib/jsonFile-server"; import { localOnlySettingsRefusal } from "yt-dlp-transcript-common/lib/llm/localOnly"; +import { networkSettingsProblems } from "yt-dlp-transcript-common/lib/networkExits"; // THE EDITOR'S ONE SETTINGS WRITER (one-core phase 3 slice 4a). // @@ -77,6 +78,13 @@ export async function saveSettingsHeld(patch: Patch): Promise<void> { // actions): a route off `local`, or a model server not on this machine. const localOnly = localOnlySettingsRefusal(patch as Record<string, unknown>, merged as unknown as Record<string, unknown>); if (localOnly) throw new Error(localOnly); + // NETWORK EXITS (common/lib/networkExits.ts): a `network` block outside the + // trial's scope — another platform, another request kind, a cookie jar + // given an exit — is refused here too, whichever writer sent it. + if ((patch as Record<string, unknown>).network !== undefined) { + const problems = networkSettingsProblems((patch as Record<string, unknown>).network); + if (problems.length) throw new Error(`network: not saved — ${problems.join("; ")}`); + } await writeSettings(merged); } diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -17,6 +17,7 @@ // pnpm ops get job <id> [--tail [<lines>]] // pnpm ops get jobs [--active | --failed] [--kind <kind>] [--slug <slug>] [--limit <n>] // pnpm ops get remote-listing <slug> +// pnpm ops get network [--probe] // pnpm ops get transcript <videoId> [--slug <slug>] // pnpm ops get coverage <slug> // pnpm ops job <cancel|drain|promote|force-release|retry> <id>... [--wait] @@ -68,6 +69,9 @@ // pnpm ops live-recording-ack --json '{"slug":"demo-yt","id":"<videoId>"}' // pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}' // pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait +// pnpm ops network --json '{"upsertExit":{"id":"exit-a","proxy":"socks5h://nl-ams-wg-socks5-001.relays.mullvad.net:1080"}}' +// pnpm ops network --json '{"platforms":{"rumble":{"exits":["direct","exit-a","exit-b"],"mode":"sticky"}}}' +// pnpm ops network-exit --json '{"slug":"demo-rumble","exit":"exit-b"}' // pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}' // pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}' // pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait @@ -316,6 +320,11 @@ const GETTERS = { key ? `/api/ops/settings?key=${encodeURIComponent(key)}` : "/api/ops/settings", // The /storage page: each location, mounted or not, its free space and tiers. storage: () => "/api/ops/storage", + // Named network exits (lane network-exits): each exit (proxy masked) and its + // last probe, the platform policies, the resting exits and the 1- and 7-day + // counts per platform and exit. --probe first asks each enabled exit's proxy + // to answer (and, only with network.echoUrl set, the address it presents). + network: (_arg, { probe }) => (probe ? "/api/ops/network?probe=1" : "/api/ops/network"), // Saved videos holding two copies (a download over a container already in // the store keeps both): each one's active copy and its flagged alternates. "saved-alternates": (slug) => @@ -438,6 +447,7 @@ const GET_JOBS = { // Nouns whose read takes no argument. `get channel` without a slug is a // mistake; `get tags` without one is the whole vocabulary. const GET_ARG_OPTIONAL = new Set([ + "network", "tags", "channels", "publish", @@ -473,6 +483,7 @@ const GET_FLAGS = { job: ["tail"], jobs: ["active", "failed", "kind", "slug", "limit"], "live-recordings": ["all"], + network: ["probe"], }; // The row buttons of /jobs (`POST /api/ops/job`), as `job <verb> <id…>`. @@ -697,6 +708,12 @@ const ACTIONS = [ // ({slug, sweep}). "settings", "clear-platform-hold", + // NAMED NETWORK EXITS (lane network-exits): the exits, the platform + // policies, the jars and the echo URL through their one writer + // ({exits | upsertExit | removeExit | platforms | jars | echoUrl}); one + // channel's sticky exit reassigned ({slug, exit}). + "network", + "network-exit", // COOKIE REFRESH ALERTS: a service's alert rechecked with one request // through its own path ({service}), dismissed ({service}), or the jobs it // stopped re-run once it is OK again ({service}). @@ -935,6 +952,7 @@ export function parseArgs(argv) { let leads = false; let accounts = false; let all = false; + let probe = false; // record-live only: return once media bytes are being written. let waitStarted = false; let tail = 0; @@ -986,6 +1004,9 @@ export function parseArgs(argv) { } else if (arg === "--all") { all = true; used.add("all"); + } else if (arg === "--probe") { + probe = true; + used.add("probe"); } else if (arg === "--wait-started") { waitStarted = true; } else if (arg === "--active" || arg === "--failed") { @@ -1107,7 +1128,7 @@ export function parseArgs(argv) { } return { method: "GET", - path: GETTERS[noun](positional[2], { counts, leads, accounts, all, tail, jobs }), + path: GETTERS[noun](positional[2], { counts, leads, accounts, all, tail, jobs, probe }), wait: false, quiet, waitTimeout, @@ -1395,6 +1416,7 @@ export function usage() { " pnpm ops job wait <id>... [--wait-timeout <seconds>]", " pnpm ops get settings [<key>]", " pnpm ops get storage | sites | workers | auto-queue | scheduler", + " pnpm ops get network [--probe]", " pnpm ops get saved-alternates [<slug>]", " pnpm ops get compaction-review [<slug>]", " pnpm ops get kept-originals [<slug>]", @@ -1666,7 +1688,7 @@ export function usage() { ' {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block\'s keys', ' merge one level; an array, a scalar or an object nested in a block', ' replaces. Refused before anything is written: an unknown key; a key', - ' another writer owns (channelPriority, autoQueue, workers, storage — the', + ' another writer owns (channelPriority, autoQueue, workers, storage, network — the', ' refusal names it); a value the schema would not keep as sent (clamped,', ' dropped), named with what would be saved. Answers the saved values.', "", @@ -1724,6 +1746,29 @@ export function usage() { 'clear-platform-hold clears a platform\'s rate-limit hold, backoff and raised', ' pace, as the lane strip\'s Clear hold: {"platform"}. Answers the sentence.', "", + 'network writes the named network exits (settings.network) through their one', + ' writer, as /settings → Network exits: {"upsertExit": {"id", "label"?,', + ' "proxy"?, "enabled"?}}, {"removeExit": "<id>"} (also out of every policy),', + ' {"exits": [...]} (the whole list), {"platforms": {"<platform>": {"exits":', + ' [ids, "direct" allowed], "mode": "sticky"} | null}}, {"jars": {...}},', + ' {"echoUrl": "<url>" | ""}. Proxy URLs: socks5h://, socks5://, http://,', + ' https:// with a port; credentials are secrets, answered as <redacted>@,', + ' and a masked proxy sent back keeps the stored one. THE TRIAL routes only', + ' rumble and twitch LISTINGS: any other platform or request kind, and any', + ' cookie jar given an exit, is refused whole, every problem named. A', + ' channel\'s exit is a stable hash of its slug over the enabled exits,', + ' recorded once; a listing that carries a login goes direct; a 429 or bot', + ' check rests that exit (its channels wait); a proxy that does not answer', + ' fails the listing naming the exit, never falling back to direct. Not a', + ' disguise: no fingerprint or user-agent changes, and a login never moves.', + ' get network [--probe] reports each exit, the rests and the 1- and 7-day', + ' counts; --probe asks each proxy to answer (and fetches network.echoUrl', + ' through it only when set).', + "", + 'network-exit reassigns one channel\'s exit: {"slug", "exit"} (an enabled', + ' exit of its platform\'s policy, or "direct"). The only way a channel moves', + ' besides its exit being removed or disabled.', + "", 'recheck-service asks a service whose cookie refresh alert is up ONE request', ' through its own path, as the dashboard banner\'s Recheck: {"service"}', ' ("rumble", "youtube", "odysee", "archive.today", "x", "instagram" or a', diff --git a/settings.json.example b/settings.json.example @@ -27,6 +27,12 @@ "jobGapSeconds": {}, "jitter": 0.25 }, + "network": { + "exits": [], + "platforms": {}, + "jars": {}, + "echoUrl": "" + }, "downloadFormat": "auto", "sourceVideoQuality": "original", "minFreeDiskGB": 5,