@zfadhli/tokrec-cli 0.18.2 → 0.18.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -83,9 +83,10 @@ TikTok only serves some streams to logged-in sessions.
83
83
  - **Firefox (fallback)** — with no `cookies.json`, `tokrec` reads `sessionid_ss`
84
84
  and the Slardar WAF cookie from Firefox's cookie store when it exists.
85
85
 
86
- Age-restricted lives need an account that is allowed to view them: a session
87
- refused with `4003110` is the account's answer, so switching stores or accounts
88
- is the fix, not a code change.
86
+ A live that is gated for your session answers `4003110` instead of the room, so
87
+ switching accounts is the fix, not a code change. Reading Firefox's store works
88
+ while the browser is running — `tokrec` snapshots `cookies.sqlite` with its
89
+ `-wal` and opens the copy.
89
90
 
90
91
  ## Links
91
92
 
package/dist/bin.mjs CHANGED
@@ -99,7 +99,7 @@ async function main() {
99
99
  const config = result.config;
100
100
  const resolved = resolveCookies(config.cookiesPath);
101
101
  config.cookies = resolved?.cookies;
102
- const store = resolved?.source === "Firefox" ? "the Firefox session" : resolved?.path ?? "no cookie store";
102
+ const store = resolved?.source === "Firefox" ? "the Firefox session" : resolved?.path;
103
103
  config.logConsole = false;
104
104
  const display = createDisplay();
105
105
  if (resolved) {
package/dist/bin.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"bin.mjs","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env bun\n/**\n * Entry point — parses CLI args, creates the recorder, and handles signals.\n * The record flow's output wiring lives in `ui.attachDisplay`.\n */\n\nimport { existsSync, writeFileSync } from \"node:fs\"\nimport { join } from \"node:path\"\nimport type { RecorderConfig } from \"@zfadhli/tokrec\"\nimport { createRecorder, splitCookies, TikTokError } from \"@zfadhli/tokrec\"\nimport * as color from \"yoctocolors\"\nimport { extractTikTokCookiesFromFirefox, loadCookiesFile, resolveCookies } from \"./browser-cookies\"\nimport { type CLIResult, parseArgs } from \"./cli\"\nimport { tmuxStart, tmuxStatus, tmuxStop } from \"./tmux\"\nimport { attachDisplay, createDisplay } from \"./ui\"\n\nasync function main(): Promise<void> {\n let result: CLIResult\n\n try {\n result = parseArgs()\n } catch (err) {\n if (err instanceof TikTokError && err.code === \"config-error\") {\n console.error(`${color.red(\"Error:\")} ${err.message}`)\n process.exit(1)\n }\n throw err\n }\n\n // Handle tmux subcommands\n if (result.command === \"start\") {\n // Extract user from args to build session name\n const userMatch = result.args.find((_, i, a) => a[i - 1] === \"--user\" || a[i - 1] === \"-u\")\n if (!userMatch) {\n console.error(`${color.red(\"Error:\")} --user is required for \"start\" command`)\n process.exit(1)\n }\n const cmd = `tokrec ${result.args.join(\" \")}`\n try {\n await tmuxStart(userMatch, cmd)\n console.log(`${color.green(\"✓\")} Session \"tokrec-${userMatch}\" started in background`)\n console.log(` tmux attach -t tokrec-${userMatch} — view live output`)\n console.log(` tokrec stop -u ${userMatch} — stop recording`)\n } catch (err) {\n console.error(`${color.red(\"Error:\")} ${err instanceof Error ? err.message : String(err)}`)\n process.exit(1)\n }\n return\n }\n\n if (result.command === \"stop\") {\n try {\n await tmuxStop(result.user)\n if (result.user) {\n console.log(`${color.green(\"✓\")} Session \"tokrec-${result.user}\" stopped`)\n } else {\n console.log(`${color.green(\"✓\")} All tokrec sessions stopped`)\n }\n } catch (err) {\n console.error(`${color.red(\"Error:\")} ${err instanceof Error ? err.message : String(err)}`)\n process.exit(1)\n }\n return\n }\n\n if (result.command === \"status\") {\n const sessions = await tmuxStatus(result.user)\n if (sessions.length === 0) {\n console.log(\n `${color.gray(\"○\")} No active session${result.user ? ` for \"${result.user}\"` : \"\"}`,\n )\n } else {\n for (const s of sessions) {\n console.log(`${color.green(\"●\")} tokrec-${s.user}`)\n console.log(` tmux attach -t ${s.session} — view live output`)\n }\n }\n return\n }\n\n if (result.command === \"setup\") {\n // 1. Check cookies.json — the file the recorder prefers\n const cookiesPath = join(process.cwd(), \"cookies.json\")\n if (existsSync(cookiesPath)) {\n const fromFile = loadCookiesFile(cookiesPath)\n if (fromFile) {\n const names = Object.keys(fromFile)\n const detail = names.length > 1 ? ` (${names.length} cookies)` : \"\"\n console.log(`${color.green(\"✓\")} cookies.json found at ./cookies.json${detail}`)\n return\n }\n }\n\n // 2. Check Firefox cookies\n const firefoxCookies = extractTikTokCookiesFromFirefox()\n if (firefoxCookies) {\n const names = Object.keys(firefoxCookies)\n const detail = names.length > 1 ? ` (${names.length} cookies)` : \"\"\n console.log(`${color.green(\"✓\")} Firefox cookies detected${detail}`)\n console.log(` No setup needed — tokrec falls back to Firefox cookies.`)\n return\n }\n\n // 3. No cookies found — interactive setup\n console.log(`${color.yellow(\"⚠\")} No TikTok cookies found.`)\n console.log()\n console.log(`You need a valid sessionid_ss cookie to bypass TikTok's WAF.`)\n console.log(`Either log in to TikTok in Firefox (auto-detected), or enter manually:`)\n console.log()\n\n const sessionid = prompt(\" sessionid_ss cookie value:\")\n if (!sessionid || sessionid.trim().length === 0) {\n console.log(`${color.red(\"✗\")} No cookie provided. Setup cancelled.`)\n return\n }\n\n writeFileSync(cookiesPath, `${JSON.stringify({ sessionid_ss: sessionid.trim() }, null, 2)}\\n`)\n console.log()\n console.log(`${color.green(\"✓\")} cookies.json created at ./cookies.json`)\n console.log(` You can now run: tokrec -u <username>`)\n return\n }\n\n // Record command — full recorder flow\n const config: RecorderConfig = result.config\n\n // Load cookies: `-c` wins, then ./cookies.json, then Firefox\n const resolved = resolveCookies(config.cookiesPath)\n config.cookies = resolved?.cookies\n // Named in the restricted verdict: the account that was refused is the one thing\n // the operator has to change, and which store it came from is not guessable.\n const store =\n resolved?.source === \"Firefox\" ? \"the Firefox session\" : (resolved?.path ?? \"no cookie store\")\n\n // Suppress internal logger's console output — the Display owns the terminal\n config.logConsole = false\n\n // Beautiful terminal display\n const display = createDisplay()\n\n if (resolved) {\n const loaded = resolved.cookies\n // The recorder never sends these: a stale value makes a live room look private.\n const { stale } = splitCookies(loaded)\n if (stale.length > 0) {\n display.showWarning(\n `Ignoring ${stale.join(\" and \")} — TikTok computes those per session, and a stale value makes a live room look private`,\n )\n }\n const names = Object.keys(loaded)\n const detail = names.length > 1 ? ` (${names.length - stale.length} sent)` : \"\"\n display.showInfo(`${resolved.source} cookies loaded${detail}`)\n } else {\n display.showWarning(\n \"No TikTok cookies found — log in at tiktok.com in Firefox or create cookies.json\",\n )\n }\n\n const recorder = createRecorder(config)\n attachDisplay(display, recorder, config.user, store)\n\n // Signal handling\n let stopping = false\n const handleSignal = async () => {\n if (stopping) return // ignore duplicate signals (e.g. SIGINT + SIGTERM from one Ctrl-C)\n stopping = true\n // Remove signal handlers so they don't accumulate if main() is called again\n process.off(\"SIGINT\", handleSignal)\n process.off(\"SIGTERM\", handleSignal)\n process.off(\"SIGHUP\", handleSignal)\n display.showInfo(\"Shutting down gracefully...\")\n await recorder.stop()\n display.stop()\n process.exit(0)\n }\n\n process.on(\"SIGINT\", handleSignal)\n process.on(\"SIGTERM\", handleSignal)\n process.on(\"SIGHUP\", handleSignal)\n\n // Show initial status and start the recorder\n display.pollingStarted(config.interval ?? 3)\n try {\n await recorder.start()\n } catch (err) {\n if (err instanceof TikTokError) {\n display.showError(`[${err.code}] ${err.message}`)\n } else {\n display.showError(`Unexpected error: ${err instanceof Error ? err.message : String(err)}`)\n }\n process.off(\"SIGINT\", handleSignal)\n process.off(\"SIGTERM\", handleSignal)\n process.off(\"SIGHUP\", handleSignal)\n await recorder.stop()\n display.stop()\n process.exit(1)\n }\n}\n\nmain().catch((err) => {\n console.error(\"Fatal:\", err instanceof Error ? err.message : String(err))\n process.exit(1)\n})\n"],"mappings":";;;;;;;;;;;;;;AAgBA,eAAe,OAAsB;CACnC,IAAI;CAEJ,IAAI;EACF,SAAS,UAAU;CACrB,SAAS,KAAK;EACZ,IAAI,eAAe,eAAe,IAAI,SAAS,gBAAgB;GAC7D,QAAQ,MAAM,GAAG,MAAM,IAAI,QAAQ,EAAE,GAAG,IAAI,SAAS;GACrD,QAAQ,KAAK,CAAC;EACh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D,QAAQ,UAAU,qBAAqB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,GAAG;EAE3F,QAAQ,IAAI,UAAU,YAAY;EAClC,QAAQ,IAAI,WAAW,YAAY;EACnC,QAAQ,IAAI,UAAU,YAAY;EAClC,MAAM,SAAS,KAAK;EACpB,QAAQ,KAAK;EACb,QAAQ,KAAK,CAAC;CAChB;AACF;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CACpB,QAAQ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;CACxE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"bin.mjs","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env bun\n/**\n * Entry point — parses CLI args, creates the recorder, and handles signals.\n * The record flow's output wiring lives in `ui.attachDisplay`.\n */\n\nimport { existsSync, writeFileSync } from \"node:fs\"\nimport { join } from \"node:path\"\nimport type { RecorderConfig } from \"@zfadhli/tokrec\"\nimport { createRecorder, splitCookies, TikTokError } from \"@zfadhli/tokrec\"\nimport * as color from \"yoctocolors\"\nimport { extractTikTokCookiesFromFirefox, loadCookiesFile, resolveCookies } from \"./browser-cookies\"\nimport { type CLIResult, parseArgs } from \"./cli\"\nimport { tmuxStart, tmuxStatus, tmuxStop } from \"./tmux\"\nimport { attachDisplay, createDisplay } from \"./ui\"\n\nasync function main(): Promise<void> {\n let result: CLIResult\n\n try {\n result = parseArgs()\n } catch (err) {\n if (err instanceof TikTokError && err.code === \"config-error\") {\n console.error(`${color.red(\"Error:\")} ${err.message}`)\n process.exit(1)\n }\n throw err\n }\n\n // Handle tmux subcommands\n if (result.command === \"start\") {\n // Extract user from args to build session name\n const userMatch = result.args.find((_, i, a) => a[i - 1] === \"--user\" || a[i - 1] === \"-u\")\n if (!userMatch) {\n console.error(`${color.red(\"Error:\")} --user is required for \"start\" command`)\n process.exit(1)\n }\n const cmd = `tokrec ${result.args.join(\" \")}`\n try {\n await tmuxStart(userMatch, cmd)\n console.log(`${color.green(\"✓\")} Session \"tokrec-${userMatch}\" started in background`)\n console.log(` tmux attach -t tokrec-${userMatch} — view live output`)\n console.log(` tokrec stop -u ${userMatch} — stop recording`)\n } catch (err) {\n console.error(`${color.red(\"Error:\")} ${err instanceof Error ? err.message : String(err)}`)\n process.exit(1)\n }\n return\n }\n\n if (result.command === \"stop\") {\n try {\n await tmuxStop(result.user)\n if (result.user) {\n console.log(`${color.green(\"✓\")} Session \"tokrec-${result.user}\" stopped`)\n } else {\n console.log(`${color.green(\"✓\")} All tokrec sessions stopped`)\n }\n } catch (err) {\n console.error(`${color.red(\"Error:\")} ${err instanceof Error ? err.message : String(err)}`)\n process.exit(1)\n }\n return\n }\n\n if (result.command === \"status\") {\n const sessions = await tmuxStatus(result.user)\n if (sessions.length === 0) {\n console.log(\n `${color.gray(\"○\")} No active session${result.user ? ` for \"${result.user}\"` : \"\"}`,\n )\n } else {\n for (const s of sessions) {\n console.log(`${color.green(\"●\")} tokrec-${s.user}`)\n console.log(` tmux attach -t ${s.session} — view live output`)\n }\n }\n return\n }\n\n if (result.command === \"setup\") {\n // 1. Check cookies.json — the file the recorder prefers\n const cookiesPath = join(process.cwd(), \"cookies.json\")\n if (existsSync(cookiesPath)) {\n const fromFile = loadCookiesFile(cookiesPath)\n if (fromFile) {\n const names = Object.keys(fromFile)\n const detail = names.length > 1 ? ` (${names.length} cookies)` : \"\"\n console.log(`${color.green(\"✓\")} cookies.json found at ./cookies.json${detail}`)\n return\n }\n }\n\n // 2. Check Firefox cookies\n const firefoxCookies = extractTikTokCookiesFromFirefox()\n if (firefoxCookies) {\n const names = Object.keys(firefoxCookies)\n const detail = names.length > 1 ? ` (${names.length} cookies)` : \"\"\n console.log(`${color.green(\"✓\")} Firefox cookies detected${detail}`)\n console.log(` No setup needed — tokrec falls back to Firefox cookies.`)\n return\n }\n\n // 3. No cookies found — interactive setup\n console.log(`${color.yellow(\"⚠\")} No TikTok cookies found.`)\n console.log()\n console.log(`You need a valid sessionid_ss cookie to bypass TikTok's WAF.`)\n console.log(`Either log in to TikTok in Firefox (auto-detected), or enter manually:`)\n console.log()\n\n const sessionid = prompt(\" sessionid_ss cookie value:\")\n if (!sessionid || sessionid.trim().length === 0) {\n console.log(`${color.red(\"✗\")} No cookie provided. Setup cancelled.`)\n return\n }\n\n writeFileSync(cookiesPath, `${JSON.stringify({ sessionid_ss: sessionid.trim() }, null, 2)}\\n`)\n console.log()\n console.log(`${color.green(\"✓\")} cookies.json created at ./cookies.json`)\n console.log(` You can now run: tokrec -u <username>`)\n return\n }\n\n // Record command — full recorder flow\n const config: RecorderConfig = result.config\n\n // Load cookies: `-c` wins, then ./cookies.json, then Firefox\n const resolved = resolveCookies(config.cookiesPath)\n config.cookies = resolved?.cookies\n // Named in the restricted verdict: the account that was refused is the one thing\n // the operator has to change, and which store it came from is not guessable.\n // Undefined when no store had a session, so the display can leave the clause out.\n const store = resolved?.source === \"Firefox\" ? \"the Firefox session\" : resolved?.path\n\n // Suppress internal logger's console output — the Display owns the terminal\n config.logConsole = false\n\n // Beautiful terminal display\n const display = createDisplay()\n\n if (resolved) {\n const loaded = resolved.cookies\n // The recorder never sends these: a stale value makes a live room look private.\n const { stale } = splitCookies(loaded)\n if (stale.length > 0) {\n display.showWarning(\n `Ignoring ${stale.join(\" and \")} — TikTok computes those per session, and a stale value makes a live room look private`,\n )\n }\n const names = Object.keys(loaded)\n const detail = names.length > 1 ? ` (${names.length - stale.length} sent)` : \"\"\n display.showInfo(`${resolved.source} cookies loaded${detail}`)\n } else {\n display.showWarning(\n \"No TikTok cookies found — log in at tiktok.com in Firefox or create cookies.json\",\n )\n }\n\n const recorder = createRecorder(config)\n attachDisplay(display, recorder, config.user, store)\n\n // Signal handling\n let stopping = false\n const handleSignal = async () => {\n if (stopping) return // ignore duplicate signals (e.g. SIGINT + SIGTERM from one Ctrl-C)\n stopping = true\n // Remove signal handlers so they don't accumulate if main() is called again\n process.off(\"SIGINT\", handleSignal)\n process.off(\"SIGTERM\", handleSignal)\n process.off(\"SIGHUP\", handleSignal)\n display.showInfo(\"Shutting down gracefully...\")\n await recorder.stop()\n display.stop()\n process.exit(0)\n }\n\n process.on(\"SIGINT\", handleSignal)\n process.on(\"SIGTERM\", handleSignal)\n process.on(\"SIGHUP\", handleSignal)\n\n // Show initial status and start the recorder\n display.pollingStarted(config.interval ?? 3)\n try {\n await recorder.start()\n } catch (err) {\n if (err instanceof TikTokError) {\n display.showError(`[${err.code}] ${err.message}`)\n } else {\n display.showError(`Unexpected error: ${err instanceof Error ? err.message : String(err)}`)\n }\n process.off(\"SIGINT\", handleSignal)\n process.off(\"SIGTERM\", handleSignal)\n process.off(\"SIGHUP\", handleSignal)\n await recorder.stop()\n display.stop()\n process.exit(1)\n }\n}\n\nmain().catch((err) => {\n console.error(\"Fatal:\", err instanceof Error ? err.message : String(err))\n process.exit(1)\n})\n"],"mappings":";;;;;;;;;;;;;;AAgBA,eAAe,OAAsB;CACnC,IAAI;CAEJ,IAAI;EACF,SAAS,UAAU;CACrB,SAAS,KAAK;EACZ,IAAI,eAAe,eAAe,IAAI,SAAS,gBAAgB;GAC7D,QAAQ,MAAM,GAAG,MAAM,IAAI,QAAQ,EAAE,GAAG,IAAI,SAAS;GACrD,QAAQ,KAAK,CAAC;EAChB;EACA,MAAM;CACR;CAGA,IAAI,OAAO,YAAY,SAAS;EAE9B,MAAM,YAAY,OAAO,KAAK,MAAM,GAAG,GAAG,MAAM,EAAE,IAAI,OAAO,YAAY,EAAE,IAAI,OAAO,IAAI;EAC1F,IAAI,CAAC,WAAW;GACd,QAAQ,MAAM,GAAG,MAAM,IAAI,QAAQ,EAAE,wCAAwC;GAC7E,QAAQ,KAAK,CAAC;EAChB;EACA,MAAM,MAAM,UAAU,OAAO,KAAK,KAAK,GAAG;EAC1C,IAAI;GACF,MAAM,UAAU,WAAW,GAAG;GAC9B,QAAQ,IAAI,GAAG,MAAM,MAAM,GAAG,EAAE,mBAAmB,UAAU,wBAAwB;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:fs";
1
+ import { copyFileSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { Database } from "bun:sqlite";
4
- import { homedir } from "node:os";
4
+ import { homedir, tmpdir } from "node:os";
5
5
  //#region src/browser-cookies.ts
6
6
  /**
7
7
  * Browser cookie extraction — reads TikTok session cookies from cookies.json,
@@ -56,17 +56,37 @@ function resolveCookies(cookiesPath, readFirefox = extractTikTokCookiesFromFiref
56
56
  /**
57
57
  * Extract TikTok session cookies from Firefox's cookie store.
58
58
  *
59
- * Queries ALL cookies for TikTok domains from Firefox, including the
60
- * Slardar WAF challenge cookie which is needed to bypass bot detection.
61
- *
62
- * Returns null if Firefox isn't found, cookies can't be read, or no
63
- * sessionid_ss cookie exists (without which the session is useless).
59
+ * Returns all TikTok cookies, including the Slardar WAF challenge cookie, and
60
+ * null when Firefox isn't found or the store carries no `sessionid_ss`.
64
61
  */
65
62
  function extractTikTokCookiesFromFirefox() {
66
63
  const dbPath = findFirefoxCookieDb();
67
64
  if (!dbPath) return null;
65
+ return readTikTokCookies(dbPath);
66
+ }
67
+ /**
68
+ * Read TikTok cookies out of a `cookies.sqlite`, through a snapshot copy rather
69
+ * than the live file.
70
+ *
71
+ * Two measured reasons. Opening Firefox's database read-only fails with
72
+ * `disk I/O error` while the browser holds it. And a running browser keeps the
73
+ * schema together with the newest rows in an un-checkpointed `-wal`, so a copy
74
+ * of the main file alone answers `no such table: moz_cookies` — the `-wal` and
75
+ * `-shm` have to travel with it.
76
+ */
77
+ function readTikTokCookies(dbPath) {
78
+ let dir = null;
68
79
  try {
69
- const db = new Database(dbPath, { readonly: true });
80
+ dir = mkdtempSync(join(tmpdir(), "tokrec-firefox-"));
81
+ for (const suffix of [
82
+ "",
83
+ "-wal",
84
+ "-shm"
85
+ ]) {
86
+ const src = `${dbPath}${suffix}`;
87
+ if (existsSync(src)) copyFileSync(src, join(dir, `cookies.sqlite${suffix}`));
88
+ }
89
+ const db = new Database(join(dir, "cookies.sqlite"), { readonly: true });
70
90
  try {
71
91
  const rows = db.query(`SELECT name, value FROM moz_cookies
72
92
  WHERE host LIKE '%.tiktok.com' OR host LIKE '%.tiktokv.com'`).all();
@@ -79,6 +99,11 @@ function extractTikTokCookiesFromFirefox() {
79
99
  }
80
100
  } catch {
81
101
  return null;
102
+ } finally {
103
+ if (dir) rmSync(dir, {
104
+ recursive: true,
105
+ force: true
106
+ });
82
107
  }
83
108
  }
84
109
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"browser-cookies.mjs","names":[],"sources":["../src/browser-cookies.ts"],"sourcesContent":["/**\n * Browser cookie extraction — reads TikTok session cookies from cookies.json,\n * or from Firefox's cookie store via bun:sqlite (no external dependencies).\n */\n\nimport { Database } from \"bun:sqlite\"\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { join } from \"node:path\"\n\n/**\n * Load `{ sessionid_ss, ... }` from a cookies.json path (default\n * `./cookies.json`). Returns null when the file is missing, unparseable, or\n * carries no session cookie — the caller decides whether to warn or prompt.\n */\nexport function loadCookiesFile(cookiesPath?: string): Record<string, string> | null {\n const path = cookiesPath ?? join(process.cwd(), \"cookies.json\")\n if (!existsSync(path)) return null\n try {\n const data = JSON.parse(readFileSync(path, \"utf-8\")) as Record<string, string | undefined>\n if (data.sessionid_ss && data.sessionid_ss.length > 0) {\n return data as Record<string, string>\n }\n return null\n } catch {\n return null\n }\n}\n\n/** Where the session cookies came from. */\nexport interface ResolvedCookies {\n cookies: Record<string, string>\n source: \"Firefox\" | \"cookies.json\"\n path: string\n}\n\n/**\n * Resolve the session cookies: an explicit `-c` path wins, then `./cookies.json`,\n * then Firefox. The file comes before the browser store because a `cookies.json`\n * is a deliberate choice — the Firefox session may be a different TikTok account,\n * and only one of them may be eligible for a given room. An explicit `-c` path\n * never falls through to auto-detection.\n */\nexport function resolveCookies(\n cookiesPath?: string,\n readFirefox: () => Record<string, string> | null = extractTikTokCookiesFromFirefox,\n): ResolvedCookies | null {\n if (cookiesPath) {\n const fromFile = loadCookiesFile(cookiesPath)\n return fromFile ? { cookies: fromFile, source: \"cookies.json\", path: cookiesPath } : null\n }\n const cwdJson = join(process.cwd(), \"cookies.json\")\n const fileCookies = loadCookiesFile(cwdJson)\n if (fileCookies) return { cookies: fileCookies, source: \"cookies.json\", path: cwdJson }\n const firefoxCookies = readFirefox()\n return firefoxCookies\n ? { cookies: firefoxCookies, source: \"Firefox\", path: \"Firefox profile\" }\n : null\n}\n\n/**\n * Extract TikTok session cookies from Firefox's cookie store.\n *\n * Queries ALL cookies for TikTok domains from Firefox, including the\n * Slardar WAF challenge cookie which is needed to bypass bot detection.\n *\n * Returns null if Firefox isn't found, cookies can't be read, or no\n * sessionid_ss cookie exists (without which the session is useless).\n */\nexport function extractTikTokCookiesFromFirefox(): Record<string, string> | null {\n const dbPath = findFirefoxCookieDb()\n if (!dbPath) return null\n\n try {\n const db = new Database(dbPath, { readonly: true })\n try {\n const rows = db\n .query(\n `SELECT name, value FROM moz_cookies\n WHERE host LIKE '%.tiktok.com' OR host LIKE '%.tiktokv.com'`,\n )\n .all() as Array<{ name: string; value: string }>\n\n // Require sessionid_ss — without it the session is useless\n const hasSession = rows.some((r) => r.name === \"sessionid_ss\")\n if (!hasSession) return null\n\n const cookies: Record<string, string> = {}\n for (const row of rows) {\n cookies[row.name] = row.value\n }\n return cookies\n } finally {\n db.close()\n }\n } catch {\n return null\n }\n}\n\n/**\n * Locate the Firefox cookies.sqlite by scanning profile directories.\n *\n * Strategy:\n * 1. Check ~/.mozilla/firefox/ for profiles.ini and parse the default profile.\n * 2. Fall back to scanning directory entries that look like Firefox profiles\n * (contain a cookies.sqlite file).\n */\n/** @public Exported for testing */\nexport function findFirefoxCookieDb(): string | null {\n const firefoxDir = join(homedir(), \".mozilla\", \"firefox\")\n if (!existsSync(firefoxDir)) return null\n\n // Try profiles.ini first for a reliable default-profile path\n const iniPath = join(firefoxDir, \"profiles.ini\")\n if (existsSync(iniPath)) {\n try {\n const profilePath = parseFirefoxProfilesIni(iniPath, firefoxDir)\n if (profilePath) {\n const dbPath = join(profilePath, \"cookies.sqlite\")\n if (existsSync(dbPath)) return dbPath\n }\n } catch {\n // fall through to directory scan\n }\n }\n\n // Fallback: scan for any directory containing cookies.sqlite\n const entries = readdirSync(firefoxDir, { withFileTypes: true })\n for (const entry of entries) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const dbPath = join(firefoxDir, entry.name, \"cookies.sqlite\")\n if (existsSync(dbPath)) return dbPath\n }\n\n return null\n}\n\n/**\n * Parse Firefox's profiles.ini to find the default profile path.\n *\n * The INI format looks like:\n * [Profile0]\n * Name=default\n * IsRelative=1\n * Path=1pese0rl.default-release\n * Default=1\n */\n/** @public Exported for testing */\nexport function parseFirefoxProfilesIni(iniPath: string, firefoxDir: string): string | null {\n const text = readFileSync(iniPath, \"utf-8\")\n\n let defaultPath: string | null = null\n let isRelative = true\n let inProfile = false\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim()\n\n // Section header\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n if (inProfile && defaultPath) break // found it\n inProfile = trimmed.toLowerCase().startsWith(\"[profile\")\n if (inProfile) {\n defaultPath = null\n isRelative = true\n }\n continue\n }\n\n if (!inProfile) continue\n\n const lower = trimmed.toLowerCase()\n if (lower.startsWith(\"path=\")) {\n defaultPath = trimmed.slice(5)\n } else if (lower.startsWith(\"isrelative=\")) {\n isRelative = trimmed.slice(11).trim() !== \"0\"\n } else if (lower.startsWith(\"default=\")) {\n if (trimmed.slice(8).trim() !== \"1\") {\n // Not the default profile — skip\n inProfile = false\n defaultPath = null\n }\n }\n }\n\n if (!defaultPath) return null\n return isRelative ? join(firefoxDir, defaultPath) : defaultPath\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,SAAgB,gBAAgB,aAAqD;CACnF,MAAM,OAAO,eAAe,KAAK,QAAQ,IAAI,GAAG,cAAc;CAC9D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AO;CACzB,OAAO,aAAa,KAAK,YAAY,WAAW,IAAI;AACtD"}
1
+ {"version":3,"file":"browser-cookies.mjs","names":[],"sources":["../src/browser-cookies.ts"],"sourcesContent":["/**\n * Browser cookie extraction — reads TikTok session cookies from cookies.json,\n * or from Firefox's cookie store via bun:sqlite (no external dependencies).\n */\n\nimport { Database } from \"bun:sqlite\"\nimport { copyFileSync, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from \"node:fs\"\nimport { homedir, tmpdir } from \"node:os\"\nimport { join } from \"node:path\"\n\n/**\n * Load `{ sessionid_ss, ... }` from a cookies.json path (default\n * `./cookies.json`). Returns null when the file is missing, unparseable, or\n * carries no session cookie — the caller decides whether to warn or prompt.\n */\nexport function loadCookiesFile(cookiesPath?: string): Record<string, string> | null {\n const path = cookiesPath ?? join(process.cwd(), \"cookies.json\")\n if (!existsSync(path)) return null\n try {\n const data = JSON.parse(readFileSync(path, \"utf-8\")) as Record<string, string | undefined>\n if (data.sessionid_ss && data.sessionid_ss.length > 0) {\n return data as Record<string, string>\n }\n return null\n } catch {\n return null\n }\n}\n\n/** Where the session cookies came from. */\nexport interface ResolvedCookies {\n cookies: Record<string, string>\n source: \"Firefox\" | \"cookies.json\"\n path: string\n}\n\n/**\n * Resolve the session cookies: an explicit `-c` path wins, then `./cookies.json`,\n * then Firefox. The file comes before the browser store because a `cookies.json`\n * is a deliberate choice — the Firefox session may be a different TikTok account,\n * and only one of them may be eligible for a given room. An explicit `-c` path\n * never falls through to auto-detection.\n */\nexport function resolveCookies(\n cookiesPath?: string,\n readFirefox: () => Record<string, string> | null = extractTikTokCookiesFromFirefox,\n): ResolvedCookies | null {\n if (cookiesPath) {\n const fromFile = loadCookiesFile(cookiesPath)\n return fromFile ? { cookies: fromFile, source: \"cookies.json\", path: cookiesPath } : null\n }\n const cwdJson = join(process.cwd(), \"cookies.json\")\n const fileCookies = loadCookiesFile(cwdJson)\n if (fileCookies) return { cookies: fileCookies, source: \"cookies.json\", path: cwdJson }\n const firefoxCookies = readFirefox()\n return firefoxCookies\n ? { cookies: firefoxCookies, source: \"Firefox\", path: \"Firefox profile\" }\n : null\n}\n\n/**\n * Extract TikTok session cookies from Firefox's cookie store.\n *\n * Returns all TikTok cookies, including the Slardar WAF challenge cookie, and\n * null when Firefox isn't found or the store carries no `sessionid_ss`.\n */\nexport function extractTikTokCookiesFromFirefox(): Record<string, string> | null {\n const dbPath = findFirefoxCookieDb()\n if (!dbPath) return null\n return readTikTokCookies(dbPath)\n}\n\n/**\n * Read TikTok cookies out of a `cookies.sqlite`, through a snapshot copy rather\n * than the live file.\n *\n * Two measured reasons. Opening Firefox's database read-only fails with\n * `disk I/O error` while the browser holds it. And a running browser keeps the\n * schema together with the newest rows in an un-checkpointed `-wal`, so a copy\n * of the main file alone answers `no such table: moz_cookies` — the `-wal` and\n * `-shm` have to travel with it.\n */\nexport function readTikTokCookies(dbPath: string): Record<string, string> | null {\n let dir: string | null = null\n try {\n dir = mkdtempSync(join(tmpdir(), \"tokrec-firefox-\"))\n for (const suffix of [\"\", \"-wal\", \"-shm\"]) {\n const src = `${dbPath}${suffix}`\n if (existsSync(src)) copyFileSync(src, join(dir, `cookies.sqlite${suffix}`))\n }\n\n const db = new Database(join(dir, \"cookies.sqlite\"), { readonly: true })\n try {\n const rows = db\n .query(\n `SELECT name, value FROM moz_cookies\n WHERE host LIKE '%.tiktok.com' OR host LIKE '%.tiktokv.com'`,\n )\n .all() as Array<{ name: string; value: string }>\n\n // Require sessionid_ss — without it the session is useless\n if (!rows.some((r) => r.name === \"sessionid_ss\")) return null\n\n const cookies: Record<string, string> = {}\n for (const row of rows) {\n cookies[row.name] = row.value\n }\n return cookies\n } finally {\n db.close()\n }\n } catch {\n return null\n } finally {\n if (dir) rmSync(dir, { recursive: true, force: true })\n }\n}\n\n/**\n * Locate the Firefox cookies.sqlite by scanning profile directories.\n *\n * Strategy:\n * 1. Check ~/.mozilla/firefox/ for profiles.ini and parse the default profile.\n * 2. Fall back to scanning directory entries that look like Firefox profiles\n * (contain a cookies.sqlite file).\n */\n/** @public Exported for testing */\nexport function findFirefoxCookieDb(): string | null {\n const firefoxDir = join(homedir(), \".mozilla\", \"firefox\")\n if (!existsSync(firefoxDir)) return null\n\n // Try profiles.ini first for a reliable default-profile path\n const iniPath = join(firefoxDir, \"profiles.ini\")\n if (existsSync(iniPath)) {\n try {\n const profilePath = parseFirefoxProfilesIni(iniPath, firefoxDir)\n if (profilePath) {\n const dbPath = join(profilePath, \"cookies.sqlite\")\n if (existsSync(dbPath)) return dbPath\n }\n } catch {\n // fall through to directory scan\n }\n }\n\n // Fallback: scan for any directory containing cookies.sqlite\n const entries = readdirSync(firefoxDir, { withFileTypes: true })\n for (const entry of entries) {\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const dbPath = join(firefoxDir, entry.name, \"cookies.sqlite\")\n if (existsSync(dbPath)) return dbPath\n }\n\n return null\n}\n\n/**\n * Parse Firefox's profiles.ini to find the default profile path.\n *\n * The INI format looks like:\n * [Profile0]\n * Name=default\n * IsRelative=1\n * Path=1pese0rl.default-release\n * Default=1\n */\n/** @public Exported for testing */\nexport function parseFirefoxProfilesIni(iniPath: string, firefoxDir: string): string | null {\n const text = readFileSync(iniPath, \"utf-8\")\n\n let defaultPath: string | null = null\n let isRelative = true\n let inProfile = false\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim()\n\n // Section header\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n if (inProfile && defaultPath) break // found it\n inProfile = trimmed.toLowerCase().startsWith(\"[profile\")\n if (inProfile) {\n defaultPath = null\n isRelative = true\n }\n continue\n }\n\n if (!inProfile) continue\n\n const lower = trimmed.toLowerCase()\n if (lower.startsWith(\"path=\")) {\n defaultPath = trimmed.slice(5)\n } else if (lower.startsWith(\"isrelative=\")) {\n isRelative = trimmed.slice(11).trim() !== \"0\"\n } else if (lower.startsWith(\"default=\")) {\n if (trimmed.slice(8).trim() !== \"1\") {\n // Not the default profile — skip\n inProfile = false\n defaultPath = null\n }\n }\n }\n\n if (!defaultPath) return null\n return isRelative ? join(firefoxDir, defaultPath) : defaultPath\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,SAAgB,gBAAgB,aAAqD;CACnF,MAAM,OAAO,eAAe,KAAK,QAAQ,IAAI,GAAG,cAAc;CAC9D,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,IAAI;EACF,MAAM,OAAO,KAAK,MAAM,aAAa,MAAM,OAAO,CAAC;EACnD,IAAI,KAAK,gBAAgB,KAAK,aAAa,SAAS,GAClD,OAAO;EAET,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;AAgBA,SAAgB,eACd,aACA,cAAmD,iCAC3B;CACxB,IAAI,aAAa;EACf,MAAM,WAAW,gBAAgB,WAAW;EAC5C,OAAO,WAAW;GAAE,SAAS;GAAU,QAAQ;GAAgB,MAAM;EAAY,IAAI;CACvF;CACA,MAAM,UAAU,KAAK,QAAQ,IAAI,GAAG,cAAc;CAClD,MAAM,cAAc,gBAAgB,OAAO;CAC3C,IAAI,aAAa,OAAO;EAAE,SAAS;EAAa,QAAQ;EAAgB,MAAM;CAAQ;CACtF,MAAM,iBAAiB,YAAY;CACnC,OAAO,iBACH;EAAE,SAAS;EAAgB,QAAQ;EAAW,MAAM;CAAkB,IACtE;AACN;;;;;;;AAQA,SAAgB,kCAAiE;CAC/E,MAAM,SAAS,oBAAoB;CACnC,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO,kBAAkB,MAAM;AACjC;;;;;;;;;;;AAYA,SAAgB,kBAAkB,QAA+C;CAC/E,IAAI,MAAqB;CACzB,IAAI;EACF,MAAM,YAAY,KAAK,OAAO,GAAG,iBAAiB,CAAC;EACnD,KAAK,MAAM,UAAU;GAAC;GAAI;GAAQ;EAAM,GAAG;GACzC,MAAM,MAAM,GAAG,SAAS;GACxB,IAAI,WAAW,GAAG,GAAG,aAAa,KAAK,KAAK,KAAK,iBAAiB,Q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MAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;EACnC,MAAM,UAAU,KAAK,KAAK;EAG1B,IAAI,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,GAAG;GACpD,IAAI,aAAa,aAAa;GAC9B,YAAY,QAAQ,YAAY,CAAC,CAAC,WAAW,UAAU;GACvD,IAAI,WAAW;IACb,cAAc;IACd,aAAa;GACf;GACA;EACF;EAEA,IAAI,CAAC,WAAW;EAEhB,MAAM,QAAQ,QAAQ,YAAY;EAClC,IAAI,MAAM,WAAW,OAAO,GAC1B,cAAc,QAAQ,MAAM,CAAC;OACxB,IAAI,MAAM,WAAW,aAAa,GACvC,aAAa,QAAQ,MAAM,EAAE,CAAC,CAAC,KAAK,MAAM;OACrC,IAAI,MAAM,WAAW,UAAU;OAChC,QAAQ,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,KAAK;IAEnC,YAAY;IACZ,cAAc;GAChB;;CAEJ;CAEA,IAAI,CAAC,aAAa,OAAO;CACzB,OAAO,aAAa,KAAK,YAAY,WAAW,IAAI;AACtD"}
package/dist/package.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.18.2";
2
+ var version = "0.18.4";
3
3
  //#endregion
4
4
  export { version };
5
5
 
package/dist/ui.mjs CHANGED
@@ -71,10 +71,11 @@ function createDisplay() {
71
71
  offlineLineShown = false;
72
72
  process.stdout.write(`${tag.live}${color.bold(color.green(`@${user}`))} ${color.dim(`(room: ${color.bold(color.yellow(roomId))})`)}\n`);
73
73
  },
74
- userRestricted(user, store = "this session") {
74
+ userRestricted(user, store) {
75
75
  clearSpinner();
76
76
  offlineLineShown = false;
77
- process.stdout.write(`${tag.lock}${color.bold(color.yellow(`@${user}`))}${color.dim(` is live but this session is refused (age- or login-gated) \u2014 ${store} is not eligible; try another account with -c <cookies.json>`)}\n`);
77
+ const refused = store ? ` \u2014 ${store} is not eligible` : "";
78
+ process.stdout.write(`${tag.lock}${color.bold(color.yellow(`@${user}`))}${color.dim(` is live but room/info refused this session (status_code 4003110)${refused}; try another account with -c <cookies.json>`)}\n`);
78
79
  },
79
80
  userLiveNoStream(user, roomId) {
80
81
  clearSpinner();
package/dist/ui.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ui.mjs","names":[],"sources":["../src/ui.ts"],"sourcesContent":["/**\n * Terminal Display Manager — console output via yocto-spinner and yoctocolors.\n *\n * This module owns the terminal and should be the only thing writing to\n * stdout/stderr (the file logger handles persistent logs).\n */\n\nimport {\n bytesToHuman,\n formatDuration,\n isLiveReason,\n type RecorderController,\n relativeTime,\n} from \"@zfadhli/tokrec\"\nimport yoctoSpinner, { type Spinner } from \"yocto-spinner\"\nimport * as color from \"yoctocolors\"\n\n// ─── Tag helpers ──────────────────────────────────────────\nconst tag = {\n ok: color.bold(color.green(\"[OK] \")),\n done: color.bold(color.green(\"[DONE] \")),\n live: color.bold(color.green(\"[LIVE] \")),\n info: color.bold(color.blue(\"[INFO] \")),\n off: color.bold(color.blue(\"[OFF] \")),\n lock: color.bold(color.yellow(\"[LOCK] \")),\n warn: color.bold(color.yellow(\"[WARN] \")),\n err: color.bold(color.red(\"[ERR] \")),\n}\n\nexport interface Display {\n /** Called once when polling begins. */\n pollingStarted(intervalMinutes: number): void\n /** Spinner while checking if a user is live. */\n checkingUser(user: string): void\n /** User is offline (no active display). */\n userOffline(user: string): void\n /** User is still offline — updates the previous offline line with a timestamp. */\n userOfflineRepeat(user: string, lastCheck: string): void\n /** User is live! Clears the checking spinner. */\n userLive(user: string, roomId: string): void\n /** User is live but refused by the account gate — `store` names the cookie source used. */\n userRestricted(user: string, store?: string): void\n /** User is live but no stream URL was resolved. */\n userLiveNoStream(user: string, roomId: string): void\n\n /** Recording starts: spinner without filename (known only post-download). */\n startRecording(): void\n /** Recording finished successfully. Shows filename from the result. */\n finishRecording(filename: string, duration: number, size: string): void\n /** Recording encountered a non-fatal error. */\n recordingError(message: string): void\n\n /** FFmpeg segmenting starts. */\n startSegmenting(): void\n /** FFmpeg segmenting done. */\n segmentsCreated(count: number): void\n\n /** FFmpeg simple conversion starts (fallback path). */\n startConverting(): void\n /** Simple conversion done. */\n conversionDone(output: string): void\n\n /** Audio normalization starts (EBU R128 via peaknorm). */\n normalizeStart(): void\n /** Audio normalization progress update. */\n normalizeProgress(percent: number, phase: string): void\n /** Audio normalization completed successfully. */\n normalizeComplete(): void\n /** Audio normalization failed. */\n normalizeError(message: string): void\n\n /** Show version banner at startup. */\n showVersion(name: string, version: string): void\n\n /** General-purpose status helpers. */\n showError(message: string): void\n showInfo(message: string): void\n showWarning(message: string): void\n\n /** Stop all active spinners and clean up the terminal. */\n stop(): void\n}\n\nexport function createDisplay(): Display {\n // yocto-spinner with handleSignals off: bin.ts owns SIGINT/SIGTERM teardown.\n const stream = process.stdout\n // Mirrors yocto-spinner's internal isInteractive(); spinner.text writes a full\n // line when non-interactive, so per-tick updates must be skipped there.\n const animated = Boolean(stream.isTTY && process.env.TERM !== \"dumb\" && !(\"CI\" in process.env))\n const spin = (text: string): Spinner => yoctoSpinner({ text, stream, handleSignals: false })\n\n let activeSpinner: Spinner | null = null\n let offlineLineShown = false\n\n // Recording timer state\n let recordingStartTime: number | null = null\n let recordingTimer: ReturnType<typeof setInterval> | null = null\n\n /** Stop the currently active spinner (if any) without printing anything. */\n function clearSpinner(): void {\n if (recordingTimer) {\n clearInterval(recordingTimer)\n recordingTimer = null\n }\n if (activeSpinner?.isSpinning) {\n activeSpinner.stop()\n }\n activeSpinner = null\n }\n\n /** Stop the current spinner and print a one-liner with the given tag prefix. */\n function finalize(prefix: string, text: string): void {\n clearSpinner()\n process.stdout.write(`${prefix}${text}\\n`)\n }\n\n return {\n pollingStarted(intervalMinutes: number): void {\n finalize(\n tag.info,\n `${color.dim(\"Polling started (every \")}${color.bold(color.yellow(String(intervalMinutes)))}${color.dim(\" min)\")}`,\n )\n },\n\n checkingUser(user: string): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(`Checking @${user}...`))\n activeSpinner.start()\n },\n\n userOffline(user: string): void {\n finalize(tag.off, `${color.bold(color.yellow(`@${user}`))}${color.dim(\" is offline\")}`)\n offlineLineShown = true\n },\n\n userOfflineRepeat(user: string, lastCheck: string): void {\n clearSpinner()\n const text = `${tag.off}${color.bold(color.yellow(`@${user}`))}${color.dim(\" is offline\")} ${color.dim(`[last online: ${color.bold(color.yellow(lastCheck))}]`)}`\n if (offlineLineShown) {\n // Move cursor up one line and overwrite the previous offline message\n process.stdout.write(`\\x1b[1A\\r${text}\\x1b[K\\n`)\n } else {\n process.stdout.write(`${text}\\n`)\n offlineLineShown = true\n }\n },\n\n userLive(user: string, roomId: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(\n `${tag.live}${color.bold(color.green(`@${user}`))} ${color.dim(`(room: ${color.bold(color.yellow(roomId))})`)}\\n`,\n )\n },\n\n userRestricted(user: string, store = \"this session\"): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(\n `${tag.lock}${color.bold(color.yellow(`@${user}`))}${color.dim(` is live but this session is refused (age- or login-gated) \\u2014 ${store} is not eligible; try another account with -c <cookies.json>`)}\\n`,\n )\n },\n\n userLiveNoStream(user: string, roomId: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(\n `${tag.live}${color.bold(color.green(`@${user}`))} ${color.dim(`(room: ${color.bold(color.yellow(roomId))}) \\u2014 no stream URL found`)}\\n`,\n )\n },\n\n startRecording(): void {\n clearSpinner()\n recordingStartTime = Date.now()\n activeSpinner = spin(\n `${color.cyan(\"Recording...\")} ${color.dim(`[${color.bold(color.yellow(\"0s\"))}]`)}`,\n )\n activeSpinner.start()\n\n recordingTimer = setInterval(() => {\n if (!animated || !activeSpinner?.isSpinning || !recordingStartTime) return\n const elapsed = (Date.now() - recordingStartTime) / 1000\n activeSpinner.text = `${color.cyan(\"Recording...\")} ${color.dim(`[${color.bold(color.yellow(formatDuration(elapsed)))}]`)}`\n }, 1000)\n },\n\n finishRecording(filename: string, duration: number, size: string): void {\n finalize(\n tag.done,\n `${color.cyan(filename)}${color.dim(\" — \")}${color.bold(color.yellow(size))}${color.dim(` in ${color.bold(color.yellow(formatDuration(duration)))}`)}`,\n )\n },\n\n recordingError(message: string): void {\n finalize(tag.err, color.red(`Recording failed: ${message}`))\n },\n\n startSegmenting(): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(\"Segmenting...\"))\n activeSpinner.start()\n },\n\n segmentsCreated(count: number): void {\n finalize(\n tag.ok,\n `${color.dim(\"Created \")}${color.bold(color.yellow(String(count)))}${color.dim(` MP4 segment${count !== 1 ? \"s\" : \"\"}`)}`,\n )\n },\n\n startConverting(): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(\"Converting to MP4...\"))\n activeSpinner.start()\n },\n\n conversionDone(output: string): void {\n finalize(tag.done, `${color.cyan(output)}`)\n },\n\n normalizeStart(): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(\"Normalizing audio...\"))\n activeSpinner.start()\n },\n\n normalizeProgress(percent: number, phase: string): void {\n if (!animated || !activeSpinner?.isSpinning) return\n const label = phase === \"analyzing\" ? \"Analyzing\" : \"Normalizing\"\n activeSpinner.text = ` ${label}... ${color.bold(color.yellow(`${percent}%`))}`\n },\n\n normalizeComplete(): void {\n finalize(tag.ok, color.green(\"Audio normalized\"))\n },\n\n normalizeError(message: string): void {\n finalize(tag.err, color.red(`Normalization failed: ${message}`))\n },\n\n showVersion(name: string, version: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${color.dim(`${name} ${version}`)}\\n`)\n },\n\n showError(message: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${tag.err}${color.red(message)}\\n`)\n },\n\n showInfo(message: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${tag.info}${color.dim(message)}\\n`)\n },\n\n showWarning(message: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${tag.warn}${color.yellow(message)}\\n`)\n },\n\n stop(): void {\n clearSpinner()\n offlineLineShown = false\n },\n }\n}\n\n/**\n * Wire the recorder's four event channels to the terminal.\n *\n * Lives next to the display it drives: the mapping from recorder phase to\n * terminal line is presentation, so `bin.ts` should not carry it.\n */\nexport function attachDisplay(\n display: Display,\n recorder: Pick<RecorderController, \"on\">,\n user: string,\n store?: string,\n): void {\n let lastWasLive: boolean | null = null\n let firstOfflineTime = 0\n\n recorder.on(\"verdict\", (verdict) => {\n if (verdict.reason === \"restricted\") {\n display.userRestricted(user, store)\n } else if (verdict.reason === \"no-stream-url\") {\n display.userLiveNoStream(user, verdict.room?.id ?? \"?\")\n } else if (isLiveReason(verdict.reason)) {\n display.userLive(user, verdict.room?.id ?? \"?\")\n } else if (lastWasLive === null || lastWasLive === true) {\n display.userOffline(user)\n firstOfflineTime = Date.now()\n } else {\n display.userOfflineRepeat(user, relativeTime(Date.now() - firstOfflineTime))\n }\n lastWasLive = isLiveReason(verdict.reason)\n })\n\n recorder.on(\"record\", (event) => {\n switch (event.phase) {\n case \"start\":\n display.startRecording()\n break\n case \"download\": {\n const parsed = event.file.split(\"/\").pop() ?? event.file\n display.finishRecording(parsed, event.duration, bytesToHuman(event.size))\n break\n }\n case \"segment\":\n if (event.status === \"start\") display.startSegmenting()\n else display.segmentsCreated(event.segments)\n break\n case \"convert\":\n if (event.status === \"start\") display.startConverting()\n else display.conversionDone(event.output.split(\"/\").pop() ?? event.output)\n break\n case \"normalize\":\n if (event.status === \"start\") display.normalizeStart()\n else if (event.status === \"done\") display.normalizeComplete()\n else display.normalizeError(event.error)\n break\n case \"end\":\n break\n }\n })\n\n recorder.on(\"progress\", (event) => {\n if (event.kind === \"normalize\") display.normalizeProgress(event.percent, event.phase)\n })\n\n recorder.on(\"failure\", (err) => {\n display.showError(`[${err.code}] ${err.message}`)\n })\n}\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,MAAM;CACV,IAAI,MAAM,KAAK,MAAM,MAAM,OAAO,CAAC;CACnC,MAAM,MAAM,KAAK,MAAM,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;GACvD,QAAQ,YAAY,IAAI;GACxB,mBAAmB,KAAK,IAAI;EAC9B,OACE,QAAQ,kBAAkB,MAAM,aAAa,KAAK,IAAI,IAAI,gBAAgB,CAAC;EAE7E,cAAc,aAAa,QAAQ,MAAM;CAC3C,CAAC;CAED,SAAS,GAAG,WAAW,UAAU;EAC/B,QAAQ,MAAM,OAAd;GACE,KAAK;IACH,QAAQ,eAAe;IACvB;GACF,KAAK,YAAY;IACf,MAAM,SAAS,MAAM,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,MAAM;IACpD,QAAQ,gBAAgB,QAAQ,MAAM,UAAU,aAAa,MAAM,IAAI,CAAC;IACxE;GACF;GACA,KAAK;IACH,IAAI,MAAM,WAAW,SAAS,QAAQ,gBAAgB;SACjD,QAAQ,gBAAgB,MAAM,QAAQ;IAC3C;GACF,KAAK;IACH,IAAI,MAAM,WAAW,SAAS,QAAQ,gBAAgB;SACjD,QAAQ,eAAe,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,MAAM,MAAM;IACzE;GACF,KAAK;IACH,IAAI,MAAM,WAAW,SAAS,QAAQ,eAAe;SAChD,IAAI,MAAM,WAAW,QAAQ,QAAQ,kBAAkB;SACvD,QAAQ,eAAe,MAAM,KAAK;IACvC;GACF,KAAK,OACH;EACJ;CACF,CAAC;CAED,SAAS,GAAG,aAAa,UAAU;EACjC,IAAI,MAAM,SAAS,aAAa,QAAQ,kBAAkB,MAAM,SAAS,MAAM,KAAK;CACtF,CAAC;CAED,SAAS,GAAG,YAAY,QAAQ;EAC9B,QAAQ,UAAU,IAAI,IAAI,KAAK,IAAI,IAAI,SAAS;CAClD,CAAC;AACH"}
1
+ {"version":3,"file":"ui.mjs","names":[],"sources":["../src/ui.ts"],"sourcesContent":["/**\n * Terminal Display Manager — console output via yocto-spinner and yoctocolors.\n *\n * This module owns the terminal and should be the only thing writing to\n * stdout/stderr (the file logger handles persistent logs).\n */\n\nimport {\n bytesToHuman,\n formatDuration,\n isLiveReason,\n type RecorderController,\n relativeTime,\n} from \"@zfadhli/tokrec\"\nimport yoctoSpinner, { type Spinner } from \"yocto-spinner\"\nimport * as color from \"yoctocolors\"\n\n// ─── Tag helpers ──────────────────────────────────────────\nconst tag = {\n ok: color.bold(color.green(\"[OK] \")),\n done: color.bold(color.green(\"[DONE] \")),\n live: color.bold(color.green(\"[LIVE] \")),\n info: color.bold(color.blue(\"[INFO] \")),\n off: color.bold(color.blue(\"[OFF] \")),\n lock: color.bold(color.yellow(\"[LOCK] \")),\n warn: color.bold(color.yellow(\"[WARN] \")),\n err: color.bold(color.red(\"[ERR] \")),\n}\n\nexport interface Display {\n /** Called once when polling begins. */\n pollingStarted(intervalMinutes: number): void\n /** Spinner while checking if a user is live. */\n checkingUser(user: string): void\n /** User is offline (no active display). */\n userOffline(user: string): void\n /** User is still offline — updates the previous offline line with a timestamp. */\n userOfflineRepeat(user: string, lastCheck: string): void\n /** User is live! Clears the checking spinner. */\n userLive(user: string, roomId: string): void\n /**\n * User is live but `room/info` refused the session. `store` names the cookie\n * source used, and is omitted when there was none to name.\n */\n userRestricted(user: string, store?: string): void\n /** User is live but no stream URL was resolved. */\n userLiveNoStream(user: string, roomId: string): void\n\n /** Recording starts: spinner without filename (known only post-download). */\n startRecording(): void\n /** Recording finished successfully. Shows filename from the result. */\n finishRecording(filename: string, duration: number, size: string): void\n /** Recording encountered a non-fatal error. */\n recordingError(message: string): void\n\n /** FFmpeg segmenting starts. */\n startSegmenting(): void\n /** FFmpeg segmenting done. */\n segmentsCreated(count: number): void\n\n /** FFmpeg simple conversion starts (fallback path). */\n startConverting(): void\n /** Simple conversion done. */\n conversionDone(output: string): void\n\n /** Audio normalization starts (EBU R128 via peaknorm). */\n normalizeStart(): void\n /** Audio normalization progress update. */\n normalizeProgress(percent: number, phase: string): void\n /** Audio normalization completed successfully. */\n normalizeComplete(): void\n /** Audio normalization failed. */\n normalizeError(message: string): void\n\n /** Show version banner at startup. */\n showVersion(name: string, version: string): void\n\n /** General-purpose status helpers. */\n showError(message: string): void\n showInfo(message: string): void\n showWarning(message: string): void\n\n /** Stop all active spinners and clean up the terminal. */\n stop(): void\n}\n\nexport function createDisplay(): Display {\n // yocto-spinner with handleSignals off: bin.ts owns SIGINT/SIGTERM teardown.\n const stream = process.stdout\n // Mirrors yocto-spinner's internal isInteractive(); spinner.text writes a full\n // line when non-interactive, so per-tick updates must be skipped there.\n const animated = Boolean(stream.isTTY && process.env.TERM !== \"dumb\" && !(\"CI\" in process.env))\n const spin = (text: string): Spinner => yoctoSpinner({ text, stream, handleSignals: false })\n\n let activeSpinner: Spinner | null = null\n let offlineLineShown = false\n\n // Recording timer state\n let recordingStartTime: number | null = null\n let recordingTimer: ReturnType<typeof setInterval> | null = null\n\n /** Stop the currently active spinner (if any) without printing anything. */\n function clearSpinner(): void {\n if (recordingTimer) {\n clearInterval(recordingTimer)\n recordingTimer = null\n }\n if (activeSpinner?.isSpinning) {\n activeSpinner.stop()\n }\n activeSpinner = null\n }\n\n /** Stop the current spinner and print a one-liner with the given tag prefix. */\n function finalize(prefix: string, text: string): void {\n clearSpinner()\n process.stdout.write(`${prefix}${text}\\n`)\n }\n\n return {\n pollingStarted(intervalMinutes: number): void {\n finalize(\n tag.info,\n `${color.dim(\"Polling started (every \")}${color.bold(color.yellow(String(intervalMinutes)))}${color.dim(\" min)\")}`,\n )\n },\n\n checkingUser(user: string): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(`Checking @${user}...`))\n activeSpinner.start()\n },\n\n userOffline(user: string): void {\n finalize(tag.off, `${color.bold(color.yellow(`@${user}`))}${color.dim(\" is offline\")}`)\n offlineLineShown = true\n },\n\n userOfflineRepeat(user: string, lastCheck: string): void {\n clearSpinner()\n const text = `${tag.off}${color.bold(color.yellow(`@${user}`))}${color.dim(\" is offline\")} ${color.dim(`[last online: ${color.bold(color.yellow(lastCheck))}]`)}`\n if (offlineLineShown) {\n // Move cursor up one line and overwrite the previous offline message\n process.stdout.write(`\\x1b[1A\\r${text}\\x1b[K\\n`)\n } else {\n process.stdout.write(`${text}\\n`)\n offlineLineShown = true\n }\n },\n\n userLive(user: string, roomId: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(\n `${tag.live}${color.bold(color.green(`@${user}`))} ${color.dim(`(room: ${color.bold(color.yellow(roomId))})`)}\\n`,\n )\n },\n\n userRestricted(user: string, store?: string): void {\n clearSpinner()\n offlineLineShown = false\n const refused = store ? ` \\u2014 ${store} is not eligible` : \"\"\n process.stdout.write(\n `${tag.lock}${color.bold(color.yellow(`@${user}`))}${color.dim(` is live but room/info refused this session (status_code 4003110)${refused}; try another account with -c <cookies.json>`)}\\n`,\n )\n },\n\n userLiveNoStream(user: string, roomId: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(\n `${tag.live}${color.bold(color.green(`@${user}`))} ${color.dim(`(room: ${color.bold(color.yellow(roomId))}) \\u2014 no stream URL found`)}\\n`,\n )\n },\n\n startRecording(): void {\n clearSpinner()\n recordingStartTime = Date.now()\n activeSpinner = spin(\n `${color.cyan(\"Recording...\")} ${color.dim(`[${color.bold(color.yellow(\"0s\"))}]`)}`,\n )\n activeSpinner.start()\n\n recordingTimer = setInterval(() => {\n if (!animated || !activeSpinner?.isSpinning || !recordingStartTime) return\n const elapsed = (Date.now() - recordingStartTime) / 1000\n activeSpinner.text = `${color.cyan(\"Recording...\")} ${color.dim(`[${color.bold(color.yellow(formatDuration(elapsed)))}]`)}`\n }, 1000)\n },\n\n finishRecording(filename: string, duration: number, size: string): void {\n finalize(\n tag.done,\n `${color.cyan(filename)}${color.dim(\" — \")}${color.bold(color.yellow(size))}${color.dim(` in ${color.bold(color.yellow(formatDuration(duration)))}`)}`,\n )\n },\n\n recordingError(message: string): void {\n finalize(tag.err, color.red(`Recording failed: ${message}`))\n },\n\n startSegmenting(): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(\"Segmenting...\"))\n activeSpinner.start()\n },\n\n segmentsCreated(count: number): void {\n finalize(\n tag.ok,\n `${color.dim(\"Created \")}${color.bold(color.yellow(String(count)))}${color.dim(` MP4 segment${count !== 1 ? \"s\" : \"\"}`)}`,\n )\n },\n\n startConverting(): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(\"Converting to MP4...\"))\n activeSpinner.start()\n },\n\n conversionDone(output: string): void {\n finalize(tag.done, `${color.cyan(output)}`)\n },\n\n normalizeStart(): void {\n clearSpinner()\n activeSpinner = spin(color.cyan(\"Normalizing audio...\"))\n activeSpinner.start()\n },\n\n normalizeProgress(percent: number, phase: string): void {\n if (!animated || !activeSpinner?.isSpinning) return\n const label = phase === \"analyzing\" ? \"Analyzing\" : \"Normalizing\"\n activeSpinner.text = ` ${label}... ${color.bold(color.yellow(`${percent}%`))}`\n },\n\n normalizeComplete(): void {\n finalize(tag.ok, color.green(\"Audio normalized\"))\n },\n\n normalizeError(message: string): void {\n finalize(tag.err, color.red(`Normalization failed: ${message}`))\n },\n\n showVersion(name: string, version: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${color.dim(`${name} ${version}`)}\\n`)\n },\n\n showError(message: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${tag.err}${color.red(message)}\\n`)\n },\n\n showInfo(message: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${tag.info}${color.dim(message)}\\n`)\n },\n\n showWarning(message: string): void {\n clearSpinner()\n offlineLineShown = false\n process.stdout.write(`${tag.warn}${color.yellow(message)}\\n`)\n },\n\n stop(): void {\n clearSpinner()\n offlineLineShown = false\n },\n }\n}\n\n/**\n * Wire the recorder's four event channels to the terminal.\n *\n * Lives next to the display it drives: the mapping from recorder phase to\n * terminal line is presentation, so `bin.ts` should not carry it.\n */\nexport function attachDisplay(\n display: Display,\n recorder: Pick<RecorderController, \"on\">,\n user: string,\n store?: string,\n): void {\n let lastWasLive: boolean | null = null\n let firstOfflineTime = 0\n\n recorder.on(\"verdict\", (verdict) => {\n if (verdict.reason === \"restricted\") {\n display.userRestricted(user, store)\n } else if (verdict.reason === \"no-stream-url\") {\n display.userLiveNoStream(user, verdict.room?.id ?? \"?\")\n } else if (isLiveReason(verdict.reason)) {\n display.userLive(user, verdict.room?.id ?? \"?\")\n } else if (lastWasLive === null || lastWasLive === true) {\n display.userOffline(user)\n firstOfflineTime = Date.now()\n } else {\n display.userOfflineRepeat(user, relativeTime(Date.now() - firstOfflineTime))\n }\n lastWasLive = isLiveReason(verdict.reason)\n })\n\n recorder.on(\"record\", (event) => {\n switch (event.phase) {\n case \"start\":\n display.startRecording()\n break\n case \"download\": {\n const parsed = event.file.split(\"/\").pop() ?? event.file\n display.finishRecording(parsed, event.duration, bytesToHuman(event.size))\n break\n }\n case \"segment\":\n if (event.status === \"start\") display.startSegmenting()\n else display.segmentsCreated(event.segments)\n break\n case \"convert\":\n if (event.status === \"start\") display.startConverting()\n else display.conversionDone(event.output.split(\"/\").pop() ?? event.output)\n break\n case \"normalize\":\n if (event.status === \"start\") display.normalizeStart()\n else if (event.status === \"done\") display.normalizeComplete()\n else display.normalizeError(event.error)\n break\n case \"end\":\n break\n }\n })\n\n recorder.on(\"progress\", (event) => {\n if (event.kind === \"normalize\") display.normalizeProgress(event.percent, event.phase)\n })\n\n recorder.on(\"failure\", (err) => {\n display.showError(`[${err.code}] ${err.message}`)\n })\n}\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,MAAM;CACV,IAAI,MAAM,KAAK,MAAM,MAAM,OAAO,CAAC;CACnC,MAAM,MAAM,KAAK,MAAM,MAAM,SAAS,CAAC;CACvC,MAAM,MAAM,KAAK,MAAM,MAAM,SAAS,CAAC;CACvC,MAAM,MAAM,KAAK,MAAM,KAAK,SAAS,CAAC;CACtC,KAAK,MAAM,KAAK,MAAM,KAAK,QAAQ,CAAC;CACpC,MAAM,MAAM,KAAK,MAAM,OAAO,SAAS,CAAC;CACxC,MAAM,MAAM,KAAK,MAAM,OAAO,SAAS,CAAC;CACxC,KAAK,MAAM,KAAK,MAAM,IAA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;IACvB;GACF,KAAK,YAAY;IACf,MAAM,SAAS,MAAM,KAAK,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,MAAM;IACpD,QAAQ,gBAAgB,QAAQ,MAAM,UAAU,aAAa,MAAM,IAAI,CAAC;IACxE;GACF;GACA,KAAK;IACH,IAAI,MAAM,WAAW,SAAS,QAAQ,gBAAgB;SACjD,QAAQ,gBAAgB,MAAM,QAAQ;IAC3C;GACF,KAAK;IACH,IAAI,MAAM,WAAW,SAAS,QAAQ,gBAAgB;SACjD,QAAQ,eAAe,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK,MAAM,MAAM;IACzE;GACF,KAAK;IACH,IAAI,MAAM,WAAW,SAAS,QAAQ,eAAe;SAChD,IAAI,MAAM,WAAW,QAAQ,QAAQ,kBAAkB;SACvD,QAAQ,eAAe,MAAM,KAAK;IACvC;GACF,KAAK,OACH;EACJ;CACF,CAAC;CAED,SAAS,GAAG,aAAa,UAAU;EACjC,IAAI,MAAM,SAAS,aAAa,QAAQ,kBAAkB,MAAM,SAAS,MAAM,KAAK;CACtF,CAAC;CAED,SAAS,GAAG,YAAY,QAAQ;EAC9B,QAAQ,UAAU,IAAI,IAAI,KAAK,IAAI,IAAI,SAAS;CAClD,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zfadhli/tokrec-cli",
3
- "version": "0.18.2",
3
+ "version": "0.18.4",
4
4
  "description": "TikTok live stream recorder CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -14,7 +14,7 @@
14
14
  "typecheck": "tsc --noEmit"
15
15
  },
16
16
  "dependencies": {
17
- "@zfadhli/tokrec": "^0.18.2",
17
+ "@zfadhli/tokrec": "^0.18.4",
18
18
  "cac": "^7.0.0",
19
19
  "execa": "^9.6.1",
20
20
  "yocto-spinner": "^1.2.2",