commit 70e85ecd80886114c1b7be24deb28814e6d72905 parent b82871efd928980f0361f12e9de21fb86cc65708 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 31 Oct 2026 14:40:45 -0400 Merge lane/auto-user-agent: yt-dlp gets the installed Firefox's User-Agent automatically when it borrows Firefox cookies or impersonates Firefox (not YouTube); a --user-agent pin still wins; web pacer, live fetch and stored-URL reads use the derived UA too Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
25 files changed, 853 insertions(+), 38 deletions(-)
diff --git a/CHANNEL.md b/CHANNEL.md @@ -32,7 +32,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `savedVideosDir` | config | Per-channel override for the saved-video store root: this channel's persisted source videos live under `<savedVideosDir>/<slug>/<videoId>/`. Trimmed; blank = the global store. | | `dataDir` | config | RETIRED (release 17). The whole-directory layout's record: the absolute path `channels/<slug>/data` was a symlink to. Still parsed for one release so a write never erases it: a channel that carries it — or whose `data/` is a link — is `legacy`, and every media job, lane and build holds it until `archilyzer storage migrate-tier <slug>` moves its text back and its media into `mediaDir`. Written only by the re-point of a storage location (which keeps it `<root>/<slug>/data` on the new root); removed by that migration. | | `mediaDir` | config | Where this channel's big files live when relocated: `channels/<slug>/media` is a symlink to it, `<root>/<slug>/media`. Absent = in place. Written only by relocate / re-point / the tier migration — a record of what is on disk, never free text, because a value that disagrees with the link is an "inconsistent" channel every media guard refuses. The text (`data/`) never moves. | -| `ytdlpExtraArgs` | config | Extra yt-dlp arguments, appended verbatim. Must be an array of strings or it is dropped. | +| `ytdlpExtraArgs` | config | Extra yt-dlp arguments, appended verbatim (after the platform's own, so they win). Must be an array of strings or it is dropped. No `--user-agent` pin is needed for Firefox's cookies: a spawn that reads Firefox's cookies or passes `--impersonate firefox` (any platform but YouTube) gets the UA of the Firefox on this machine, derived from the profile's `compatibility.ini` (lib/browserUserAgent-server.ts). A `--user-agent` here still wins — only to override it. | | `subLangs` | config | yt-dlp `--sub-langs` value for caption downloads (comma-separated; a leading `-` excludes). Absent = `en.*,live_chat`. The `live_chat` entry is dropped unless `chat` is `"with-download"`. A Configure field. | | `chat` | config | When a stream's live chat replay is fetched: `"with-download"` (default — with the captions, as a `live_chat` subtitle track), `"later"` (the downloads leave it out — each YouTube download of a streaming channel is 2–4× faster — and when the channel has nothing left to download, the download lane queues one paced, resumable `fetch-chat-backlog` job for its `was_live` streams' chats; `pnpm ops fetch-chat-backlog` runs it by hand) or `"never"` (left out; `pnpm ops fetch-chat` still fetches one). A Configure field. | | `lastSyncedAt` | sync state | SYNC STATE. When the channel last synced (ISO time). Stamped by every sync, and by a social fetch; read by the scheduler's cadence gate. | @@ -46,7 +46,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `downloadMode` | config | `"auto"` (default) or `"manual"`. Manual: nothing is downloaded unasked — the download lane skips the channel, a sync or full sweep reads the listing (roster, `playlist`, maybe-missing) but downloads none of the new uploads it finds, and the batch downloads (Download from playlist, Download videos / `download-missing`, a bucket retry) refuse. What someone asks for still downloads: `import-video`, the video page's download and persist buttons, `persist-videos`, clip windows (`fetch-windows`), a whole-recording fetch; videos on disk are still transcribed by the lanes. The listed videos it never downloaded are reported as not requested (`manualNotRequestedIds` in its report), never as undownloaded work or as never-fetched losses. A Configure field (`downloadMode`). | | `downloadFilter` | config | Per-channel title/description download filter, matched against the per-video metadata prefetch. A declined video is SETTLED by a terminal download-outcome keyed on the filter's signature, not by an archive line, so changing either pattern re-evaluates every settled video on the next run. An object with no real rule is dropped (the filter is inert). See [`downloadFilter`](#downloadfilter). | | `skipShorts` | config | `true`: the channel's YouTube Shorts — the listing entries whose URL is `youtube.com/shorts/<id>` — are not wanted. Decided from the listing URL alone (no metadata): a sync or full sweep does not download them, Download from playlist, Download videos and the bucket retries skip them, the metadata scan does not read them, and the report lists the ones with nothing on disk as `skippedShortsIds` instead of as undownloaded work (or, once delisted, as never-fetched losses). Importing a Shorts URL still downloads it, and a Short already on disk stays an ordinary video. Absent = Shorts are downloaded like any upload. A Configure field (`skipShorts`). | -| `cookiesFromBrowser` | config | Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit. | +| `cookiesFromBrowser` | config | Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit. A `firefox[:profile]` spec also sends that Firefox's own User-Agent (derived, so a Cloudflare clearance it earned is honoured after a browser update); a `--user-agent` in `ytdlpExtraArgs` overrides it. | | `cookieMode` | config | Per-channel override of the global cookie mode. Absent = inherit. | | `sleepBetweenDownloadsSeconds` | config | Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600. | | `audioCheck` | config | Audio-integrity checking for sources that intermittently serve corrupt audio mid-download: the managed downloader periodically validates the in-progress `.part` file and rolls back to the last known-good snapshot on corruption (transcribe handling), and a clip window gets the same final probe, fetched once more when malformed and never kept when malformed twice. ON BY DEFAULT for an Odysee video (`audioCheck: {"enabled": false}` turns it off); the channel's opt-in for any other platform. See [`audioCheck`](#audiocheck). | diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -72,7 +72,8 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `ARCHILYZER_SOURCE_REPO` | this checkout's git common dir | The git DIR `archilyzer source publish` mirrors `main` from, when the checkout has none: in Docker, `/data/source.git`, the host's git common dir mounted read-only by docker-compose.source.yml. A value that names nothing refuses the publish. | common/publish/source.ts, common/bin/doctor.ts, docker/entrypoint.sh | | `YTDLP_SOURCE_HOST_DIR` | — (required by the overlay) | Docker: the HOST path of a yt-dlp source checkout (the directory holding `yt_dlp/`), mounted read-only at `/opt/yt-dlp-src` by docker-compose.ytdlp.yml. See [RUNNING_IN_DOCKER.md](RUNNING_IN_DOCKER.md), "Substituting yt-dlp". | docker-compose.ytdlp.yml | | `YTDLP_AUTO_UPDATE` | off | Docker: `1` runs `yt-dlp -U` on every editor boot — on the image's yt-dlp only; an override (`YTDLP_BIN` naming another) is left alone, with a warning. | docker/entrypoint.sh, common/bin/doctor.ts | -| `XDG_CONFIG_HOME` | `~/.config` | Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it. | common/bin/doctor.ts, common/lib/pagesDeploy.ts | +| `XDG_CONFIG_HOME` | `~/.config` | Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it. Also where a Linux Firefox may keep its profiles (`<it>/mozilla/firefox`), whose `compatibility.ini` gives the derived Firefox user agent. | common/bin/doctor.ts, common/lib/pagesDeploy.ts, common/lib/browserUserAgent-server.ts | +| `APPDATA` | `~/AppData/Roaming` | Windows: where Firefox keeps its profiles (`<it>/Mozilla/Firefox`), whose `compatibility.ini` gives the derived Firefox user agent. Set by Windows itself. | common/lib/browserUserAgent-server.ts | | `YTDLP_SOURCE_DIR` | `/opt/yt-dlp-src` | Docker: where `/usr/local/bin/yt-dlp-from-source` finds the yt-dlp source tree it runs with the image's python. | docker/yt-dlp-from-source.sh | | `DOCKER_BIN` | `docker` | The container engine for docker-mode builds (e.g. `podman`). | common/publish/build.ts | | `DOCKER_BUILD_MEMORY` | no cap | Per-container memory cap for a docker-mode build (`--memory`). | common/publish/build.ts | diff --git a/SETTINGS.md b/SETTINGS.md @@ -160,7 +160,7 @@ Default: ## `cookiesFromBrowser` -Browser spec (e.g. "firefox", "chrome:Default", "firefox:/data/browser/firefox" for a profile directory) passed to `yt-dlp --cookies-from-browser` — or `file:<path>`, a cookies.txt passed as `--cookies <path>` (for a container or a server with no browser). WHEN it is passed is governed by `cookieMode` below. Empty string = no cookies configured. Per-channel override available (ChannelConfig.cookiesFromBrowser). +Browser spec (e.g. "firefox", "chrome:Default", "firefox:/data/browser/firefox" for a profile directory) passed to `yt-dlp --cookies-from-browser` — or `file:<path>`, a cookies.txt passed as `--cookies <path>` (for a container or a server with no browser). WHEN it is passed is governed by `cookieMode` below. Empty string = no cookies configured. A `firefox` spec also sends the User-Agent of the Firefox on this machine, derived from its profile (outside YouTube; a channel's `--user-agent` in `ytdlpExtraArgs` overrides it). Per-channel override available (ChannelConfig.cookiesFromBrowser). Default: `""` diff --git a/common/controller/checkAvailability.ts b/common/controller/checkAvailability.ts @@ -28,7 +28,7 @@ import { getSettings } from "../lib/settings"; // digest registry's claude-code lane, which has the same problem. import { parseStdoutJson } from "../lib/parseStdoutJson"; import { readChannelConfig } from "./channels"; -import { channelExtraArgs, pacedPlatformArgs } from "../ytdlp/channelArgs"; +import { channelExtraArgs, pacedPlatformArgs, withBrowserUserAgent } from "../ytdlp/channelArgs"; import { detectPlatform } from "../lib/platform"; import { resolveShardItems } from "./shard"; import type { Paths } from "../lib/paths"; @@ -270,11 +270,15 @@ export async function runAvailabilityCheck({ "--no-warnings", ...(config ? channelExtraArgs(config, probeCookies) - : [ - ...cookieArgs(probeCookies), - // At the platform's current pace (release 17, slice RL). - ...pacedPlatformArgs(detectPlatform(url)), - ]), + : withBrowserUserAgent( + [ + ...cookieArgs(probeCookies), + // At the platform's current pace (release 17, slice RL). + ...pacedPlatformArgs(detectPlatform(url)), + ], + // Firefox's cookies go with Firefox's user agent, as in channelExtraArgs. + detectPlatform(url), + )), "--", url, ]; diff --git a/common/controller/feedMetadataBackfill.ts b/common/controller/feedMetadataBackfill.ts @@ -311,6 +311,7 @@ export const fetchFeedText: FetchFeed = async (url, signal) => { headers: { accept: "application/rss+xml, application/xml;q=0.9, text/xml;q=0.8, */*;q=0.1", + // Identifies the project on purpose: a public feed, read as a bot — never the derived browser UA. "user-agent": `${PROJECT_NAME} feed backfill (+${PROJECT_URL})`, }, }); diff --git a/common/controller/fetchWindowsStoredUrl.test.ts b/common/controller/fetchWindowsStoredUrl.test.ts @@ -15,6 +15,7 @@ import { fetchWindows, storedUrlDoor, type FetchWindowsDeps, type FetchWindowsIt import { parseClipProvenance } from "../lib/clipWindow"; import { detectPlatform } from "../lib/platform"; import type { StoredUrlMode } from "../lib/storedMediaUrl"; +import { storedMediaUserAgent } from "../lib/storedMediaUrl-server"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { SiteSettings } from "../lib/settings"; @@ -180,7 +181,7 @@ test("fallback: the page 429s, the window is cut from the stored CDN URL after t // ffmpeg, read the way the site's player reads it: the page's Referer AND Origin, // a browser user agent, an input seek to the window (ranged requests), the window's length. assert.equal(cdnArgs[cdnArgs.indexOf("-headers") + 1], "Referer: https://odysee.com/\r\nOrigin: https://odysee.com\r\n"); - assert.match(cdnArgs[cdnArgs.indexOf("-user_agent") + 1], /Chrome\//); + assert.equal(cdnArgs[cdnArgs.indexOf("-user_agent") + 1], storedMediaUserAgent()); assert.ok(cdnArgs.indexOf("-ss") < cdnArgs.indexOf("-i"), "an input seek: only the window's bytes are fetched"); assert.equal(cdnArgs[cdnArgs.indexOf("-ss") + 1], "10.00"); assert.equal(cdnArgs[cdnArgs.indexOf("-t") + 1], "10.00"); diff --git a/common/controller/recheckServiceCookies.ts b/common/controller/recheckServiceCookies.ts @@ -47,7 +47,7 @@ import { } from "../lib/serviceCookies-server"; import { recordPlatformClean } from "../jobs/downloadBackoff"; import { runOneYtdlp, type AttemptOutcome } from "../ytdlp/runOneYtdlp"; -import { channelExtraArgs, configForVideoUrl, pacedPlatformArgs } from "../ytdlp/channelArgs"; +import { channelExtraArgs, configForVideoUrl, pacedPlatformArgs, withBrowserUserAgent } from "../ytdlp/channelArgs"; import type { ChannelConfig } from "../lib/channelConfig"; import { readChannelConfig } from "./channels"; @@ -129,7 +129,9 @@ export function recheckYtdlpArgs(url: string, config: ChannelConfig | null, cook "--skip-download", "--print", "id", - ...(config ? channelExtraArgs(configForVideoUrl(config, url), cookies) : [...cookieArgs(cookies), ...pacedPlatformArgs(platform)]), + ...(config + ? channelExtraArgs(configForVideoUrl(config, url), cookies) + : withBrowserUserAgent([...cookieArgs(cookies), ...pacedPlatformArgs(platform)], platform)), "--no-write-info-json", "--no-write-description", "--no-write-thumbnail", diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -89,6 +89,7 @@ import { mp4CanHold, type MediaProbe } from "../lib/mediaImport"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { channelExtraArgs, configForVideoUrl } from "../ytdlp/channelArgs"; +import { browserUserAgentOr } from "../lib/browserUserAgent-server"; import { dataDirIdForUrl } from "../ytdlp/runYtdlp"; import { ensureStoreRoot, @@ -121,9 +122,14 @@ export const RECORD_LIVE_BODY_KEYS = [ "preclip", ] as const; -// The user agent path B's ffmpeg and the playlist reads present (the pinned -// Firefox the Rumble channels' `ytdlpExtraArgs` carry). -export const LIVE_FETCH_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:156.0) Gecko/20100101 Firefox/156.0"; +// The user agent path B's ffmpeg and the playlist reads present: the Firefox on +// this machine (lib/browserUserAgent-server.ts) — the one whose cookies and UA +// the Rumble channels' yt-dlp spawns carry — else the module's fixed Firefox, +// for a machine with none (the request still has to look like a browser). It +// was a pinned Firefox 156 here, already behind the browser. +export function liveFetchUserAgent(): string { + return browserUserAgentOr(); +} // Kick's VOD poller: how often the playlist is read, and how long it may stop // growing before the stream counts as over (shorter once the channel's live @@ -337,13 +343,13 @@ function withTimeout(signal: AbortSignal, ms: number): AbortSignal { } export const fetchText: FetchText = async (url, signal) => { - const r = await fetch(url, { headers: { "user-agent": LIVE_FETCH_USER_AGENT }, signal: withTimeout(signal, 30_000) }); + const r = await fetch(url, { headers: { "user-agent": liveFetchUserAgent() }, signal: withTimeout(signal, 30_000) }); if (!r.ok) throw new Error(`HTTP ${r.status} for ${url}`); return r.text(); }; export const fetchBytes: FetchBytes = async (url, signal) => { - const r = await fetch(url, { headers: { "user-agent": LIVE_FETCH_USER_AGENT }, signal: withTimeout(signal, 60_000) }); + const r = await fetch(url, { headers: { "user-agent": liveFetchUserAgent() }, signal: withTimeout(signal, 60_000) }); if (!r.ok) throw new Error(`HTTP ${r.status} for ${url}`); return new Uint8Array(await r.arrayBuffer()); }; @@ -973,7 +979,7 @@ export async function recordLiveRun( await save(); const o = await runRecorder({ bin: paths.ffmpegBin, - args: ffmpegLiveArgs({ url: chosen, output: file, fromStart, userAgent: LIVE_FETCH_USER_AGENT, referer: "https://rumble.com/" }), + args: ffmpegLiveArgs({ url: chosen, output: file, fromStart, userAgent: liveFetchUserAgent(), referer: "https://rumble.com/" }), cwd: channelDir, onLog, signal, diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts @@ -44,6 +44,7 @@ import { rename, rm, stat } from "node:fs/promises"; import { jitterUp } from "./jitter.mjs"; import { pacingJitter } from "./jitter"; +// Identifies the project ON PURPOSE (an archive asks bots to say who they are) — never the derived browser UA. export const ARCHIVE_ORG_USER_AGENT = `${PROJECT_NAME} archive.org import (+${PROJECT_URL})`; export class ArchiveOrgRequestError extends Error { diff --git a/common/lib/archives/archiveTodayClient.ts b/common/lib/archives/archiveTodayClient.ts @@ -52,6 +52,7 @@ import { import { ArchiveRefusal, type ArchiveCaptureRow, type ArchiveMementoRef, type ArchiveRawCapture } from "./types"; export const ARCHIVE_TODAY_QUEUE = "platform:archive.today"; +// Identifies the project ON PURPOSE (an archive asks bots to say who they are) — never the derived browser UA. export const ARCHIVE_TODAY_USER_AGENT = `${PROJECT_NAME} archive.today import (+${PROJECT_URL})`; export const ARCHIVE_TODAY_MAX_REDIRECTS = 5; // A copy's body is read up to this (the Wayback page cap's size). diff --git a/common/lib/browserUserAgent-server.test.ts b/common/lib/browserUserAgent-server.test.ts @@ -0,0 +1,222 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { + browserUserAgentOr, + defaultProfileFromIni, + deriveFirefoxUserAgent, + FALLBACK_FIREFOX_VERSION, + firefoxOsToken, + firefoxRoots, + firefoxUserAgent, + formatFirefoxUserAgent, + parseCompatibilityIniVersion, + parseCookieBrowserSpec, + parseFirefoxVersionOutput, + PROFILE_TTL_MS, + resolveFirefoxProfile, + setFirefoxUserAgentForTests, +} from "./browserUserAgent-server"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/browserUserAgent-server.test.ts + +const compat = (v: string) => + `[Compatibility]\nLastVersion=${v}_20261015234007/20261015234007\nLastOSABI=Linux_x86_64-gcc3\nLastPlatformDir=/usr/lib/firefox\n`; + +// A temp HOME with ~/.mozilla/firefox holding `profiles` (name → version, or +// null for no compatibility.ini), each with a cookies.sqlite of the given age. +function fakeHome( + profiles: Record<string, { version: string | null; cookiesAgeS?: number }>, + ini?: { installs?: string; profiles?: string }, +): { home: string; root: string } { + const home = mkdtempSync(path.join(os.tmpdir(), "ff-ua-")); + const root = path.join(home, ".mozilla", "firefox"); + mkdirSync(root, { recursive: true }); + for (const [name, p] of Object.entries(profiles)) { + const dir = path.join(root, name); + mkdirSync(dir); + if (p.version) writeFileSync(path.join(dir, "compatibility.ini"), compat(p.version)); + if (p.cookiesAgeS !== undefined) { + const f = path.join(dir, "cookies.sqlite"); + writeFileSync(f, ""); + const t = Date.now() / 1000 - p.cookiesAgeS; + utimesSync(f, t, t); + } + } + if (ini?.installs) writeFileSync(path.join(root, "installs.ini"), ini.installs); + if (ini?.profiles) writeFileSync(path.join(root, "profiles.ini"), ini.profiles); + return { home, root }; +} + +const LINUX = { platform: "linux" as const, env: {} as NodeJS.ProcessEnv }; +const noBinary = () => null; + +test("compatibility.ini's LastVersion, and `firefox --version`, parse to the version", () => { + assert.equal(parseCompatibilityIniVersion(compat("158.0")), "158.0"); + assert.equal(parseCompatibilityIniVersion(compat("149.0.2")), "149.0.2"); + assert.equal(parseCompatibilityIniVersion("[Compatibility]\nLastOSABI=x\n"), null); + assert.equal(parseCompatibilityIniVersion(""), null); + assert.equal(parseFirefoxVersionOutput("Mozilla Firefox 158.0\n"), "158.0"); + assert.equal(parseFirefoxVersionOutput("Mozilla Firefox 140.4.0esr"), "140.4.0"); + assert.equal(parseFirefoxVersionOutput("command not found"), null); +}); + +test("the UA is Firefox's own format, major.0, with this platform's token", () => { + assert.equal( + formatFirefoxUserAgent("158.0", "linux", "x64"), + "Mozilla/5.0 (X11; Linux x86_64; rv:158.0) Gecko/20100101 Firefox/158.0", + ); + assert.equal( + formatFirefoxUserAgent("149.0.2", "linux", "x64"), + "Mozilla/5.0 (X11; Linux x86_64; rv:149.0) Gecko/20100101 Firefox/149.0", + ); + assert.equal( + formatFirefoxUserAgent("158.0", "darwin", "arm64"), + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:158.0) Gecko/20100101 Firefox/158.0", + ); + assert.equal( + formatFirefoxUserAgent("158.0", "win32", "x64"), + "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:158.0) Gecko/20100101 Firefox/158.0", + ); + assert.equal(firefoxOsToken("linux", "arm64"), "X11; Linux aarch64"); + assert.equal(formatFirefoxUserAgent("nightly", "linux", "x64"), null); +}); + +test("cookie specs parse as yt-dlp's BROWSER[+KEYRING][:PROFILE][::CONTAINER]", () => { + assert.deepEqual(parseCookieBrowserSpec("firefox"), { browser: "firefox" }); + assert.deepEqual(parseCookieBrowserSpec("Firefox:/data/ff"), { browser: "firefox", profile: "/data/ff" }); + assert.deepEqual(parseCookieBrowserSpec("firefox:work::Personal"), { + browser: "firefox", + profile: "work", + container: "Personal", + }); + assert.deepEqual(parseCookieBrowserSpec("firefox::Personal"), { browser: "firefox", container: "Personal" }); + assert.deepEqual(parseCookieBrowserSpec("chrome+gnomekeyring:Default"), { + browser: "chrome", + keyring: "gnomekeyring", + profile: "Default", + }); + assert.equal(parseCookieBrowserSpec("file:/x/cookies.txt"), null); + assert.equal(parseCookieBrowserSpec(""), null); + assert.equal(parseCookieBrowserSpec(undefined), null); +}); + +test("roots per platform, in yt-dlp's order", () => { + assert.deepEqual(firefoxRoots("/h", "linux", {}), [ + "/h/.config/mozilla/firefox", + "/h/.mozilla/firefox", + "/h/snap/firefox/common/.mozilla/firefox", + "/h/.var/app/org.mozilla.firefox/.mozilla/firefox", + ]); + assert.deepEqual(firefoxRoots("/h", "darwin", {}), ["/h/Library/Application Support/Firefox"]); +}); + +test("the default profile: installs.ini, else profiles.ini's Install, Default=1, or only profile", () => { + const files: Record<string, string> = {}; + const read = (p: string) => files[p] ?? null; + files["/r/profiles.ini"] = "[Profile0]\nName=a\nIsRelative=1\nPath=a.default\n\n[Profile1]\nName=b\nIsRelative=1\nPath=b.x\nDefault=1\n"; + assert.equal(defaultProfileFromIni("/r", read), "/r/b.x"); + files["/r/profiles.ini"] += "\n[Install4F96]\nDefault=a.default\nLocked=1\n"; + assert.equal(defaultProfileFromIni("/r", read), "/r/a.default"); + files["/r/installs.ini"] = "[4F96D1932A9F858E]\nDefault=c.release\n"; + assert.equal(defaultProfileFromIni("/r", read), "/r/c.release"); + assert.equal(defaultProfileFromIni("/r", () => "[Profile0]\nIsRelative=0\nPath=/abs/p\n"), "/abs/p"); + assert.equal(defaultProfileFromIni("/r", () => null), null); +}); + +test("yt-dlp's profile: the newest cookies.sqlite; a named one; else the ini's default", () => { + const { home, root } = fakeHome( + { + "old.default": { version: "107.0.1", cookiesAgeS: 86400 * 400 }, + "cur.default-release": { version: "158.0", cookiesAgeS: 60 }, + "rec.Recording": { version: "149.0.2", cookiesAgeS: 86400 * 30 }, + }, + ); + assert.equal(resolveFirefoxProfile(undefined, { home, ...LINUX }), path.join(root, "cur.default-release")); + assert.equal(resolveFirefoxProfile("rec.Recording", { home, ...LINUX }), path.join(root, "rec.Recording")); + assert.equal(resolveFirefoxProfile(path.join(root, "old.default"), { home, ...LINUX }), path.join(root, "old.default")); + assert.equal(resolveFirefoxProfile("missing", { home, ...LINUX }), null); + + const noCookies = fakeHome( + { "a.default": { version: "150.0" }, "b.main": { version: "158.0" } }, + { installs: "[ABC]\nDefault=b.main\n" }, + ); + assert.equal(resolveFirefoxProfile(undefined, { home: noCookies.home, ...LINUX }), path.join(noCookies.root, "b.main")); +}); + +test("derived from the profile; re-read when compatibility.ini changes", () => { + const { home, root } = fakeHome({ "cur.default": { version: "158.0", cookiesAgeS: 10 } }); + let now = 1_000_000; + const deps = { home, ...LINUX, arch: "x64", now: () => now, firefoxVersion: noBinary }; + const a = deriveFirefoxUserAgent(undefined, deps); + assert.equal(a?.source, "profile"); + assert.equal(a?.userAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:158.0) Gecko/20100101 Firefox/158.0"); + + // Firefox updated: it rewrote compatibility.ini (a new mtime) — picked up within the TTL. + const f = path.join(root, "cur.default", "compatibility.ini"); + writeFileSync(f, compat("159.0")); + const t = Date.now() / 1000 + 5; + utimesSync(f, t, t); + now += 1_000; + assert.equal(deriveFirefoxUserAgent(undefined, deps)?.version, "159.0"); + + // After the TTL the profile is resolved again (a new profile's cookies are newer). + mkdirSync(path.join(root, "new.default")); + writeFileSync(path.join(root, "new.default", "compatibility.ini"), compat("160.0")); + writeFileSync(path.join(root, "new.default", "cookies.sqlite"), ""); + utimesSync(path.join(root, "new.default", "cookies.sqlite"), t + 10, t + 10); + assert.equal(deriveFirefoxUserAgent(undefined, deps)?.version, "159.0", "within the TTL: the same profile"); + now += PROFILE_TTL_MS; + assert.equal(deriveFirefoxUserAgent(undefined, deps)?.version, "160.0"); +}); + +test("no version in the profile: `firefox --version`, else the logged fallback", () => { + const { home } = fakeHome({ "x.default": { version: null, cookiesAgeS: 10 } }); + const bin = deriveFirefoxUserAgent(undefined, { home, ...LINUX, arch: "x64", firefoxVersion: () => "157.0" }); + assert.equal(bin?.source, "binary"); + assert.equal(bin?.version, "157.0"); + + const other = fakeHome({ "y.default": { version: null, cookiesAgeS: 10 } }); + const logs: string[] = []; + setFirefoxUserAgentForTests(undefined); // clears the once-only warning + const fb = deriveFirefoxUserAgent(undefined, { + home: other.home, + ...LINUX, + arch: "x64", + firefoxVersion: noBinary, + log: (m) => logs.push(m), + }); + assert.equal(fb?.source, "fallback"); + assert.equal(fb?.version, FALLBACK_FIREFOX_VERSION); + assert.equal(logs.length, 1); + assert.match(logs[0], /FALLBACK_FIREFOX_VERSION/); +}); + +test("no Firefox at all (a container): null, and callers that need a browser get their fallback", () => { + const home = mkdtempSync(path.join(os.tmpdir(), "ff-none-")); + assert.equal(deriveFirefoxUserAgent(undefined, { home, ...LINUX, firefoxVersion: noBinary }), null); + // The binary alone is enough (a Firefox that has never been opened). + const home2 = mkdtempSync(path.join(os.tmpdir(), "ff-bin-")); + assert.equal( + deriveFirefoxUserAgent(undefined, { home: home2, ...LINUX, arch: "x64", firefoxVersion: () => "158.0" })?.source, + "binary", + ); + + setFirefoxUserAgentForTests(null); + try { + assert.equal(firefoxUserAgent("firefox"), null); + assert.equal(browserUserAgentOr("UA-FALLBACK"), "UA-FALLBACK"); + } finally { + setFirefoxUserAgentForTests(undefined); + } + setFirefoxUserAgentForTests("UA-X"); + try { + assert.equal(firefoxUserAgent(), "UA-X"); + assert.equal(browserUserAgentOr("UA-FALLBACK"), "UA-X"); + } finally { + setFirefoxUserAgentForTests(undefined); + } +}); diff --git a/common/lib/browserUserAgent-server.ts b/common/lib/browserUserAgent-server.ts @@ -0,0 +1,371 @@ +// THE USER AGENT OF THE FIREFOX ON THIS MACHINE — derived, never pinned. +// +// A channel that borrows Firefox's cookies (`cookiesFromBrowser: "firefox"`) — +// Rumble's Cloudflare `cf_clearance`, Odysee — must send the SAME User-Agent as +// the Firefox that earned the clearance, or Cloudflare refuses it (403). Until +// this module each such channel pinned it by hand in `ytdlpExtraArgs` +// (`--user-agent "… Firefox/158.0"`), and every Firefox update silently broke +// all of them until someone edited every config. yt-dlp's own +// `--impersonate firefox` does not help: its UA is the older Firefox the +// impersonation target was built from. +// +// So the version is read from the Firefox PROFILE yt-dlp reads cookies from: +// +// 1. the profile — the one the cookie spec names (`firefox:<name|path>`), else +// yt-dlp's own choice (the profile whose `cookies.sqlite` is newest; only +// its mtime is looked at, never its contents), else the install's default +// (installs.ini / profiles.ini) — and its `compatibility.ini` +// `LastVersion=158.0_<build>/<build>`, the version that last ran it; +// 2. else `firefox --version` ("Mozilla Firefox 158.0"); +// 3. else, when a Firefox profile directory exists at all but neither said a +// version, FALLBACK_FIREFOX_VERSION — logged once, because a UA that is +// not the browser's will be refused the moment the browser moves on; +// 4. else null: no Firefox here (a Docker container, a server), and callers +// add nothing. +// +// The OS token is this process's platform, in Firefox's own spelling. +// Cached: the profile is re-resolved at most every PROFILE_TTL_MS, its +// compatibility.ini is re-read whenever its mtime changes, and `firefox +// --version` is asked at most once per PROFILE_TTL_MS. +// +// Server-only (node:fs, node:child_process). The argv rule that uses it is +// `withBrowserUserAgent` in ytdlp/channelArgs.ts. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { execFileSync } from "node:child_process"; + +// The version used when a Firefox profile exists but no version could be read +// from it or from `firefox --version`: the operator's Firefox when this module +// was written (2026-10-31). Only a last resort — see the header. +export const FALLBACK_FIREFOX_VERSION = "158.0"; + +export const PROFILE_TTL_MS = 5 * 60_000; + +// ── pure parts ─────────────────────────────────────────────────────────────── + +// Firefox's platform token: what `navigator.userAgent` says inside the +// parentheses. Linux reports X11 even under Wayland; macOS has been frozen at +// 10.15 and Windows at NT 10.0 since Firefox 87 / 116. +export function firefoxOsToken( + platform: NodeJS.Platform = process.platform, + arch: string = process.arch, +): string { + if (platform === "darwin") return "Macintosh; Intel Mac OS X 10.15"; + if (platform === "win32") return "Windows NT 10.0; Win64; x64"; + const machine = arch === "arm64" ? "aarch64" : arch === "ia32" ? "i686" : "x86_64"; + return `X11; Linux ${machine}`; +} + +// Firefox's UA carries only the major version, as `<major>.0` (115.3.1 sends +// `rv:115.0 … Firefox/115.0`). +export function formatFirefoxUserAgent( + version: string, + platform: NodeJS.Platform = process.platform, + arch: string = process.arch, +): string | null { + const major = /^(\d+)/.exec(version.trim())?.[1]; + if (!major) return null; + const v = `${Number(major)}.0`; + return `Mozilla/5.0 (${firefoxOsToken(platform, arch)}; rv:${v}) Gecko/20100101 Firefox/${v}`; +} + +// A minimal INI reader: sections of key=value lines, `;`/`#` comments. +export function parseIni(text: string): Record<string, Record<string, string>> { + const out: Record<string, Record<string, string>> = {}; + let section = ""; + for (const raw of text.split(/\r?\n/)) { + const line = raw.trim(); + if (!line || line.startsWith(";") || line.startsWith("#")) continue; + const head = /^\[(.*)\]$/.exec(line); + if (head) { + section = head[1]; + out[section] ??= {}; + continue; + } + const eq = line.indexOf("="); + if (eq <= 0) continue; + (out[section] ??= {})[line.slice(0, eq).trim()] = line.slice(eq + 1).trim(); + } + return out; +} + +// `LastVersion=158.0_20261015234007/20261015234007` → "158.0". +export function parseCompatibilityIniVersion(text: string): string | null { + const v = parseIni(text).Compatibility?.LastVersion ?? ""; + const m = /^(\d+(?:\.\d+)*)/.exec(v); + return m ? m[1] : null; +} + +// `Mozilla Firefox 158.0` (or `… 140.4.0esr`) → "158.0" / "140.4.0". +export function parseFirefoxVersionOutput(text: string): string | null { + const m = /Firefox\s+(\d+(?:\.\d+)*)/i.exec(text); + return m ? m[1] : null; +} + +export type CookieBrowserSpec = { + browser: string; + keyring?: string; + profile?: string; + container?: string; +}; + +// yt-dlp's `BROWSER[+KEYRING][:PROFILE][::CONTAINER]`. Null for `file:<path>` +// (a cookies.txt, no browser) and for an empty spec. +export function parseCookieBrowserSpec(spec: string | undefined | null): CookieBrowserSpec | null { + const s = spec?.trim() ?? ""; + if (!s || s.startsWith("file:")) return null; + const m = /^([^+:]+)(?:\+([^:]+))?(?::(?!:)(.+?))?(?:::(.+))?$/.exec(s); + if (!m) return null; + return { + browser: m[1].toLowerCase(), + ...(m[2] ? { keyring: m[2] } : {}), + ...(m[3] ? { profile: m[3] } : {}), + ...(m[4] ? { container: m[4] } : {}), + }; +} + +// The directories that hold Firefox profiles (and profiles.ini) on this +// platform — yt-dlp's `_firefox_browser_dirs`, in its order. +export function firefoxRoots( + home: string, + platform: NodeJS.Platform = process.platform, + env: NodeJS.ProcessEnv = process.env, +): string[] { + if (platform === "darwin") return [path.join(home, "Library", "Application Support", "Firefox")]; + if (platform === "win32") { + const appData = env.APPDATA || path.join(home, "AppData", "Roaming"); + return [path.join(appData, "Mozilla", "Firefox")]; + } + const xdg = env.XDG_CONFIG_HOME || path.join(home, ".config"); + return [ + path.join(xdg, "mozilla", "firefox"), + path.join(home, ".mozilla", "firefox"), + path.join(home, "snap", "firefox", "common", ".mozilla", "firefox"), + path.join(home, ".var", "app", "org.mozilla.firefox", ".mozilla", "firefox"), + ]; +} + +// The install's default profile from a root's installs.ini / profiles.ini: +// an `[Install…]` section's `Default=` (what Firefox actually opens), else the +// `[Profile…]` marked `Default=1`, else the only profile. An absolute path. +export function defaultProfileFromIni(root: string, read: (p: string) => string | null = readText): string | null { + const resolve = (p: string, relative = true) => (relative && !path.isAbsolute(p) ? path.join(root, p) : p); + for (const file of ["installs.ini", "profiles.ini"]) { + const text = read(path.join(root, file)); + if (!text) continue; + const ini = parseIni(text); + for (const [name, sec] of Object.entries(ini)) { + if ((file === "installs.ini" || name.startsWith("Install")) && sec.Default) return resolve(sec.Default); + } + } + const profiles = Object.entries(parseIni(read(path.join(root, "profiles.ini")) ?? "")).filter( + ([name, sec]) => name.startsWith("Profile") && sec.Path, + ); + const chosen = profiles.find(([, sec]) => sec.Default === "1") ?? (profiles.length === 1 ? profiles[0] : undefined); + return chosen ? resolve(chosen[1].Path, chosen[1].IsRelative !== "0") : null; +} + +// ── the filesystem ─────────────────────────────────────────────────────────── + +function readText(p: string): string | null { + try { + return fs.readFileSync(p, "utf8"); + } catch { + return null; + } +} + +function mtimeMs(p: string): number | null { + try { + return fs.statSync(p).mtimeMs; + } catch { + return null; + } +} + +function isDir(p: string): boolean { + try { + return fs.statSync(p).isDirectory(); + } catch { + return false; + } +} + +// Every profile directory under a root: its direct children and those of +// `Profiles/` (the macOS and Windows layout). +function profileDirs(root: string): string[] { + const out: string[] = []; + for (const dir of [root, path.join(root, "Profiles")]) { + let names: string[]; + try { + names = fs.readdirSync(dir); + } catch { + continue; + } + for (const n of names) { + const p = path.join(dir, n); + if (n !== "Profiles" && isDir(p)) out.push(p); + } + } + return out; +} + +export type ProfileEnv = { + home?: string; + platform?: NodeJS.Platform; + env?: NodeJS.ProcessEnv; +}; + +// The profile directory yt-dlp would read Firefox cookies from for `profile` +// (the spec's PROFILE part): a path is that directory; a name is that +// directory under the first root holding it; none is the profile whose +// `cookies.sqlite` was written last (yt-dlp's rule), else the install's +// default. Null when there is no Firefox profile here at all. +export function resolveFirefoxProfile(profile: string | undefined, e: ProfileEnv = {}): string | null { + const home = e.home ?? os.homedir(); + const roots = firefoxRoots(home, e.platform, e.env).filter(isDir); + if (profile) { + if (profile.includes("/") || profile.includes("\\")) return isDir(profile) ? profile : null; + for (const r of roots) { + for (const p of [path.join(r, profile), path.join(r, "Profiles", profile)]) if (isDir(p)) return p; + } + return null; + } + let newest: { dir: string; at: number } | null = null; + for (const r of roots) { + for (const dir of profileDirs(r)) { + const at = mtimeMs(path.join(dir, "cookies.sqlite")); + if (at !== null && (!newest || at > newest.at)) newest = { dir, at }; + } + } + if (newest) return newest.dir; + for (const r of roots) { + const d = defaultProfileFromIni(r); + if (d && isDir(d)) return d; + } + return null; +} + +function firefoxVersionFromBinary(): string | null { + try { + const out = execFileSync("firefox", ["--version"], { + encoding: "utf8", + timeout: 5_000, + stdio: ["ignore", "pipe", "ignore"], + }); + return parseFirefoxVersionOutput(out); + } catch { + return null; + } +} + +// ── the cached derivation ──────────────────────────────────────────────────── + +export type FirefoxVersionSource = "profile" | "binary" | "fallback"; + +export type DerivedUserAgent = { + userAgent: string; + version: string; + source: FirefoxVersionSource; + profileDir: string | null; +}; + +export type DeriveDeps = ProfileEnv & { + now?: () => number; + firefoxVersion?: () => string | null; + arch?: string; + log?: (msg: string) => void; +}; + +type CacheEntry = { + resolvedAt: number; + profileDir: string | null; + compatMtime: number | null; + binaryVersion: string | null | undefined; + result: DerivedUserAgent | null; +}; + +const cache = new Map<string, CacheEntry>(); +let warnedFallback = false; +let override: { ua: string | null } | undefined; + +// For tests: pin what `firefoxUserAgent` returns (a string, or null for "no +// Firefox here"); `undefined` restores the derivation. Clears the cache. +export function setFirefoxUserAgentForTests(ua: string | null | undefined): void { + override = ua === undefined ? undefined : { ua }; + cache.clear(); + warnedFallback = false; +} + +// The full derivation, for one cookie spec's profile (undefined = yt-dlp's +// default choice). `deps` replace the machine for tests. +export function deriveFirefoxUserAgent(profile?: string, deps: DeriveDeps = {}): DerivedUserAgent | null { + const now = (deps.now ?? Date.now)(); + const key = JSON.stringify([profile ?? "", deps.home ?? "", deps.platform ?? ""]); + let entry = cache.get(key); + if (!entry || now - entry.resolvedAt >= PROFILE_TTL_MS) { + entry = { + resolvedAt: now, + profileDir: resolveFirefoxProfile(profile, deps), + compatMtime: null, + binaryVersion: undefined, + result: null, + }; + cache.set(key, entry); + entry.result = compute(entry, deps); + return entry.result; + } + // Within the TTL: the same profile, re-read only when Firefox rewrote its + // compatibility.ini (an update ran it). + const compat = entry.profileDir ? mtimeMs(path.join(entry.profileDir, "compatibility.ini")) : null; + if (compat !== entry.compatMtime) entry.result = compute(entry, deps); + return entry.result; +} + +function compute(entry: CacheEntry, deps: DeriveDeps): DerivedUserAgent | null { + const platform = deps.platform ?? process.platform; + const arch = deps.arch ?? process.arch; + const make = (version: string, source: FirefoxVersionSource): DerivedUserAgent | null => { + const userAgent = formatFirefoxUserAgent(version, platform, arch); + return userAgent ? { userAgent, version, source, profileDir: entry.profileDir } : null; + }; + if (entry.profileDir) { + const compatFile = path.join(entry.profileDir, "compatibility.ini"); + entry.compatMtime = mtimeMs(compatFile); + const text = readText(compatFile); + const v = text ? parseCompatibilityIniVersion(text) : null; + if (v) return make(v, "profile"); + } + if (entry.binaryVersion === undefined) entry.binaryVersion = (deps.firefoxVersion ?? firefoxVersionFromBinary)(); + if (entry.binaryVersion) return make(entry.binaryVersion, "binary"); + if (!entry.profileDir) return null; + if (!warnedFallback) { + warnedFallback = true; + (deps.log ?? ((m: string) => console.warn(m)))( + `browser user agent: no Firefox version in ${entry.profileDir}/compatibility.ini and no \`firefox --version\`; ` + + `sending Firefox ${FALLBACK_FIREFOX_VERSION} (FALLBACK_FIREFOX_VERSION) — Cloudflare refuses it once the browser is newer`, + ); + } + return make(FALLBACK_FIREFOX_VERSION, "fallback"); +} + +// THE ENTRY POINT: the User-Agent of the Firefox whose cookies `cookieSpec` +// (a `--cookies-from-browser` spec; undefined = the default profile) reads, or +// null when there is no Firefox on this machine. +export function firefoxUserAgent(cookieSpec?: string): string | null { + if (override) return override.ua; + const spec = parseCookieBrowserSpec(cookieSpec); + const profile = spec?.browser === "firefox" ? spec.profile : undefined; + return deriveFirefoxUserAgent(profile)?.userAgent ?? null; +} + +// FALLBACK_FIREFOX_VERSION as this platform's Firefox would send it. +export const FALLBACK_FIREFOX_USER_AGENT = formatFirefoxUserAgent(FALLBACK_FIREFOX_VERSION)!; + +// For a request that must present SOME browser (not yt-dlp's argv, where no +// Firefox means no flag): this machine's Firefox, else `fallback`. +export function browserUserAgentOr(fallback: string = FALLBACK_FIREFOX_USER_AGENT, cookieSpec?: string): string { + return firefoxUserAgent(cookieSpec) ?? fallback; +} diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -265,7 +265,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { "RETIRED (release 17). The whole-directory layout's record: the absolute path `channels/<slug>/data` was a symlink to. Still parsed for one release so a write never erases it: a channel that carries it — or whose `data/` is a link — is `legacy`, and every media job, lane and build holds it until `archilyzer storage migrate-tier <slug>` moves its text back and its media into `mediaDir`. Written only by the re-point of a storage location (which keeps it `<root>/<slug>/data` on the new root); removed by that migration.", mediaDir: "Where this channel's big files live when relocated: `channels/<slug>/media` is a symlink to it, `<root>/<slug>/media`. Absent = in place. Written only by relocate / re-point / the tier migration — a record of what is on disk, never free text, because a value that disagrees with the link is an \"inconsistent\" channel every media guard refuses. The text (`data/`) never moves.", - ytdlpExtraArgs: "Extra yt-dlp arguments, appended verbatim. Must be an array of strings or it is dropped.", + ytdlpExtraArgs: + "Extra yt-dlp arguments, appended verbatim (after the platform's own, so they win). Must be an array of strings or it is dropped. No `--user-agent` pin is needed for Firefox's cookies: a spawn that reads Firefox's cookies or passes `--impersonate firefox` (any platform but YouTube) gets the UA of the Firefox on this machine, derived from the profile's `compatibility.ini` (lib/browserUserAgent-server.ts). A `--user-agent` here still wins — only to override it.", subLangs: "yt-dlp `--sub-langs` value for caption downloads (comma-separated; a leading `-` excludes). Absent = `en.*,live_chat`. The `live_chat` entry is dropped unless `chat` is `\"with-download\"`. A Configure field.", chat: @@ -291,7 +292,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { skipShorts: "`true`: the channel's YouTube Shorts — the listing entries whose URL is `youtube.com/shorts/<id>` — are not wanted. Decided from the listing URL alone (no metadata): a sync or full sweep does not download them, Download from playlist, Download videos and the bucket retries skip them, the metadata scan does not read them, and the report lists the ones with nothing on disk as `skippedShortsIds` instead of as undownloaded work (or, once delisted, as never-fetched losses). Importing a Shorts URL still downloads it, and a Short already on disk stays an ordinary video. Absent = Shorts are downloaded like any upload. A Configure field (`skipShorts`).", cookiesFromBrowser: - "Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit.", + "Per-channel override of the global cookies-from-browser spec (a browser spec, or `file:<path>` for a cookies.txt). Trimmed; blank = inherit. A `firefox[:profile]` spec also sends that Firefox's own User-Agent (derived, so a Cloudflare clearance it earned is honoured after a browser update); a `--user-agent` in `ytdlpExtraArgs` overrides it.", cookieMode: "Per-channel override of the global cookie mode. Absent = inherit.", sleepBetweenDownloadsSeconds: "Per-channel override for the global pause between downloads. Absent = inherit; 0 = no sleep; floored and capped at 600.", diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -108,7 +108,8 @@ const DECLARED: EnvVarDecl[] = [ { name: "ARCHILYZER_SOURCE_REPO", audience: "runtime", default: "this checkout's git common dir", readBy: "common/publish/source.ts, common/bin/doctor.ts, docker/entrypoint.sh", doc: "The git DIR `archilyzer source publish` mirrors `main` from, when the checkout has none: in Docker, `/data/source.git`, the host's git common dir mounted read-only by docker-compose.source.yml. A value that names nothing refuses the publish." }, { name: "YTDLP_SOURCE_HOST_DIR", audience: "runtime", default: "— (required by the overlay)", readBy: "docker-compose.ytdlp.yml", doc: "Docker: the HOST path of a yt-dlp source checkout (the directory holding `yt_dlp/`), mounted read-only at `/opt/yt-dlp-src` by docker-compose.ytdlp.yml. See [RUNNING_IN_DOCKER.md](RUNNING_IN_DOCKER.md), \"Substituting yt-dlp\"." }, { name: "YTDLP_AUTO_UPDATE", audience: "runtime", default: "off", readBy: "docker/entrypoint.sh, common/bin/doctor.ts", doc: "Docker: `1` runs `yt-dlp -U` on every editor boot — on the image's yt-dlp only; an override (`YTDLP_BIN` naming another) is left alone, with a warning." }, - { name: "XDG_CONFIG_HOME", audience: "runtime", default: "`~/.config`", readBy: "common/bin/doctor.ts, common/lib/pagesDeploy.ts", doc: "Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it." }, + { name: "XDG_CONFIG_HOME", audience: "runtime", default: "`~/.config`", readBy: "common/bin/doctor.ts, common/lib/pagesDeploy.ts, common/lib/browserUserAgent-server.ts", doc: "Where `wrangler login` keeps its config (`<it>/.wrangler/config/default.toml`); the doctor looks for it there, by path, never reading it. Also where a Linux Firefox may keep its profiles (`<it>/mozilla/firefox`), whose `compatibility.ini` gives the derived Firefox user agent." }, + { name: "APPDATA", audience: "runtime", default: "`~/AppData/Roaming`", readBy: "common/lib/browserUserAgent-server.ts", doc: "Windows: where Firefox keeps its profiles (`<it>/Mozilla/Firefox`), whose `compatibility.ini` gives the derived Firefox user agent. Set by Windows itself." }, { name: "YTDLP_SOURCE_DIR", audience: "runtime", default: "`/opt/yt-dlp-src`", readBy: "docker/yt-dlp-from-source.sh", doc: "Docker: where `/usr/local/bin/yt-dlp-from-source` finds the yt-dlp source tree it runs with the image's python." }, { name: "DOCKER_BIN", audience: "runtime", default: "`docker`", readBy: "common/publish/build.ts", doc: "The container engine for docker-mode builds (e.g. `podman`)." }, { name: "DOCKER_BUILD_MEMORY", audience: "runtime", default: "no cap", readBy: "common/publish/build.ts", doc: "Per-container memory cap for a docker-mode build (`--memory`)." }, diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -1874,7 +1874,7 @@ export const siteSettingsSchema = z.object({ "Configured transcription workers (named processing slots). The scheduler distributes each video to the highest-priority free worker. A settings.json predating this field is migrated to a single enabled worker from the active app (see defaultWorkersFromApps). See common/lib/workers.ts.", ), cookiesFromBrowser: settingsField((v): string => (typeof v === "string" ? v.trim() : "")).describe( - "Browser spec (e.g. \"firefox\", \"chrome:Default\", \"firefox:/data/browser/firefox\" for a profile directory) passed to `yt-dlp --cookies-from-browser` — or `file:<path>`, a cookies.txt passed as `--cookies <path>` (for a container or a server with no browser). WHEN it is passed is governed by `cookieMode` below. Empty string = no cookies configured. Per-channel override available (ChannelConfig.cookiesFromBrowser).", + "Browser spec (e.g. \"firefox\", \"chrome:Default\", \"firefox:/data/browser/firefox\" for a profile directory) passed to `yt-dlp --cookies-from-browser` — or `file:<path>`, a cookies.txt passed as `--cookies <path>` (for a container or a server with no browser). WHEN it is passed is governed by `cookieMode` below. Empty string = no cookies configured. A `firefox` spec also sends the User-Agent of the Firefox on this machine, derived from its profile (outside YouTube; a channel's `--user-agent` in `ytdlpExtraArgs` overrides it). Per-channel override available (ChannelConfig.cookiesFromBrowser).", ), cookieMode: settingsField((v): CookieMode => (isCookieMode(v) ? v : DEFAULT_COOKIE_MODE)).describe( "How yt-dlp invocations use the configured cookies (see common/lib/cookiePolicy.ts): \"always\" passes them on every invocation, \"when-required\" (default; the historical behavior) only to retry an auth/age failure, \"defer\" never in normal runs — auth-gated videos are excluded from batches and collected into the per-channel \"Needs cookies\" bucket for a manual cookie run. Per-channel override available (ChannelConfig.cookieMode).", diff --git a/common/lib/storedMediaUrl-server.ts b/common/lib/storedMediaUrl-server.ts @@ -4,7 +4,14 @@ import path from "node:path"; import { readFile } from "node:fs/promises"; -import { storedMediaUrlFromInfo, type StoredMediaUrl } from "./storedMediaUrl"; +import { STORED_MEDIA_USER_AGENT, storedMediaUrlFromInfo, type StoredMediaUrl } from "./storedMediaUrl"; +import { browserUserAgentOr } from "./browserUserAgent-server"; + +// The user agent a stored media URL is read with: this machine's Firefox (a +// current browser), else the fixed STORED_MEDIA_USER_AGENT. +export function storedMediaUserAgent(): string { + return browserUserAgentOr(STORED_MEDIA_USER_AGENT); +} export async function storedMediaUrl(videoDir: string): Promise<StoredMediaUrl | null> { try { diff --git a/common/lib/storedMediaUrl.ts b/common/lib/storedMediaUrl.ts @@ -73,7 +73,12 @@ export type StoredUrlWhy = "rate-limited" | "held" | "only"; // The browser user agent a stored media URL is read with: the player's, not // yt-dlp's (release 32). Shared by the clip cut (ytdlp/fetchWindowManaged.ts) -// and the whole-file ranged download (ytdlp/storedUrlDownload.ts). +// and the whole-file ranged download (ytdlp/storedUrlDownload.ts). Since the +// derived Firefox UA (2026-10-31) this is only the FALLBACK, for a machine with +// no Firefox: storedMediaUserAgent() (storedMediaUrl-server.ts) sends this +// machine's Firefox, which stays current where this Chrome 141 ages. Nothing +// required Chrome — the 2026-10-16 measurement needed "a browser user agent"; +// no cookies go with these reads, so it need not match a cookie jar either. export const STORED_MEDIA_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"; @@ -81,9 +86,10 @@ export const STORED_MEDIA_USER_AGENT = // Referer and Origin and a browser user agent. No cookies, no token. export function storedMediaHeaders( stored: Pick<StoredMediaUrl, "referer">, + userAgent: string = STORED_MEDIA_USER_AGENT, ): Record<string, string> { return { - "User-Agent": STORED_MEDIA_USER_AGENT, + "User-Agent": userAgent, Referer: stored.referer, Origin: new URL(stored.referer).origin, Accept: "*/*", diff --git a/common/lib/web/pacer.ts b/common/lib/web/pacer.ts @@ -11,13 +11,19 @@ // make two streams. import { jitterUp } from "../jitter.mjs"; import { pacingJitter } from "../jitter"; +import { browserUserAgentOr } from "../browserUserAgent-server"; export const WEB_MIN_GAP_MS = 3_000; export const WEB_BACKOFF_BASE_MS = 10_000; export const WEB_BACKOFF_MAX_MS = 120_000; export const WEB_MAX_ATTEMPTS = 3; export const WEB_TIMEOUT_MS = 30_000; -export const WEB_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0"; +// The user agent a web request presents: the Firefox on this machine (a current +// browser, never a pinned one that ages — this was Firefox 128), else the +// module's fixed Firefox. No cookies go with it, so any current browser would do. +export function webUserAgent(): string { + return browserUserAgentOr(); +} const BACK_OFF = new Set([429, 503]); @@ -124,7 +130,7 @@ export class WebPacer { res = await this.deps.fetch(url, { ...init, signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout, - headers: { "user-agent": WEB_USER_AGENT, "accept-language": "en", ...(init.headers as Record<string, string>) }, + headers: { "user-agent": webUserAgent(), "accept-language": "en", ...(init.headers as Record<string, string>) }, }); } catch (e) { this.lastDoneAt = this.deps.now(); diff --git a/common/social/xNitterFetcher.ts b/common/social/xNitterFetcher.ts @@ -274,6 +274,7 @@ export const xNitterFetcher: SocialFetcher = { try { const ctx = await browser.newContext({ + // Chrome-shaped on purpose: this context IS Chromium, so a Firefox UA (lib/browserUserAgent-server.ts) would contradict its fingerprint. userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", }); @@ -401,6 +402,7 @@ xNitterFetcher.checkAvailability = async ({ ids, handle, signal, onLog }) => { const browser = await chromium.launch({ headless: true }); try { const ctx = await browser.newContext({ + // Chrome-shaped on purpose: this context IS Chromium, so a Firefox UA (lib/browserUserAgent-server.ts) would contradict its fingerprint. userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", }); diff --git a/common/ytdlp/channelArgs.test.ts b/common/ytdlp/channelArgs.test.ts @@ -14,8 +14,11 @@ import { platformMinGapSeconds, staticSleepRequestsSeconds, withSleepRequests, + hasUserAgentArg, + withBrowserUserAgent, } from "./channelArgs"; import type { ChannelConfig } from "../lib/channelConfig"; +import { setFirefoxUserAgentForTests } from "../lib/browserUserAgent-server"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/channelArgs.test.ts @@ -70,7 +73,10 @@ test("an explicit config.platform wins over the URL's host", () => { ); }); -test("order: cookies, then platform args, then the channel's own (so an override wins)", () => { +test("order: cookies, then platform args, then the channel's own (so an override wins)", (t) => { + // No Firefox on this "machine": the derived UA is covered below. + setFirefoxUserAgentForTests(null); + t.after(() => setFirefoxUserAgentForTests(undefined)); const args = channelExtraArgs( cfg({ url: "https://rumble.com/c/x", @@ -216,3 +222,96 @@ test("a video's own URL picks the platform args when the channel names none or a assert.equal(configForVideoUrl(yt, "https://www.youtube.com/watch?v=abc"), yt); assert.equal(configForVideoUrl(yt, "https://example.com/v.mp4"), yt); }); + +// ── the derived Firefox user agent (lib/browserUserAgent-server.ts) ────────── + +const FF = "Mozilla/5.0 (X11; Linux x86_64; rv:158.0) Gecko/20100101 Firefox/158.0"; +const PINNED = [ + "--impersonate", + "firefox", + "--user-agent", + "Mozilla/5.0 (X11; Linux x86_64; rv:150.0) Gecko/20100101 Firefox/150.0", +]; + +function withFirefox(t: { after: (fn: () => void) => void }, ua: string | null = FF) { + setFirefoxUserAgentForTests(ua); + t.after(() => setFirefoxUserAgentForTests(undefined)); +} + +test("Firefox cookies and no pin: the derived UA is appended, last", (t) => { + withFirefox(t); + const args = channelExtraArgs( + cfg({ url: "https://rumble.com/c/x", ytdlpExtraArgs: ["--impersonate", "firefox"] }), + "firefox", + 1, + ); + assert.deepEqual(args, [ + "--cookies-from-browser", "firefox", + "--impersonate", "chrome", "--sleep-requests", "1", + "--impersonate", "firefox", + "--user-agent", FF, + ]); +}); + +test("Firefox cookies without a Firefox impersonation still get the UA (the clearance is the cookie's)", (t) => { + withFirefox(t); + const args = channelExtraArgs(cfg({ url: "https://odysee.com/@x" }), "firefox:/data/ff", 1); + assert.deepEqual(args.slice(-2), ["--user-agent", FF]); +}); + +test("--impersonate firefox alone (no cookies) gets the UA too", (t) => { + withFirefox(t); + const args = channelExtraArgs( + cfg({ url: "https://rumble.com/c/x", ytdlpExtraArgs: ["--impersonate", "firefox-135"] }), + undefined, + 1, + ); + assert.deepEqual(args.slice(-2), ["--user-agent", FF]); +}); + +test("a pinned --user-agent wins: nothing is added", (t) => { + withFirefox(t); + const args = channelExtraArgs(cfg({ url: "https://rumble.com/c/x", ytdlpExtraArgs: PINNED }), "firefox", 1); + assert.equal(args.filter((a) => a === "--user-agent").length, 1); + assert.equal(args[args.length - 1], PINNED[3]); + for (const pin of [["--user-agent=X"], ["--add-headers", "User-Agent: X"], ["--add-headers=user-agent:X"]]) { + assert.ok(hasUserAgentArg(pin), pin.join(" ")); + assert.deepEqual( + withBrowserUserAgent(["--cookies-from-browser", "firefox", ...pin], "rumble", () => FF), + ["--cookies-from-browser", "firefox", ...pin], + ); + } + assert.equal(hasUserAgentArg(["--add-headers", "Referer: x"]), false); +}); + +test("not added: other browsers' cookies, a cookies.txt, no cookies, YouTube, or no Firefox here", (t) => { + withFirefox(t); + const rumble = cfg({ url: "https://rumble.com/c/x" }); + // Rumble's own impersonation is Chrome's: without Firefox's cookies, no UA. + for (const cookies of ["chrome", "chromium:Default", "file:/tmp/cookies.txt", undefined]) { + assert.ok(!channelExtraArgs(rumble, cookies, 1).includes("--user-agent"), String(cookies)); + } + // YouTube keeps yt-dlp's default even with Firefox's cookies. + assert.deepEqual(channelExtraArgs(cfg({ url: "https://www.youtube.com/@x" }), "firefox", 1), [ + "--cookies-from-browser", "firefox", "--sleep-requests", "1", + ]); + // A video on another platform takes that platform's rule (configForVideoUrl). + const yt = cfg({ url: "https://www.youtube.com/@x" }); + assert.ok( + channelExtraArgs(configForVideoUrl(yt, "https://rumble.com/v1-x.html"), "firefox", 1).includes("--user-agent"), + ); + // No Firefox on this machine (a container): nothing added. + setFirefoxUserAgentForTests(null); + assert.ok(!channelExtraArgs(rumble, "firefox", 1).includes("--user-agent")); +}); + +test("the UA is derived for the cookie spec's profile; args after -- are not options", () => { + const asked: (string | undefined)[] = []; + const ua = (spec: string | undefined) => (asked.push(spec), FF); + withBrowserUserAgent(["--cookies-from-browser", "firefox:work::Personal"], "rumble", ua); + withBrowserUserAgent(["--impersonate", "firefox"], "rumble", ua); + assert.deepEqual(withBrowserUserAgent(["--", "--cookies-from-browser", "firefox"], "rumble", ua), [ + "--", "--cookies-from-browser", "firefox", + ]); + assert.deepEqual(asked, ["firefox:work::Personal", undefined]); +}); diff --git a/common/ytdlp/channelArgs.ts b/common/ytdlp/channelArgs.ts @@ -22,11 +22,18 @@ // `livePlatformPaceSeconds`, so EVERY spawn against the platform — listing, // prefetch, primary, availability, metadata scan, clip — slows down together. // The channel's own args still come last and win. +// +// THE FIREFOX USER AGENT IS DERIVED (withBrowserUserAgent, below). A spawn that +// reads Firefox's cookies or impersonates Firefox gets `--user-agent` with the +// UA of the Firefox on this machine (lib/browserUserAgent-server.ts), so a +// Cloudflare clearance earned in that browser is honoured and a Firefox update +// needs no config edit. A `--user-agent` in the channel's own args still wins. import type { ChannelConfig } from "../lib/channelConfig"; import { cookieArgs } from "../lib/cookiePolicy"; import { detectPlatform, type Platform } from "../lib/platform"; import { livePlatformPaceSeconds } from "../jobs/autoQueueState"; +import { firefoxUserAgent, parseCookieBrowserSpec } from "../lib/browserUserAgent-server"; // The platform args table lives in `platformArgs.mjs` (plain JS so umtool's // `.mjs` scripts can import the same copy); re-exported here for TS callers. @@ -106,5 +113,66 @@ export function channelExtraArgs( args.push(...cookieArgs(cookies)); args.push(...withSleepRequests(platformArgs(channelPlatform(config)), paceSeconds)); if (config.ytdlpExtraArgs?.length) args.push(...config.ytdlpExtraArgs); - return args; + return withBrowserUserAgent(args, channelPlatform(config)); +} + +// The value of a yt-dlp option in `args` — the LAST one (yt-dlp is +// last-flag-wins), in either spelling (`--opt v` / `--opt=v`). +function lastOptionValue(args: readonly string[], opt: string): string | undefined { + let v: string | undefined; + for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a === "--") break; + if (a === opt && i + 1 < args.length) v = args[++i]; + else if (a.startsWith(`${opt}=`)) v = a.slice(opt.length + 1); + } + return v; +} + +// Whether `args` already set the User-Agent: `--user-agent`, or an +// `--add-headers "User-Agent: …"` (yt-dlp's other spelling of it). +export function hasUserAgentArg(args: readonly string[]): boolean { + for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a === "--") break; + if (a === "--user-agent" || a.startsWith("--user-agent=")) return true; + const header = + a === "--add-headers" || a === "--add-header" + ? args[i + 1] + : /^--add-headers?=/.test(a) + ? a.slice(a.indexOf("=") + 1) + : undefined; + if (header !== undefined && /^\s*user-agent\s*:/i.test(header)) return true; + } + return false; +} + +// `args` with `--user-agent <the Firefox on this machine>` appended when the +// spawn reads Firefox's cookies (`--cookies-from-browser firefox[…]`) or +// impersonates Firefox (`--impersonate firefox[…]`) and nothing in `args` sets +// the User-Agent already — a channel's own `--user-agent` pin still wins. +// Unchanged when there is no Firefox here (the UA is null: a container, a +// server). +// +// Not for YouTube: no Cloudflare clearance to match there, and its extractor +// sends per-client user agents of its own; a Firefox UA was never pinned on a +// YouTube channel, so one reading Firefox's cookies keeps yt-dlp's default. +export function withBrowserUserAgent( + args: readonly string[], + platform: Platform | null | undefined, + // The UA for the cookie spec in `args`; default: derived. Tests pass it. + userAgentFor: (cookieSpec: string | undefined) => string | null = firefoxUserAgent, +): string[] { + const out = [...args]; + if (platform === "youtube" || hasUserAgentArg(out)) return out; + const cookieSpec = lastOptionValue(out, "--cookies-from-browser"); + const firefoxCookies = parseCookieBrowserSpec(cookieSpec)?.browser === "firefox"; + const impersonate = lastOptionValue(out, "--impersonate")?.trim().toLowerCase() ?? ""; + if (!firefoxCookies && !impersonate.startsWith("firefox")) return out; + const ua = userAgentFor(firefoxCookies ? cookieSpec : undefined); + if (!ua) return out; + // Before a `--` (what follows it is the URL, not options), else last. + const end = out.indexOf("--"); + out.splice(end < 0 ? out.length : end, 0, "--user-agent", ua); + return out; } diff --git a/common/ytdlp/fetchWindowManaged.ts b/common/ytdlp/fetchWindowManaged.ts @@ -57,6 +57,7 @@ import { type StoredMediaUrl, type StoredUrlWhy, } from "../lib/storedMediaUrl"; +import { storedMediaUserAgent } from "../lib/storedMediaUrl-server"; import { newStoredPageSession, openPlayerPage, @@ -221,8 +222,9 @@ class MalformedWindowError extends Error {} // ffmpeg's argv for a window cut from a stored media URL (see fetchWindowOnce): the player's // headers, an input seek so only the window's bytes are fetched, a frame-accurate re-encode // (as --force-keyframes-at-cuts) capped at the clip height, faststart mp4. -// The constant lives in lib/storedMediaUrl.ts (the whole-file download reads with it too). -export { STORED_MEDIA_USER_AGENT }; +// The user agent is storedMediaUserAgent() (lib/storedMediaUrl-server.ts: this machine's +// Firefox, else STORED_MEDIA_USER_AGENT) — the whole-file download reads with it too. +export { STORED_MEDIA_USER_AGENT, storedMediaUserAgent }; export function storedMediaFfmpegArgs( stored: Pick<StoredMediaUrl, "url" | "referer">, @@ -234,7 +236,7 @@ export function storedMediaFfmpegArgs( const origin = new URL(stored.referer).origin; return [ "-nostdin", "-hide_banner", "-v", "error", "-y", - "-user_agent", STORED_MEDIA_USER_AGENT, + "-user_agent", storedMediaUserAgent(), "-headers", `Referer: ${stored.referer}\r\nOrigin: ${origin}\r\n`, "-ss", from.toFixed(2), "-i", stored.url, diff --git a/common/ytdlp/storedUrlDownload.test.ts b/common/ytdlp/storedUrlDownload.test.ts @@ -12,7 +12,8 @@ import { corruptBytes, hasFfmpeg, makeToneFile } from "../testing/audio/corruptA import { startFakeRangedCdn } from "../testing/web/fakeRangedCdn.mjs"; import type { ChannelConfig } from "../lib/channelConfig"; import type { Paths } from "../lib/paths"; -import { storedMediaUrlFromInfo, STORED_MEDIA_USER_AGENT } from "../lib/storedMediaUrl"; +import { storedMediaUrlFromInfo } from "../lib/storedMediaUrl"; +import { storedMediaUserAgent } from "../lib/storedMediaUrl-server"; import { STORED_URL_DROP_PAUSE_MS, STORED_URL_MAX_DROPS, storedContainerExt, storedPartNames, storedUrlDownload } from "./storedUrlDownload"; const FF = hasFfmpeg(); @@ -88,7 +89,7 @@ test("the whole file comes down in ranged reads with the player's headers, then assert.match(q.range ?? "", new RegExp(`^bytes=${expect}-`)); assert.equal(q.referer, "https://odysee.com/"); assert.equal(q.origin, "https://odysee.com"); - assert.equal(q.ua, STORED_MEDIA_USER_AGENT); + assert.equal(q.ua, storedMediaUserAgent()); expect += q.bytes; } const entries = (await readdir(videoDir)).sort(); diff --git a/common/ytdlp/storedUrlDownload.ts b/common/ytdlp/storedUrlDownload.ts @@ -56,6 +56,7 @@ import { isRealAudioFile } from "../lib/mediaFiles"; import { removeMediaFile } from "../lib/mediaTier-server"; import type { Paths } from "../lib/paths"; import { storedMediaHeaders, type StoredMediaUrl } from "../lib/storedMediaUrl"; +import { storedMediaUserAgent } from "../lib/storedMediaUrl-server"; import { transcodeAudio } from "../controller/transcode"; import { DLOM_PROBE_MARKER, DOWNLOAD_PROGRESS_MARKER } from "../jobs/progressParsers"; import { resolveKnobs, type CheckpointRecord, type Knobs } from "./audioCheckedDownload"; @@ -267,7 +268,7 @@ export async function storedUrlDownload( const partFile = path.join(videoDir, names.part); const stateFile = path.join(videoDir, names.state); const containerFile = path.join(videoDir, names.container); - const headers = storedMediaHeaders(stored); + const headers = storedMediaHeaders(stored, storedMediaUserAgent()); const checkpoints: CheckpointRecord[] = []; let rollbacks = 0; diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -6555,6 +6555,16 @@ Line numbers are `plans/FACTS.md` lines at `e172749b`, before this record's in-p (runYtdlp), the metadata scan and `checkAvailability` all delegate to it; `probeChannelMeta` and the no-config availability path call `platformArgs(detectPlatform(url))`. The table is code; there is no setting. +- **The Firefox User-Agent is derived, not pinned (2026-10-31).** `channelExtraArgs` ends with + `withBrowserUserAgent(args, platform)` (channelArgs.ts): `--cookies-from-browser firefox[…]` or + `--impersonate firefox[…]`, no `--user-agent` / `--add-headers User-Agent:` already, platform not + `youtube` → `--user-agent <firefoxUserAgent(spec)>` appended. The UA comes from + `lib/browserUserAgent-server.ts`: the profile yt-dlp reads (named, else newest `cookies.sqlite` + by mtime, else installs.ini/profiles.ini default) → `compatibility.ini` `LastVersion`, else + `firefox --version`, else `FALLBACK_FIREFOX_VERSION` (logged) when a profile exists, else null + (no flag). The no-config availability and recheck-service paths wrap their argv in it too. + Non-yt-dlp users of the same UA: `liveFetchUserAgent()` (recordLive path B), + `webUserAgent()` (web pacer), `storedMediaUserAgent()` (stored-URL reads), each with a fixed fallback. - **A 429 mid-sweep is "incomplete".** `EnumerationIncompleteError` `runYtdlp.ts:329` (`platform, pagesReached, count`), `lastListingPage` :353 (last `Downloading page N` — the real wording is `[RumbleChannel] TheQuartering: Downloading page 155`). `syncFullSweep` catches it @@ -10162,8 +10172,9 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri - **`ytdlp/storedUrlDownload.ts`** `storedUrlDownload({paths, videoDir, stored, channelConfig, audioFormat, audioCheck, onLog, signal, deps?})`: sequential `Range: bytes=<offset>-<offset+chunk-1>` GETs (`STORED_URL_CHUNK_BYTES` = 8 MiB) - of `stored.url` with `storedMediaHeaders(stored)` (lib/storedMediaUrl.ts: `User-Agent` = `STORED_MEDIA_USER_AGENT`, - which moved there from fetchWindowManaged.ts and is re-exported by it; the pinned `Referer`; its `Origin`; + of `stored.url` with `storedMediaHeaders(stored, storedMediaUserAgent())` (lib/storedMediaUrl.ts; `User-Agent` = + this machine's Firefox, derived by lib/browserUserAgent-server.ts, else the fallback `STORED_MEDIA_USER_AGENT` + (Chrome 141), which moved there from fetchWindowManaged.ts and is re-exported by it; the pinned `Referer`; its `Origin`; `Accept: */*`). No cookies, no yt-dlp. 206 + `Content-Range` (the start must equal the offset); 200 = the CDN ignored the range, read as the whole file from 0; 416 = past the end; **429 and 403 → `rate-limited`** (partial kept); 404/410/other → `http-error`; a thrown fetch or an empty body → `network`.