@zfadhli/tokrec 0.16.0 → 0.18.0
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/dist/app/config.d.mts +5 -2
- package/dist/app/config.d.mts.map +1 -1
- package/dist/app/config.mjs +1 -0
- package/dist/app/config.mjs.map +1 -1
- package/dist/app/recorder.mjs +9 -2
- package/dist/app/recorder.mjs.map +1 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +4 -2
- package/dist/io/http.d.mts +13 -0
- package/dist/io/http.d.mts.map +1 -0
- package/dist/io/http.mjs +34 -6
- package/dist/io/http.mjs.map +1 -1
- package/package.json +1 -1
- package/src/app/config.ts +11 -2
- package/src/app/recorder.ts +14 -1
- package/src/index.ts +1 -0
- package/src/io/http.ts +30 -3
package/dist/app/config.d.mts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { TikTokError } from "../core/errors.mjs";
|
|
2
2
|
import { LiveReason, Verdict } from "../core/verdict.mjs";
|
|
3
|
+
import { splitCookies } from "../io/http.mjs";
|
|
3
4
|
|
|
4
5
|
//#region src/app/config.d.ts
|
|
5
6
|
/**
|
|
6
7
|
* TikTok cookie key-value pairs extracted from Firefox or cookies.json.
|
|
7
|
-
* Includes session cookies (sessionid_ss
|
|
8
|
-
*
|
|
8
|
+
* Includes session cookies (sessionid_ss) and any WAF bypass cookies needed to
|
|
9
|
+
* avoid Slardar challenges on www.tiktok.com. Routing hints TikTok computes per
|
|
10
|
+
* session (`tt-target-idc`, `tt-target-idc-sign`) are dropped before sending —
|
|
11
|
+
* see `splitCookies` in `io/http.ts`.
|
|
9
12
|
*/
|
|
10
13
|
type CookieAuth = Record<string, string>;
|
|
11
14
|
type LogLevel = "debug" | "info" | "warn" | "error";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.mts","names":[],"sources":["../../src/app/config.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"config.d.mts","names":[],"s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;EAAgB,KAAA;EAAe,MAAA;AAAA;EACnD,KAAA;EAAoB,MAAA;EAAiB,KAAA;EAAe,KAAA;AAAA;EACnD,KAAA;AAAA,IAAiB,YAAA;;UAGP,gBAAA;EACf,KAAA;EACA,OAAA;EACA,KAAA;AAAA;;KAIU,aAAA;EACL,IAAA;AAAA,IAAqB,gBAAA;EACtB,IAAA;EAAmB,IAAA;EAAc,OAAA;EAAiB,KAAA;AAAA;AAAA,UAEvC,oBAAA;EACf,OAAA,GAAU,OAAA,EAAS,OAAA;EACnB,MAAA,GAAS,KAAA,EAAO,WAAA;EAChB,QAAA,GAAW,KAAA,EAAO,aAAA;EAClB,OAAA,GAAU,GAAA,EAAK,WAAA;AAAA"}
|
package/dist/app/config.mjs
CHANGED
package/dist/app/config.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.mjs","names":[],"sources":["../../src/app/config.ts"],"sourcesContent":["/**\n * Config — types, defaults, and normalization for the recorder.\n * The single source of truth for every user-facing option.\n */\n\nimport { TikTokError } from \"../core/errors\"\nimport type { Verdict } from \"../core/verdict\"\n\n/**\n * TikTok cookie key-value pairs extracted from Firefox or cookies.json.\n * Includes session cookies (sessionid_ss
|
|
1
|
+
{"version":3,"file":"config.mjs","names":[],"sources":["../../src/app/config.ts"],"sourcesContent":["/**\n * Config — types, defaults, and normalization for the recorder.\n * The single source of truth for every user-facing option.\n */\n\nimport { TikTokError } from \"../core/errors\"\nimport type { Verdict } from \"../core/verdict\"\n\n/**\n * TikTok cookie key-value pairs extracted from Firefox or cookies.json.\n * Includes session cookies (sessionid_ss) and any WAF bypass cookies needed to\n * avoid Slardar challenges on www.tiktok.com. Routing hints TikTok computes per\n * session (`tt-target-idc`, `tt-target-idc-sign`) are dropped before sending —\n * see `splitCookies` in `io/http.ts`.\n */\nexport type CookieAuth = Record<string, string>\n\n/**\n * Re-exported so callers who build `cookies` themselves — the CLI among them —\n * can warn about a hint we refuse to send without hardcoding its name. `io/`\n * is outside the barrel's bands, and this type is the cookie surface.\n */\nexport { splitCookies } from \"../io/http\"\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\"\n\n/**\n * Machine-readable reason for a LIVE status verdict — lives in `core/verdict.ts`.\n */\nexport type { LiveReason } from \"../core/verdict\"\n\nexport interface RecorderConfig {\n /** TikTok username (required) */\n user: string\n /** Output directory for recordings (default: ./recordings) */\n outputDir?: string\n /** Polling interval in minutes (default: 3) */\n interval?: number\n /** Max recording duration in seconds (default: 0 — unlimited). CLI accepts minutes, converted internally. */\n duration?: number\n /** HTTP proxy URL (e.g. http://127.0.0.1:8080) */\n proxy?: string\n /** Path to cookies.json (default: ./cookies.json) */\n cookiesPath?: string\n /** Cookie auth loaded from cookies.json */\n cookies?: CookieAuth\n /** Log level (default: info) */\n logLevel?: LogLevel\n /** Whether to print logs to console (default: true). Set false when using Display-based UI. */\n logConsole?: boolean\n /** Segment duration in minutes (default: 0 — disabled). When >= 1, the recording is split into segments of this length. */\n segmentMinutes?: number\n /** Normalize audio loudness via EBU R128 (default: false). */\n normalizeAudio?: boolean\n /** Target loudness in LUFS (default: -14). */\n normalizeLoudness?: number\n /** Audio codec for normalized output (default: peaknorm's default, \"libopus\"). */\n normalizeCodec?: string\n /** Audio bitrate for normalized output (default: peaknorm's default, \"96k\"). */\n normalizeBitrate?: string\n /**\n * Max API requests per second (default: 5).\n * Prevents TikTok WAF triggering on rapid polling or URL refresh loops.\n * Set to 0 for unlimited (not recommended).\n */\n ratePerSecond?: number\n /** Show API debug logging on stderr (default: false). */\n debug?: boolean\n}\n\nexport interface RecorderController {\n /** Start the polling loop */\n start(): Promise<void>\n /** Gracefully stop (joins active recording, then exits) */\n stop(): Promise<void>\n /** Snapshot of current state */\n getStatus(): RecorderStatus\n /** Subscribe to events */\n on<E extends keyof RecorderEventHandler>(event: E, handler: RecorderEventHandler[E]): void\n /** Unsubscribe a previously registered event handler */\n off<E extends keyof RecorderEventHandler>(event: E, handler: RecorderEventHandler[E]): void\n}\n\nexport type Phase = \"idle\" | \"polling\" | \"recording\" | \"segmenting\" | \"converting\" | \"stopped\"\n\nexport interface RecorderStatus {\n state: Phase\n user: string\n currentFile?: string\n sessionDuration?: number\n lastPollTime?: string\n lastError?: string\n}\n\nexport type RecorderEvent = keyof RecorderEventHandler\n\nexport interface RecordedFile {\n file: string\n duration: number\n size: number\n}\n\n/** One recording lifecycle channel: start → download → processing → end. */\nexport type RecordEvent =\n | { phase: \"start\"; user: string; file: string }\n | ({ phase: \"download\" } & RecordedFile)\n | { phase: \"segment\"; status: \"start\"; input: string; outputPattern: string }\n | { phase: \"segment\"; status: \"end\"; segments: number }\n | { phase: \"convert\"; status: \"start\"; input: string }\n | { phase: \"convert\"; status: \"done\"; input: string; output: string }\n | { phase: \"normalize\"; status: \"start\"; file: string }\n | { phase: \"normalize\"; status: \"done\"; input: string; output: string }\n | { phase: \"normalize\"; status: \"error\"; input: string; error: string }\n | ({ phase: \"end\" } & RecordedFile)\n\n/** One download progress sample. The finished-download shape is `RecordedFile`. */\nexport interface DownloadProgress {\n bytes: number\n elapsed: number\n speed: number\n}\n\n/** Download and normalize progress share one spinner in the CLI. */\nexport type ProgressEvent =\n | ({ kind: \"download\" } & DownloadProgress)\n | { kind: \"normalize\"; file: string; percent: number; phase: \"analyzing\" | \"normalizing\" }\n\nexport interface RecorderEventHandler {\n verdict: (verdict: Verdict) => void\n record: (event: RecordEvent) => void\n progress: (event: ProgressEvent) => void\n failure: (err: TikTokError) => void\n}\n\n/** A `RecorderConfig` with every default applied — what the recorder runs on. */\nexport type ResolvedConfig = Required<\n Omit<RecorderConfig, \"proxy\" | \"cookies\" | \"cookiesPath\" | \"normalizeCodec\" | \"normalizeBitrate\">\n> &\n Pick<RecorderConfig, \"proxy\" | \"cookies\" | \"cookiesPath\" | \"normalizeCodec\" | \"normalizeBitrate\">\n\n/** Apply defaults once, at the entry point; nothing downstream re-reads `??`. */\nexport function resolveConfig(config: RecorderConfig): ResolvedConfig {\n return {\n user: config.user,\n outputDir: config.outputDir ?? \".\",\n interval: config.interval ?? 3,\n duration: config.duration ?? 0,\n proxy: config.proxy,\n cookies: config.cookies,\n cookiesPath: config.cookiesPath,\n logLevel: config.logLevel ?? \"info\",\n logConsole: config.logConsole ?? true,\n segmentMinutes: config.segmentMinutes ?? 0,\n normalizeAudio: config.normalizeAudio ?? false,\n normalizeLoudness: config.normalizeLoudness ?? -14,\n normalizeCodec: config.normalizeCodec,\n normalizeBitrate: config.normalizeBitrate,\n ratePerSecond: config.ratePerSecond ?? 5,\n debug: config.debug ?? false,\n }\n}\n\nexport function validateConfig(config: RecorderConfig): void {\n if (!config.user || config.user.trim().length === 0) {\n throw new TikTokError(\"config-error\", \"--user is required\")\n }\n if (config.interval !== undefined && config.interval < 1) {\n throw new TikTokError(\"config-error\", \"--interval must be >= 1 minute\")\n }\n if (config.duration !== undefined && config.duration < 0) {\n throw new TikTokError(\"config-error\", \"--duration must be >= 0 seconds\")\n }\n}\n"],"mappings":";;;AA6IA,SAAgB,cAAc,QAAwC;CACpE,OAAO;EACL,MAAM,OAAO;EACb,WAAW,OAAO,aAAa;EAC/B,UAAU,OAAO,YAAY;EAC7B,UAAU,OAAO,YAAY;EAC7B,OAAO,OAAO;EACd,SAAS,OAAO;EAChB,aAAa,OAAO;EACpB,UAAU,OAAO,YAAY;EAC7B,YAAY,OAAO,cAAc;EACjC,gBAAgB,OAAO,kBAAkB;EACzC,gBAAgB,OAAO,kBAAkB;EACzC,mBAAmB,OAAO,qBAAqB;EAC/C,gBAAgB,OAAO;EACvB,kBAAkB,OAAO;EACzB,eAAe,OAAO,iBAAiB;EACvC,OAAO,OAAO,SAAS;CACzB;AACF"}
|
package/dist/app/recorder.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
+
import { createHttpClient, splitCookies } from "../io/http.mjs";
|
|
2
|
+
import { resolveConfig } from "./config.mjs";
|
|
1
3
|
import { planTick } from "../core/plan.mjs";
|
|
2
4
|
import { verdictOf } from "../core/verdict.mjs";
|
|
3
|
-
import { createHttpClient } from "../io/http.mjs";
|
|
4
5
|
import { createMediaConverter } from "../io/media/ffmpeg.mjs";
|
|
5
6
|
import { downloadStream } from "../io/media/download.mjs";
|
|
6
7
|
import { createTikTokClient } from "../io/tiktok/client.mjs";
|
|
7
|
-
import { resolveConfig } from "./config.mjs";
|
|
8
8
|
import { createRecordingJob } from "./job.mjs";
|
|
9
9
|
import { createLogger } from "./logger.mjs";
|
|
10
10
|
import { createPollingMonitor } from "./loop.mjs";
|
|
@@ -165,6 +165,7 @@ function createRecorder(config) {
|
|
|
165
165
|
recordedSec = 0;
|
|
166
166
|
consecutiveErrors = 0;
|
|
167
167
|
logger.info(`Starting recorder for @${cfg.user}`);
|
|
168
|
+
warnStaleCookies(cfg.cookies, logger);
|
|
168
169
|
const http = await createHttpClient(cfg);
|
|
169
170
|
const client = createTikTokClient(http, logger, cfg.debug, scope.signal);
|
|
170
171
|
const converter = createMediaConverter(logger, post.signal);
|
|
@@ -220,6 +221,12 @@ function createRecorder(config) {
|
|
|
220
221
|
off: emitter.off
|
|
221
222
|
};
|
|
222
223
|
}
|
|
224
|
+
/** Say once, up front, that a routing hint from the config is being ignored. */
|
|
225
|
+
function warnStaleCookies(cookies, logger) {
|
|
226
|
+
const { stale } = splitCookies(cookies ?? {});
|
|
227
|
+
if (stale.length === 0) return;
|
|
228
|
+
logger.warn(`Ignoring ${stale.join(" and ")}: TikTok computes those per session, and a stale value makes the room API look like a private room`);
|
|
229
|
+
}
|
|
223
230
|
function lastSource(verdict) {
|
|
224
231
|
return [...verdict.evidence].reverse().find((e) => e.outcome === "hit" || e.outcome === "denied")?.source ?? "none";
|
|
225
232
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recorder.mjs","names":[],"sources":["../../src/app/recorder.ts"],"sourcesContent":["/**\n * Recorder orchestrator — wires the TikTok client, stream download, and\n * RecordingJob into a single RecorderController.\n *\n * Policy lives in `core/plan.ts`; this file maps a TickPlan to effects and\n * owns the session state those effects mutate. Everything a tick needs is\n * constructed as a `const` in `start()` and passed in, so no call site has to\n * assert a non-null module-level `let` back into existence.\n */\n\nimport { EventEmitter } from \"node:events\"\nimport { planTick, type TickFacts } from \"../core/plan\"\nimport { verdictOf } from \"../core/verdict\"\nimport { createHttpClient, type HttpClient } from \"../io/http\"\nimport { downloadStream } from \"../io/media/download\"\nimport { createMediaConverter, type MediaConverter } from \"../io/media/ffmpeg\"\nimport { createTikTokClient, type TikTokClient } from \"../io/tiktok/client\"\nimport type {\n RecorderConfig,\n RecorderController,\n RecorderEvent,\n RecorderEventHandler,\n RecorderStatus,\n} from \"./config\"\nimport { resolveConfig } from \"./config\"\nimport { createRecordingJob, type RecordingJob } from \"./job\"\nimport { createLogger } from \"./logger\"\nimport { createPollingMonitor, type PollingMonitor } from \"./loop\"\n\n/** Max wait for a stop-time remux before aborting it (matches the pre-#32 cap). */\nconst POST_REMUX_GRACE_MS = 10 * 60 * 1000\n\n/** Everything one poll tick needs, built by `start()` before the tick can run. */\ninterface TickDeps {\n client: TikTokClient\n monitor: PollingMonitor\n scope: AbortController\n post: AbortController\n converter: MediaConverter\n}\n\n/** What `stop()` has to join and release. */\ninterface Running {\n monitor: PollingMonitor\n http: HttpClient\n scope: AbortController\n}\n\nexport function createRecorder(config: RecorderConfig): RecorderController {\n const cfg = resolveConfig(config)\n const logger = createLogger({\n level: cfg.logLevel,\n logFile: \"tiktok-recorder.log\",\n console: cfg.logConsole,\n })\n\n // Typed over `node:events`; a throwing subscriber must not kill a recording.\n const bus = new EventEmitter()\n const emitter = {\n on: bus.on.bind(bus) as RecorderController[\"on\"],\n off: bus.off.bind(bus) as RecorderController[\"off\"],\n emit: <E extends RecorderEvent>(\n event: E,\n ...args: Parameters<RecorderEventHandler[E]>\n ): void => {\n try {\n bus.emit(event, ...args)\n } catch {\n // ignore — a bad subscriber must never crash the recorder\n }\n },\n clear: () => bus.removeAllListeners(),\n }\n\n // Session state — written by ticks and by the job lifecycle, read by getStatus().\n const status: RecorderStatus = { state: \"idle\", user: cfg.user }\n let running: Running | null = null\n let postScope: AbortController | null = null\n let currentJob: RecordingJob | null = null\n let recordedSec = 0\n let consecutiveErrors = 0\n\n function setState(partial: Partial<RecorderStatus>): void {\n const prev = status.state\n Object.assign(status, partial)\n if (partial.state !== undefined && partial.state !== prev) {\n logger.info(`State: ${prev} → ${partial.state}`)\n if (partial.state === \"polling\") status.lastPollTime = new Date().toISOString()\n }\n }\n\n async function tick(d: TickDeps): Promise<void> {\n const { client, monitor, scope, post } = d\n if (scope.signal.aborted) return\n const user = cfg.user\n\n client.invalidateCache()\n logger.info(`Checking @${user}...`)\n\n const verdict = await client.getVerdict(user)\n const facts: TickFacts = {\n recording: currentJob !== null,\n recordedSec,\n oneShot: cfg.duration > 0,\n consecutiveErrors,\n }\n consecutiveErrors =\n verdict.reason === \"error\" || verdict.reason === \"no-room-id\" ? consecutiveErrors + 1 : 0\n\n emitter.emit(\"verdict\", verdict)\n const plan = planTick(verdict, facts)\n\n switch (plan.kind) {\n case \"poll\": {\n logger.info(\n `@${user} ${plan.note} (reason: ${verdict.reason}, source: ${lastSource(verdict)})`,\n )\n return\n }\n case \"hold\": {\n const why =\n plan.reason === \"restricted\"\n ? \"age-protected/restricted — stream unavailable (reason: restricted, status_code 4003110\"\n : \"no stream URL found (reason: no-stream-url\"\n logger.warn(`@${user} is live but ${why}, room: ${plan.room.id})`)\n return\n }\n case \"stop\": {\n if (plan.why === \"one-shot\") {\n logger.info(\"Duration limit reached — exiting\")\n monitor.stopAfterCurrentTick()\n } else if (plan.why === \"gave-up\") {\n logger.error(`@${user} gave up after ${consecutiveErrors} consecutive errors`)\n monitor.stopAfterCurrentTick()\n }\n return\n }\n case \"record\": {\n const { room, stream } = plan\n logger.info(`@${user} is LIVE! (room: ${room.id}, reason: live)`)\n setState({ state: \"recording\" })\n emitter.emit(\"record\", { phase: \"start\", user, file: \"\" })\n\n const getNextUrl = async (): Promise<string | null> => {\n if (scope.signal.aborted) return null\n // Use the lightweight check_alive endpoint first — avoids a full\n // page re-scan + room/info call when the stream is still active.\n const alive = await client.isRoomAlive(room.id)\n if (!alive) {\n logger.info(`@${user} is no longer live — stopping`)\n return null\n }\n client.invalidateCache()\n return client.getLiveUrl(room.id)\n }\n\n const result = await downloadStream(\n stream.url,\n user,\n cfg.outputDir,\n cfg.duration,\n (info) => emitter.emit(\"progress\", { kind: \"download\", ...info }),\n getNextUrl,\n scope.signal,\n logger,\n cfg.cookies,\n )\n\n emitter.emit(\"record\", { phase: \"download\", ...result })\n recordedSec += result.duration\n\n const job = createRecordingJob({\n result,\n cfg,\n logger,\n converter: d.converter,\n signal: post.signal,\n emitRecord: (event) => emitter.emit(\"record\", event),\n emitProgress: (event) => emitter.emit(\"progress\", event),\n emitFailure: (err) => emitter.emit(\"failure\", err),\n setState,\n })\n currentJob = job\n try {\n await job.finish()\n } finally {\n currentJob = null\n }\n\n // One-shot mode: if a duration was set, stop after this recording\n if (cfg.duration > 0) {\n logger.info(\"Duration limit reached — exiting\")\n monitor.stopAfterCurrentTick()\n } else if (!scope.signal.aborted) {\n // Recording ended because the stream went offline (not user-initiated\n // stop). Immediately re-check via the lightweight endpoint.\n const alive = await client.isRoomAlive(room.id)\n if (!alive) {\n logger.info(`@${user} is offline`)\n emitter.emit(\n \"verdict\",\n verdictOf({ room: { ...room, live: false }, evidence: verdict.evidence }),\n )\n }\n }\n return\n }\n }\n }\n\n async function start(): Promise<void> {\n if (status.state !== \"idle\") {\n logger.warn(`start() ignored: already in state ${status.state}`)\n return\n }\n const scope = new AbortController()\n // Post-processing outlives a user stop: Ctrl+C aborts the download, but the\n // partial .ts is still remuxed to .mp4 before the process exits.\n const post = new AbortController()\n postScope = post\n currentJob = null\n recordedSec = 0\n consecutiveErrors = 0\n\n logger.info(`Starting recorder for @${cfg.user}`)\n const http = await createHttpClient(cfg)\n const client = createTikTokClient(http, logger, cfg.debug, scope.signal)\n const converter = createMediaConverter(logger, post.signal)\n\n // Self-reference inside `onTick` is safe: the monitor calls it from\n // `start()`, never during construction.\n let monitor: PollingMonitor\n monitor = createPollingMonitor({\n intervalMinutes: cfg.interval,\n signal: scope.signal,\n logger,\n onTick: () => tick({ client, monitor, scope, post, converter }),\n })\n running = { monitor, http, scope }\n\n setState({ state: \"polling\" })\n await monitor.start()\n }\n\n async function stop(): Promise<void> {\n if (status.state === \"stopped\") {\n logger.warn(`stop() ignored: already stopped`)\n return\n }\n logger.info(\"Stopping recorder...\")\n running?.scope.abort(\"user\")\n\n const grace = setTimeout(() => postScope?.abort(\"stop-timeout\"), POST_REMUX_GRACE_MS)\n try {\n const job = currentJob\n if (job) {\n logger.info(\"Waiting for active recording to finish...\")\n await job.finish()\n }\n\n if (running) await running.monitor.stop()\n } finally {\n clearTimeout(grace)\n }\n if (running) await running.http.close()\n emitter.clear()\n setState({ state: \"stopped\" })\n logger.info(\"Recorder stopped\")\n }\n\n return {\n start,\n stop,\n getStatus: () => ({ ...status }),\n on: emitter.on,\n off: emitter.off,\n }\n}\n\nfunction lastSource(verdict: ReturnType<typeof verdictOf>): string {\n return (\n [...verdict.evidence].reverse().find((e) => e.outcome === \"hit\" || e.outcome === \"denied\")\n ?.source ?? \"none\"\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,sBAAsB,MAAU;AAkBtC,SAAgB,eAAe,QAA4C;CACzE,MAAM,MAAM,cAAc,MAAM;CAChC,MAAM,SAAS,aAAa;EAC1B,OAAO,IAAI;EACX,SAAS;EACT,SAAS,IAAI;CACf,CAAC;CAGD,MAAM,MAAM,IAAI,aAAa;CAC7B,MAAM,UAAU;EACd,IAAI,IAAI,GAAG,KAAK,GAAG;EACnB,KAAK,IAAI,IAAI,KAAK,GAAG;EACrB,OACE,OACA,GAAG,SACM;GACT,IAAI;IACF,IAAI,KAAK,OAAO,GAAG,IAAI;GACzB,QAAQ,CAER;EACF;EACA,aAAa,IAAI,mBAAmB;CACtC;CAGA,MAAM,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,UAAU;GACR,aAAa,KAAK;EACpB;EACA,IAAI,SAAS,MAAM,QAAQ,KAAK,MAAM;EACtC,QAAQ,MAAM;EACd,SAAS,EAAE,OAAO,UAAU,CAAC;EAC7B,OAAO,KAAK,kBAAkB;CAChC;CAEA,OAAO;EACL;EACA;EACA,kBAAkB,EAAE,GAAG,OAAO;EAC9B,IAAI,QAAQ;EACZ,KAAK,QAAQ;CACf;AACF;AAEA,SAAS,WAAW,SAA+C;CACjE,OACE,CAAC,GAAG,QAAQ,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,MAAM,EAAE,YAAY,SAAS,EAAE,YAAY,QAAQ,CAAC,EACtF,UAAU;AAElB"}
|
|
1
|
+
{"version":3,"file":"recorder.mjs","names":[],"sources":["../../src/app/recorder.ts"],"sourcesContent":["/**\n * Recorder orchestrator — wires the TikTok client, stream download, and\n * RecordingJob into a single RecorderController.\n *\n * Policy lives in `core/plan.ts`; this file maps a TickPlan to effects and\n * owns the session state those effects mutate. Everything a tick needs is\n * constructed as a `const` in `start()` and passed in, so no call site has to\n * assert a non-null module-level `let` back into existence.\n */\n\nimport { EventEmitter } from \"node:events\"\nimport { planTick, type TickFacts } from \"../core/plan\"\nimport { verdictOf } from \"../core/verdict\"\nimport { createHttpClient, type HttpClient, splitCookies } from \"../io/http\"\nimport { downloadStream } from \"../io/media/download\"\nimport { createMediaConverter, type MediaConverter } from \"../io/media/ffmpeg\"\nimport { createTikTokClient, type TikTokClient } from \"../io/tiktok/client\"\nimport type {\n RecorderConfig,\n RecorderController,\n RecorderEvent,\n RecorderEventHandler,\n RecorderStatus,\n} from \"./config\"\nimport { resolveConfig } from \"./config\"\nimport { createRecordingJob, type RecordingJob } from \"./job\"\nimport { createLogger } from \"./logger\"\nimport { createPollingMonitor, type PollingMonitor } from \"./loop\"\n\n/** Max wait for a stop-time remux before aborting it (matches the pre-#32 cap). */\nconst POST_REMUX_GRACE_MS = 10 * 60 * 1000\n\n/** Everything one poll tick needs, built by `start()` before the tick can run. */\ninterface TickDeps {\n client: TikTokClient\n monitor: PollingMonitor\n scope: AbortController\n post: AbortController\n converter: MediaConverter\n}\n\n/** What `stop()` has to join and release. */\ninterface Running {\n monitor: PollingMonitor\n http: HttpClient\n scope: AbortController\n}\n\nexport function createRecorder(config: RecorderConfig): RecorderController {\n const cfg = resolveConfig(config)\n const logger = createLogger({\n level: cfg.logLevel,\n logFile: \"tiktok-recorder.log\",\n console: cfg.logConsole,\n })\n\n // Typed over `node:events`; a throwing subscriber must not kill a recording.\n const bus = new EventEmitter()\n const emitter = {\n on: bus.on.bind(bus) as RecorderController[\"on\"],\n off: bus.off.bind(bus) as RecorderController[\"off\"],\n emit: <E extends RecorderEvent>(\n event: E,\n ...args: Parameters<RecorderEventHandler[E]>\n ): void => {\n try {\n bus.emit(event, ...args)\n } catch {\n // ignore — a bad subscriber must never crash the recorder\n }\n },\n clear: () => bus.removeAllListeners(),\n }\n\n // Session state — written by ticks and by the job lifecycle, read by getStatus().\n const status: RecorderStatus = { state: \"idle\", user: cfg.user }\n let running: Running | null = null\n let postScope: AbortController | null = null\n let currentJob: RecordingJob | null = null\n let recordedSec = 0\n let consecutiveErrors = 0\n\n function setState(partial: Partial<RecorderStatus>): void {\n const prev = status.state\n Object.assign(status, partial)\n if (partial.state !== undefined && partial.state !== prev) {\n logger.info(`State: ${prev} → ${partial.state}`)\n if (partial.state === \"polling\") status.lastPollTime = new Date().toISOString()\n }\n }\n\n async function tick(d: TickDeps): Promise<void> {\n const { client, monitor, scope, post } = d\n if (scope.signal.aborted) return\n const user = cfg.user\n\n client.invalidateCache()\n logger.info(`Checking @${user}...`)\n\n const verdict = await client.getVerdict(user)\n const facts: TickFacts = {\n recording: currentJob !== null,\n recordedSec,\n oneShot: cfg.duration > 0,\n consecutiveErrors,\n }\n consecutiveErrors =\n verdict.reason === \"error\" || verdict.reason === \"no-room-id\" ? consecutiveErrors + 1 : 0\n\n emitter.emit(\"verdict\", verdict)\n const plan = planTick(verdict, facts)\n\n switch (plan.kind) {\n case \"poll\": {\n logger.info(\n `@${user} ${plan.note} (reason: ${verdict.reason}, source: ${lastSource(verdict)})`,\n )\n return\n }\n case \"hold\": {\n const why =\n plan.reason === \"restricted\"\n ? \"age-protected/restricted — stream unavailable (reason: restricted, status_code 4003110\"\n : \"no stream URL found (reason: no-stream-url\"\n logger.warn(`@${user} is live but ${why}, room: ${plan.room.id})`)\n return\n }\n case \"stop\": {\n if (plan.why === \"one-shot\") {\n logger.info(\"Duration limit reached — exiting\")\n monitor.stopAfterCurrentTick()\n } else if (plan.why === \"gave-up\") {\n logger.error(`@${user} gave up after ${consecutiveErrors} consecutive errors`)\n monitor.stopAfterCurrentTick()\n }\n return\n }\n case \"record\": {\n const { room, stream } = plan\n logger.info(`@${user} is LIVE! (room: ${room.id}, reason: live)`)\n setState({ state: \"recording\" })\n emitter.emit(\"record\", { phase: \"start\", user, file: \"\" })\n\n const getNextUrl = async (): Promise<string | null> => {\n if (scope.signal.aborted) return null\n // Use the lightweight check_alive endpoint first — avoids a full\n // page re-scan + room/info call when the stream is still active.\n const alive = await client.isRoomAlive(room.id)\n if (!alive) {\n logger.info(`@${user} is no longer live — stopping`)\n return null\n }\n client.invalidateCache()\n return client.getLiveUrl(room.id)\n }\n\n const result = await downloadStream(\n stream.url,\n user,\n cfg.outputDir,\n cfg.duration,\n (info) => emitter.emit(\"progress\", { kind: \"download\", ...info }),\n getNextUrl,\n scope.signal,\n logger,\n cfg.cookies,\n )\n\n emitter.emit(\"record\", { phase: \"download\", ...result })\n recordedSec += result.duration\n\n const job = createRecordingJob({\n result,\n cfg,\n logger,\n converter: d.converter,\n signal: post.signal,\n emitRecord: (event) => emitter.emit(\"record\", event),\n emitProgress: (event) => emitter.emit(\"progress\", event),\n emitFailure: (err) => emitter.emit(\"failure\", err),\n setState,\n })\n currentJob = job\n try {\n await job.finish()\n } finally {\n currentJob = null\n }\n\n // One-shot mode: if a duration was set, stop after this recording\n if (cfg.duration > 0) {\n logger.info(\"Duration limit reached — exiting\")\n monitor.stopAfterCurrentTick()\n } else if (!scope.signal.aborted) {\n // Recording ended because the stream went offline (not user-initiated\n // stop). Immediately re-check via the lightweight endpoint.\n const alive = await client.isRoomAlive(room.id)\n if (!alive) {\n logger.info(`@${user} is offline`)\n emitter.emit(\n \"verdict\",\n verdictOf({ room: { ...room, live: false }, evidence: verdict.evidence }),\n )\n }\n }\n return\n }\n }\n }\n\n async function start(): Promise<void> {\n if (status.state !== \"idle\") {\n logger.warn(`start() ignored: already in state ${status.state}`)\n return\n }\n const scope = new AbortController()\n // Post-processing outlives a user stop: Ctrl+C aborts the download, but the\n // partial .ts is still remuxed to .mp4 before the process exits.\n const post = new AbortController()\n postScope = post\n currentJob = null\n recordedSec = 0\n consecutiveErrors = 0\n\n logger.info(`Starting recorder for @${cfg.user}`)\n warnStaleCookies(cfg.cookies, logger)\n const http = await createHttpClient(cfg)\n const client = createTikTokClient(http, logger, cfg.debug, scope.signal)\n const converter = createMediaConverter(logger, post.signal)\n\n // Self-reference inside `onTick` is safe: the monitor calls it from\n // `start()`, never during construction.\n let monitor: PollingMonitor\n monitor = createPollingMonitor({\n intervalMinutes: cfg.interval,\n signal: scope.signal,\n logger,\n onTick: () => tick({ client, monitor, scope, post, converter }),\n })\n running = { monitor, http, scope }\n\n setState({ state: \"polling\" })\n await monitor.start()\n }\n\n async function stop(): Promise<void> {\n if (status.state === \"stopped\") {\n logger.warn(`stop() ignored: already stopped`)\n return\n }\n logger.info(\"Stopping recorder...\")\n running?.scope.abort(\"user\")\n\n const grace = setTimeout(() => postScope?.abort(\"stop-timeout\"), POST_REMUX_GRACE_MS)\n try {\n const job = currentJob\n if (job) {\n logger.info(\"Waiting for active recording to finish...\")\n await job.finish()\n }\n\n if (running) await running.monitor.stop()\n } finally {\n clearTimeout(grace)\n }\n if (running) await running.http.close()\n emitter.clear()\n setState({ state: \"stopped\" })\n logger.info(\"Recorder stopped\")\n }\n\n return {\n start,\n stop,\n getStatus: () => ({ ...status }),\n on: emitter.on,\n off: emitter.off,\n }\n}\n\n/** Say once, up front, that a routing hint from the config is being ignored. */\nfunction warnStaleCookies(\n cookies: Record<string, string> | undefined,\n logger: { warn: (msg: string) => void },\n): void {\n const { stale } = splitCookies(cookies ?? {})\n if (stale.length === 0) return\n logger.warn(\n `Ignoring ${stale.join(\" and \")}: TikTok computes those per session, and a stale value makes the room API look like a private room`,\n )\n}\n\nfunction lastSource(verdict: ReturnType<typeof verdictOf>): string {\n return (\n [...verdict.evidence].reverse().find((e) => e.outcome === \"hit\" || e.outcome === \"denied\")\n ?.source ?? \"none\"\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA8BA,MAAM,sBAAsB,MAAU;AAkBtC,SAAgB,eAAe,QAA4C;CACzE,MAAM,MAAM,cAAc,MAAM;CAChC,MAAM,SAAS,aAAa;EAC1B,OAAO,IAAI;EACX,SAAS;EACT,SAAS,IAAI;CACf,CAAC;CAGD,MAAM,MAAM,IAAI,aAAa;CAC7B,MAAM,UAAU;EACd,IAAI,IAAI,GAAG,KAAK,GAAG;EACnB,KAAK,IAAI,IAAI,KAAK,GAAG;EACrB,OACE,OACA,GAAG,SACM;GACT,IAAI;IACF,IAAI,KAAK,OAAO,GAAG,IAAI;GACzB,QAAQ,CAER;EACF;EACA,aAAa,IAAI,mBAAmB;CACtC;CAGA,MAAM,SAAyB;EAAE,OAAO;EAAQ,MAAM,IAAI;CAAK;CAC/D,IAAI,UAA0B;CAC9B,IAAI,YAAoC;CACxC,IAAI,aAAkC;CACtC,IAAI,cAAc;CAClB,IAAI,oBAAoB;CAExB,SAAS,SAAS,SAAwC;EACxD,MAAM,OAAO,OAAO;EACpB,OAAO,OAAO,QAAQ,OAAO;EAC7B,IAAI,QAAQ,UAAU,KAAA,KAAa,QAAQ,UAAU,MAAM;GACzD,OAAO,KAAK,UAAU,KAAK,KAAK,QAAQ,OAAO;GAC/C,IAAI,QAAQ,UAAU,WAAW,OAAO,gCAAe,IAAI,KAAK,E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WAAW,GAAG;CACxB,OAAO,KACL,YAAY,MAAM,KAAK,OAAO,EAAE,mGAClC;AACF;AAEA,SAAS,WAAW,SAA+C;CACjE,OACE,CAAC,GAAG,QAAQ,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM,MAAM,EAAE,YAAY,SAAS,EAAE,YAAY,QAAQ,CAAC,EACtF,UAAU;AAElB"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { TikTokError, TikTokErrorCode } from "./core/errors.mjs";
|
|
2
2
|
import { Evidence, EvidenceOutcome, LiveReason, RoomRef, SourceId, StreamRef, Verdict, isLiveReason } from "./core/verdict.mjs";
|
|
3
|
+
import { splitCookies } from "./io/http.mjs";
|
|
3
4
|
import { LogLevel, Phase, ProgressEvent, RecordEvent, RecordedFile, RecorderConfig, RecorderController, RecorderEvent, RecorderEventHandler, RecorderStatus } from "./app/config.mjs";
|
|
4
5
|
import { createRecorder } from "./app/recorder.mjs";
|
|
5
6
|
import { bytesToHuman, formatDuration, relativeTime, sanitizeUser } from "./core/format.mjs";
|
|
6
|
-
export { type Evidence, type EvidenceOutcome, type LiveReason, type LogLevel, type Phase, type ProgressEvent, type RecordEvent, type RecordedFile, type RecorderConfig, type RecorderController, type RecorderEvent, type RecorderEventHandler, type RecorderStatus, type RoomRef, type SourceId, type StreamRef, TikTokError, type TikTokErrorCode, type Verdict, bytesToHuman, createRecorder, formatDuration, isLiveReason, relativeTime, sanitizeUser };
|
|
7
|
+
export { type Evidence, type EvidenceOutcome, type LiveReason, type LogLevel, type Phase, type ProgressEvent, type RecordEvent, type RecordedFile, type RecorderConfig, type RecorderController, type RecorderEvent, type RecorderEventHandler, type RecorderStatus, type RoomRef, type SourceId, type StreamRef, TikTokError, type TikTokErrorCode, type Verdict, bytesToHuman, createRecorder, formatDuration, isLiveReason, relativeTime, sanitizeUser, splitCookies };
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import { isLiveReason } from "./core/verdict.mjs";
|
|
2
1
|
import { TikTokError } from "./core/errors.mjs";
|
|
2
|
+
import { splitCookies } from "./io/http.mjs";
|
|
3
|
+
import "./app/config.mjs";
|
|
4
|
+
import { isLiveReason } from "./core/verdict.mjs";
|
|
3
5
|
import { bytesToHuman, formatDuration, relativeTime, sanitizeUser } from "./core/format.mjs";
|
|
4
6
|
import { createRecorder } from "./app/recorder.mjs";
|
|
5
|
-
export { TikTokError, bytesToHuman, createRecorder, formatDuration, isLiveReason, relativeTime, sanitizeUser };
|
|
7
|
+
export { TikTokError, bytesToHuman, createRecorder, formatDuration, isLiveReason, relativeTime, sanitizeUser, splitCookies };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
//#region src/io/http.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Split configured cookies into the ones we may send and the ones TikTok owns.
|
|
4
|
+
* `stale` is non-empty whenever the config carries a hint we are ignoring, so
|
|
5
|
+
* the caller can say so instead of silently dropping it.
|
|
6
|
+
*/
|
|
7
|
+
declare function splitCookies(cookies: Record<string, string>): {
|
|
8
|
+
seed: [string, string][];
|
|
9
|
+
stale: string[];
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { splitCookies };
|
|
13
|
+
//# sourceMappingURL=http.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.d.mts","names":[],"sources":["../../src/io/http.ts"],"mappings":";;;;;;iBAyDgB,YAAA,CAAa,OAAA,EAAS,MAAA;EACpC,IAAA;EACA,KAAA;AAAA"}
|
package/dist/io/http.mjs
CHANGED
|
@@ -21,17 +21,45 @@ const BROWSER_HEADERS = {
|
|
|
21
21
|
"Sec-Fetch-Site": "none",
|
|
22
22
|
"Sec-Fetch-User": "?1"
|
|
23
23
|
};
|
|
24
|
+
/**
|
|
25
|
+
* Routing hints TikTok computes per session: the datacentre hint and its
|
|
26
|
+
* signature. Sent by hand a value from a config file is stale by definition,
|
|
27
|
+
* and `tt-target-idc=useast2a` makes `room/info` answer 4003110 — the same
|
|
28
|
+
* refusal an age-restricted room returns, so the failure reads as a private
|
|
29
|
+
* room. Measured against tokgo (`internal/tiktok/client.go`), which strips
|
|
30
|
+
* both names for the same reason.
|
|
31
|
+
*/
|
|
32
|
+
const SERVER_COOKIES = ["tt-target-idc", "tt-target-idc-sign"];
|
|
33
|
+
/**
|
|
34
|
+
* Split configured cookies into the ones we may send and the ones TikTok owns.
|
|
35
|
+
* `stale` is non-empty whenever the config carries a hint we are ignoring, so
|
|
36
|
+
* the caller can say so instead of silently dropping it.
|
|
37
|
+
*/
|
|
38
|
+
function splitCookies(cookies) {
|
|
39
|
+
const seed = [];
|
|
40
|
+
const stale = [];
|
|
41
|
+
for (const entry of Object.entries(cookies)) if (SERVER_COOKIES.includes(entry[0])) stale.push(entry[0]);
|
|
42
|
+
else seed.push(entry);
|
|
43
|
+
return {
|
|
44
|
+
seed,
|
|
45
|
+
stale
|
|
46
|
+
};
|
|
47
|
+
}
|
|
24
48
|
async function createHttpClient(config) {
|
|
25
49
|
const session = await createSession({
|
|
26
50
|
browser: "firefox_149",
|
|
27
51
|
os: "windows",
|
|
28
52
|
proxy: config.proxy
|
|
29
53
|
});
|
|
30
|
-
if (config.cookies && "sessionid_ss" in config.cookies)
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
54
|
+
if (config.cookies && "sessionid_ss" in config.cookies) {
|
|
55
|
+
const domains = [
|
|
56
|
+
"https://www.tiktok.com",
|
|
57
|
+
"https://webcast.tiktok.com",
|
|
58
|
+
"https://m.tiktok.com"
|
|
59
|
+
];
|
|
60
|
+
const { seed } = splitCookies(config.cookies);
|
|
61
|
+
for (const domain of domains) for (const [name, value] of seed) session.setCookie(name, value, domain);
|
|
62
|
+
}
|
|
35
63
|
const minIntervalMs = config.ratePerSecond ? 1e3 / config.ratePerSecond : 0;
|
|
36
64
|
let lastTokenTime = 0;
|
|
37
65
|
/** Wait for the next rate-limit token, abort-aware so a stop does not wait one out. */
|
|
@@ -85,6 +113,6 @@ async function createHttpClient(config) {
|
|
|
85
113
|
};
|
|
86
114
|
}
|
|
87
115
|
//#endregion
|
|
88
|
-
export { createHttpClient };
|
|
116
|
+
export { createHttpClient, splitCookies };
|
|
89
117
|
|
|
90
118
|
//# sourceMappingURL=http.mjs.map
|
package/dist/io/http.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.mjs","names":[],"sources":["../../src/io/http.ts"],"sourcesContent":["/**\n * HTTP — the transport layer in one file: the wreq-js session (TLS fingerprint\n * impersonation, cookie jar, proxy) and the token-bucket rate limiter that\n * keeps polling from tripping TikTok's WAF.\n *\n * This file owns the `HttpClient` contract: it is the seam every adapter and\n * `test/utils/mock-http.ts` implement. There is no second definition.\n */\n\nimport { createSession, type Session } from \"wreq-js\"\nimport type { RecorderConfig } from \"../app/config\"\n\n// BodyInit is only available inside declare module \"bun\" in bun-types, not as a global\n// under the ES2022 lib. We explicitly import it to keep core/ focused on ES2022.\nexport type HttpBody = import(\"bun\").BodyInit\n\nexport interface HttpClient {\n get: (url: string, signal?: AbortSignal) => Promise<Response>\n post: (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) => Promise<Response>\n close: () => Promise<void>\n}\n\nconst REQUEST_TIMEOUT_MS = 15_000\n\n/** Standard browser headers to avoid TikTok WAF detection. */\nconst BROWSER_HEADERS: Record<string, string> = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n Accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n}\n\nexport async function createHttpClient(config: RecorderConfig): Promise<HttpClient> {\n const session: Session = await createSession({\n browser: \"firefox_149\",\n os: \"windows\",\n proxy: config.proxy,\n })\n\n // Seed cookies into the session jar so all subsequent requests are authenticated.\n // NOTE: Using a Cookie header does NOT populate wreq-js's cookie jar —\n // we must use session.setCookie() instead.\n // Seed for all TikTok domains since cookies may not propagate across\n // subdomains automatically in wreq-js's cookie jar.\n if (config.cookies && \"sessionid_ss\" in config.cookies) {\n const domains = [\"https://www.tiktok.com\", \"https://webcast.tiktok.com\", \"https://m.tiktok.com\"]\n for (const domain of domains) {\n for (const [name, value] of
|
|
1
|
+
{"version":3,"file":"http.mjs","names":[],"sources":["../../src/io/http.ts"],"sourcesContent":["/**\n * HTTP — the transport layer in one file: the wreq-js session (TLS fingerprint\n * impersonation, cookie jar, proxy) and the token-bucket rate limiter that\n * keeps polling from tripping TikTok's WAF.\n *\n * This file owns the `HttpClient` contract: it is the seam every adapter and\n * `test/utils/mock-http.ts` implement. There is no second definition.\n */\n\nimport { createSession, type Session } from \"wreq-js\"\nimport type { RecorderConfig } from \"../app/config\"\n\n// BodyInit is only available inside declare module \"bun\" in bun-types, not as a global\n// under the ES2022 lib. We explicitly import it to keep core/ focused on ES2022.\nexport type HttpBody = import(\"bun\").BodyInit\n\nexport interface HttpClient {\n get: (url: string, signal?: AbortSignal) => Promise<Response>\n post: (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) => Promise<Response>\n close: () => Promise<void>\n}\n\nconst REQUEST_TIMEOUT_MS = 15_000\n\n/** Standard browser headers to avoid TikTok WAF detection. */\nconst BROWSER_HEADERS: Record<string, string> = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n Accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n}\n\n/**\n * Routing hints TikTok computes per session: the datacentre hint and its\n * signature. Sent by hand a value from a config file is stale by definition,\n * and `tt-target-idc=useast2a` makes `room/info` answer 4003110 — the same\n * refusal an age-restricted room returns, so the failure reads as a private\n * room. Measured against tokgo (`internal/tiktok/client.go`), which strips\n * both names for the same reason.\n */\nexport const SERVER_COOKIES: readonly string[] = [\"tt-target-idc\", \"tt-target-idc-sign\"]\n\n/**\n * Split configured cookies into the ones we may send and the ones TikTok owns.\n * `stale` is non-empty whenever the config carries a hint we are ignoring, so\n * the caller can say so instead of silently dropping it.\n */\nexport function splitCookies(cookies: Record<string, string>): {\n seed: [string, string][]\n stale: string[]\n} {\n const seed: [string, string][] = []\n const stale: string[] = []\n for (const entry of Object.entries(cookies)) {\n if (SERVER_COOKIES.includes(entry[0])) stale.push(entry[0])\n else seed.push(entry)\n }\n return { seed, stale }\n}\n\nexport async function createHttpClient(config: RecorderConfig): Promise<HttpClient> {\n const session: Session = await createSession({\n browser: \"firefox_149\",\n os: \"windows\",\n proxy: config.proxy,\n })\n\n // Seed cookies into the session jar so all subsequent requests are authenticated.\n // NOTE: Using a Cookie header does NOT populate wreq-js's cookie jar —\n // we must use session.setCookie() instead.\n // Seed for all TikTok domains since cookies may not propagate across\n // subdomains automatically in wreq-js's cookie jar.\n if (config.cookies && \"sessionid_ss\" in config.cookies) {\n const domains = [\"https://www.tiktok.com\", \"https://webcast.tiktok.com\", \"https://m.tiktok.com\"]\n const { seed } = splitCookies(config.cookies)\n for (const domain of domains) {\n for (const [name, value] of seed) session.setCookie(name, value, domain)\n }\n }\n\n // Token bucket: a minimum interval between requests. `0` or less is unlimited.\n const minIntervalMs = config.ratePerSecond ? 1000 / config.ratePerSecond : 0\n let lastTokenTime = 0\n\n /** Wait for the next rate-limit token, abort-aware so a stop does not wait one out. */\n async function waitForToken(signal: AbortSignal): Promise<void> {\n if (minIntervalMs <= 0 || signal.aborted) return\n const waitTime = Math.max(0, lastTokenTime + minIntervalMs - Date.now())\n if (waitTime > 0) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, waitTime)\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer)\n resolve()\n },\n { once: true },\n )\n })\n }\n lastTokenTime = Date.now()\n }\n\n async function rateLimitedFetch(\n url: string,\n options?: { method?: string; body?: unknown; headers?: Record<string, string> },\n external?: AbortSignal,\n ): Promise<Response> {\n const controller = new AbortController()\n const onAbort = () => controller.abort(external?.reason)\n if (external?.aborted) controller.abort(external.reason)\n else external?.addEventListener(\"abort\", onAbort, { once: true })\n const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)\n try {\n await waitForToken(controller.signal)\n const res = await session.fetch(url, {\n method: options?.method,\n body: options?.body as never,\n headers: {\n ...BROWSER_HEADERS,\n ...options?.headers,\n },\n signal: controller.signal,\n })\n // SAFETY: wreq-js returns its own Response-compatible object; the port only\n // needs the standard `status`, `ok`, and `text()` surface.\n return res as unknown as Response\n } finally {\n clearTimeout(timeout)\n external?.removeEventListener(\"abort\", onAbort)\n }\n }\n\n return {\n get: async (url: string, signal?: AbortSignal) => rateLimitedFetch(url, undefined, signal),\n post: async (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) =>\n rateLimitedFetch(\n url,\n {\n method: \"POST\",\n body: body as never,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n ...headers,\n },\n },\n signal,\n ),\n close: async () => {\n await session.close()\n },\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,qBAAqB;;AAG3B,MAAM,kBAA0C;CAC9C,cAAc;CACd,QAAQ;CACR,mBA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,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,gBAAgB,WAAW,MAAM,UAAU,MAAM;EACvD,IAAI,UAAU,SAAS,WAAW,MAAM,SAAS,MAAM;OAClD,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAChE,MAAM,UAAU,iBAAiB,WAAW,MAAM,GAAG,kBAAkB;EACvE,IAAI;GACF,MAAM,aAAa,WAAW,MAAM;GAYpC,OAAO,MAXW,QAAQ,MAAM,KAAK;IACnC,QAAQ,SAAS;IACjB,MAAM,SAAS;IACf,SAAS;KACP,GAAG;KACH,GAAG,SAAS;IACd;IACA,QAAQ,WAAW;GACrB,CAAC;EAIH,UAAU;GACR,aAAa,OAAO;GACpB,UAAU,oBAAoB,SAAS,OAAO;EAChD;CACF;CAEA,OAAO;EACL,KAAK,OAAO,KAAa,WAAyB,iBAAiB,KAAK,KAAA,GAAW,MAAM;EACzF,MAAM,OACJ,KACA,MACA,SACA,WAEA,iBACE,KACA;GACE,QAAQ;GACF;GACN,SAAS;IACP,gBAAgB;IAChB,GAAG;GACL;EACF,GACA,MACF;EACF,OAAO,YAAY;GACjB,MAAM,QAAQ,MAAM;EACtB;CACF;AACF"}
|
package/package.json
CHANGED
package/src/app/config.ts
CHANGED
|
@@ -8,11 +8,20 @@ import type { Verdict } from "../core/verdict"
|
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* TikTok cookie key-value pairs extracted from Firefox or cookies.json.
|
|
11
|
-
* Includes session cookies (sessionid_ss
|
|
12
|
-
*
|
|
11
|
+
* Includes session cookies (sessionid_ss) and any WAF bypass cookies needed to
|
|
12
|
+
* avoid Slardar challenges on www.tiktok.com. Routing hints TikTok computes per
|
|
13
|
+
* session (`tt-target-idc`, `tt-target-idc-sign`) are dropped before sending —
|
|
14
|
+
* see `splitCookies` in `io/http.ts`.
|
|
13
15
|
*/
|
|
14
16
|
export type CookieAuth = Record<string, string>
|
|
15
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Re-exported so callers who build `cookies` themselves — the CLI among them —
|
|
20
|
+
* can warn about a hint we refuse to send without hardcoding its name. `io/`
|
|
21
|
+
* is outside the barrel's bands, and this type is the cookie surface.
|
|
22
|
+
*/
|
|
23
|
+
export { splitCookies } from "../io/http"
|
|
24
|
+
|
|
16
25
|
export type LogLevel = "debug" | "info" | "warn" | "error"
|
|
17
26
|
|
|
18
27
|
/**
|
package/src/app/recorder.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
import { EventEmitter } from "node:events"
|
|
12
12
|
import { planTick, type TickFacts } from "../core/plan"
|
|
13
13
|
import { verdictOf } from "../core/verdict"
|
|
14
|
-
import { createHttpClient, type HttpClient } from "../io/http"
|
|
14
|
+
import { createHttpClient, type HttpClient, splitCookies } from "../io/http"
|
|
15
15
|
import { downloadStream } from "../io/media/download"
|
|
16
16
|
import { createMediaConverter, type MediaConverter } from "../io/media/ffmpeg"
|
|
17
17
|
import { createTikTokClient, type TikTokClient } from "../io/tiktok/client"
|
|
@@ -223,6 +223,7 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
223
223
|
consecutiveErrors = 0
|
|
224
224
|
|
|
225
225
|
logger.info(`Starting recorder for @${cfg.user}`)
|
|
226
|
+
warnStaleCookies(cfg.cookies, logger)
|
|
226
227
|
const http = await createHttpClient(cfg)
|
|
227
228
|
const client = createTikTokClient(http, logger, cfg.debug, scope.signal)
|
|
228
229
|
const converter = createMediaConverter(logger, post.signal)
|
|
@@ -277,6 +278,18 @@ export function createRecorder(config: RecorderConfig): RecorderController {
|
|
|
277
278
|
}
|
|
278
279
|
}
|
|
279
280
|
|
|
281
|
+
/** Say once, up front, that a routing hint from the config is being ignored. */
|
|
282
|
+
function warnStaleCookies(
|
|
283
|
+
cookies: Record<string, string> | undefined,
|
|
284
|
+
logger: { warn: (msg: string) => void },
|
|
285
|
+
): void {
|
|
286
|
+
const { stale } = splitCookies(cookies ?? {})
|
|
287
|
+
if (stale.length === 0) return
|
|
288
|
+
logger.warn(
|
|
289
|
+
`Ignoring ${stale.join(" and ")}: TikTok computes those per session, and a stale value makes the room API look like a private room`,
|
|
290
|
+
)
|
|
291
|
+
}
|
|
292
|
+
|
|
280
293
|
function lastSource(verdict: ReturnType<typeof verdictOf>): string {
|
|
281
294
|
return (
|
|
282
295
|
[...verdict.evidence].reverse().find((e) => e.outcome === "hit" || e.outcome === "denied")
|
package/src/index.ts
CHANGED
|
@@ -23,6 +23,7 @@ export type {
|
|
|
23
23
|
RecorderEventHandler,
|
|
24
24
|
RecorderStatus,
|
|
25
25
|
} from "./app/config"
|
|
26
|
+
export { splitCookies } from "./app/config"
|
|
26
27
|
export { createRecorder } from "./app/recorder"
|
|
27
28
|
export type { TikTokErrorCode } from "./core/errors"
|
|
28
29
|
export { TikTokError } from "./core/errors"
|
package/src/io/http.ts
CHANGED
|
@@ -40,6 +40,34 @@ const BROWSER_HEADERS: Record<string, string> = {
|
|
|
40
40
|
"Sec-Fetch-User": "?1",
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Routing hints TikTok computes per session: the datacentre hint and its
|
|
45
|
+
* signature. Sent by hand a value from a config file is stale by definition,
|
|
46
|
+
* and `tt-target-idc=useast2a` makes `room/info` answer 4003110 — the same
|
|
47
|
+
* refusal an age-restricted room returns, so the failure reads as a private
|
|
48
|
+
* room. Measured against tokgo (`internal/tiktok/client.go`), which strips
|
|
49
|
+
* both names for the same reason.
|
|
50
|
+
*/
|
|
51
|
+
export const SERVER_COOKIES: readonly string[] = ["tt-target-idc", "tt-target-idc-sign"]
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Split configured cookies into the ones we may send and the ones TikTok owns.
|
|
55
|
+
* `stale` is non-empty whenever the config carries a hint we are ignoring, so
|
|
56
|
+
* the caller can say so instead of silently dropping it.
|
|
57
|
+
*/
|
|
58
|
+
export function splitCookies(cookies: Record<string, string>): {
|
|
59
|
+
seed: [string, string][]
|
|
60
|
+
stale: string[]
|
|
61
|
+
} {
|
|
62
|
+
const seed: [string, string][] = []
|
|
63
|
+
const stale: string[] = []
|
|
64
|
+
for (const entry of Object.entries(cookies)) {
|
|
65
|
+
if (SERVER_COOKIES.includes(entry[0])) stale.push(entry[0])
|
|
66
|
+
else seed.push(entry)
|
|
67
|
+
}
|
|
68
|
+
return { seed, stale }
|
|
69
|
+
}
|
|
70
|
+
|
|
43
71
|
export async function createHttpClient(config: RecorderConfig): Promise<HttpClient> {
|
|
44
72
|
const session: Session = await createSession({
|
|
45
73
|
browser: "firefox_149",
|
|
@@ -54,10 +82,9 @@ export async function createHttpClient(config: RecorderConfig): Promise<HttpClie
|
|
|
54
82
|
// subdomains automatically in wreq-js's cookie jar.
|
|
55
83
|
if (config.cookies && "sessionid_ss" in config.cookies) {
|
|
56
84
|
const domains = ["https://www.tiktok.com", "https://webcast.tiktok.com", "https://m.tiktok.com"]
|
|
85
|
+
const { seed } = splitCookies(config.cookies)
|
|
57
86
|
for (const domain of domains) {
|
|
58
|
-
for (const [name, value] of
|
|
59
|
-
session.setCookie(name, value, domain)
|
|
60
|
-
}
|
|
87
|
+
for (const [name, value] of seed) session.setCookie(name, value, domain)
|
|
61
88
|
}
|
|
62
89
|
}
|
|
63
90
|
|