// 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:`), 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_/`, 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 `.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> { const out: Record> = {}; 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:` // (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(); 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; }