commit eeba5f63da8a3f2ff10d448072635710df72ff58
parent 934ff4d4954ec7e8625df05e530c42809b71e9cc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 25 Oct 2026 22:17:04 -0400
pnpm ops get x-session: the X login an X job would use, the jar's age, the limit and whether one would start now, from the check that refuses a stale-cookie X job
xSessionReport (common/jobs/networkGuard.ts) is the fresh-jar rule's inputs
and verdict in one record; xJobGuard now answers from it, so the report and
the refusal are one computation. GET /api/ops/x-session[?slug=] serves it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
6 files changed, 187 insertions(+), 25 deletions(-)
diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts
@@ -32,7 +32,12 @@ import {
noteServiceStoppedJob,
raisedServiceAlert,
} from "../lib/serviceCookies-server";
-import { readXSessionStatus, type XSessionStatus } from "../social/xSessionBroker";
+import {
+ readXSessionStatus,
+ xCookieFile,
+ xProfileDir,
+ type XSessionStatus,
+} from "../social/xSessionBroker";
import { resolveXCookieSource, xMaxCookieAgeMinutes, type XCookieSource } from "../social/xCookieSource";
import { jobKindLabel, kindIsNetwork } from "./jobKinds";
import { queueGapPlatform } from "./queueGap";
@@ -166,38 +171,96 @@ export type XGuardResult =
| { ok: true; note?: string }
| { ok: false; message: string; alert: boolean };
-export async function xJobGuard(opts: {
+// WHAT AN X JOB WOULD BE TOLD NOW, and why — the fresh-jar rule's inputs and
+// its verdict in one record, for `pnpm ops get x-session` (an agent asks it
+// before it queues an X fetch). xJobGuard below is this record's verdict, so
+// the report and the refusal are one computation, not two that look alike.
+export type XSessionReport = {
+ // The login source in use ("profile": the session broker's exported jar;
+ // "browser": cookiesFromBrowser), and whether settings chose it.
+ source: XCookieSource;
+ sourceChosen: boolean;
+ browserSpec?: string;
+ profileDir: string;
+ cookieFile: string;
+ hasProfile: boolean;
+ hasCookies: boolean;
+ looksAuthenticated: boolean;
+ // When the jar was last written (Connect X / Refresh cookies), and its age.
+ cookiesUpdatedAt: string | null;
+ ageMinutes: number | null;
+ // social.x.maxCookieAgeMinutes, resolved (0 = off).
+ maxAgeMinutes: number;
+ // False when the age is not checked: the browser source, or a limit of 0.
+ ageChecked: boolean;
+ // The X cookie alert, when it is up (a challenge or a login wall).
+ alert: { raisedAt: string; line: string } | null;
+ // Would an X job start now? `reason` is the refusal it would get.
+ allowed: boolean;
+ reason: string | null;
+ note?: string;
+};
+
+export async function xSessionReport(opts: {
paths: Paths;
channelSlug?: string;
now?: number;
-}): Promise<XGuardResult> {
+}): Promise<XSessionReport> {
const now = opts.now ?? Date.now();
- const alert = await raisedServiceAlert(opts.paths, X_SERVICE);
- if (alert) {
- const at = (alert.raisedAt ?? alert.since).slice(11, 16);
- return {
- ok: false,
- alert: true,
- message:
- `X answered with a challenge at ${at} UTC (${alert.evidence.line}) and its cookie alert is up, ` +
- `so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`,
- };
- }
- const settings = settingsNow();
- if (!settings) return { ok: true };
const status = await readXSessionStatus(opts.paths);
+ const settings = settingsNow();
const resolved = resolveXCookieSource({
- stored: settings.social?.x?.cookieSource,
- browserSpec: await channelCookieSpec(opts.paths, opts.channelSlug, settings),
+ stored: settings?.social?.x?.cookieSource,
+ browserSpec: settings ? await channelCookieSpec(opts.paths, opts.channelSlug, settings) : undefined,
profileConnected: status.looksAuthenticated,
});
- const verdict = xJarVerdict({
+ const maxAgeMinutes =
+ settings?.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings?.social?.x);
+ const ageMinutes = status.cookiesUpdatedAt
+ ? Math.max(0, Math.floor((now - Date.parse(status.cookiesUpdatedAt)) / 60_000))
+ : null;
+ const base = {
source: resolved.source,
- status,
- maxAgeMinutes: settings.social?.x?.maxCookieAgeMinutes ?? e2eDefaultMaxAge() ?? xMaxCookieAgeMinutes(settings.social?.x),
- now,
- });
- return verdict.ok ? verdict : { ok: false, message: verdict.message, alert: false };
+ sourceChosen: resolved.chosen,
+ ...(resolved.browserSpec ? { browserSpec: resolved.browserSpec } : {}),
+ profileDir: xProfileDir(opts.paths),
+ cookieFile: xCookieFile(opts.paths),
+ hasProfile: status.hasProfile,
+ hasCookies: status.hasCookies,
+ looksAuthenticated: status.looksAuthenticated,
+ cookiesUpdatedAt: status.cookiesUpdatedAt ?? null,
+ ageMinutes,
+ maxAgeMinutes,
+ ageChecked: resolved.source === "profile" && maxAgeMinutes > 0,
+ };
+ const raised = await raisedServiceAlert(opts.paths, X_SERVICE);
+ if (raised) {
+ const at = (raised.raisedAt ?? raised.since).slice(11, 16);
+ return {
+ ...base,
+ alert: { raisedAt: raised.raisedAt ?? raised.since, line: raised.evidence.line },
+ allowed: false,
+ reason:
+ `X answered with a challenge at ${at} UTC (${raised.evidence.line}) and its cookie alert is up, ` +
+ `so no X job starts: ${serviceFixText(X_SERVICE, configuredCookieBrowser())}, then Recheck on the dashboard.`,
+ };
+ }
+ // Settings unreadable: the guard has nothing to apply and lets the job run.
+ if (!settings) return { ...base, alert: null, allowed: true, reason: null };
+ const verdict = xJarVerdict({ source: resolved.source, status, maxAgeMinutes, now });
+ return verdict.ok
+ ? { ...base, alert: null, allowed: true, reason: null, ...(verdict.note ? { note: verdict.note } : {}) }
+ : { ...base, alert: null, allowed: false, reason: verdict.message };
+}
+
+export async function xJobGuard(opts: {
+ paths: Paths;
+ channelSlug?: string;
+ now?: number;
+}): Promise<XGuardResult> {
+ const r = await xSessionReport(opts);
+ if (r.allowed) return r.note ? { ok: true, note: r.note } : { ok: true };
+ return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null };
}
// ── the one entry point ────────────────────────────────────────────────────
diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts
@@ -234,6 +234,32 @@ test("a stale jar is refused at enqueue, and at the start of a job queued while
assert.match(c.ok ? "" : c.error, /holds no login/);
});
+test("get x-session reports what the guard would answer: source, age, limit, allowed", async () => {
+ await reset();
+ const { xSessionReport, xJobGuard } = await import("./networkGuard");
+ await writeJar(5 * 60_000);
+ const fresh = await xSessionReport({ paths });
+ assert.equal(fresh.source, "profile");
+ assert.equal(fresh.sourceChosen, true);
+ assert.equal(fresh.looksAuthenticated, true);
+ assert.equal(fresh.maxAgeMinutes, 60);
+ assert.equal(fresh.ageChecked, true);
+ assert.ok(fresh.ageMinutes !== null && fresh.ageMinutes >= 4 && fresh.ageMinutes <= 6, String(fresh.ageMinutes));
+ assert.equal(fresh.allowed, true);
+ assert.equal(fresh.reason, null);
+ assert.equal(fresh.profileDir, path.join(transcripts, ".x-session", "profile"));
+ assert.deepEqual(await xJobGuard({ paths }), { ok: true });
+
+ await writeJar(2 * 60 * 60_000);
+ const stale = await xSessionReport({ paths });
+ assert.equal(stale.allowed, false);
+ assert.ok(stale.ageMinutes !== null && stale.ageMinutes >= 119);
+ assert.match(stale.reason ?? "", /^X cookies were last refreshed 2 h ago \(limit 60 min\)/);
+ const guard = await xJobGuard({ paths });
+ assert.equal(guard.ok, false);
+ assert.equal(guard.ok ? "" : guard.message, stale.reason);
+});
+
test("a network job is never run unqueued: the override \"\" is refused", async () => {
await reset();
await writeJar(60_000);
diff --git a/editor/app/api/ops/_read.test.ts b/editor/app/api/ops/_read.test.ts
@@ -46,7 +46,7 @@ const route = async (name: string) => (await import(`./${name}/route`)).GET as G
test.after(() => corpus.cleanup());
test("every read route is behind the token", async () => {
- for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler", "saved-alternates"]) {
+ for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler", "saved-alternates", "x-session"]) {
const res = await callGet(await route(name), undefined, {}, {});
assert.equal(res.status, 401, name);
}
@@ -147,6 +147,24 @@ test("get saved-alternates lists the saved videos holding two copies (none here)
assert.equal(bad.status, 400);
});
+test("get x-session answers the X login and the guard's verdict: no jar here, so an X job would be refused", async () => {
+ const get = await route("x-session");
+ const res = await callGet(get);
+ assert.equal(res.status, 200, JSON.stringify(res.body));
+ assert.equal(res.body.source, "profile");
+ assert.equal(res.body.hasCookies, false);
+ assert.equal(res.body.ageMinutes, null);
+ assert.equal(typeof res.body.maxAgeMinutes, "number");
+ if ((res.body.maxAgeMinutes as number) > 0) {
+ assert.equal(res.body.allowed, false);
+ assert.match(String(res.body.reason), /No X cookie jar has been exported/);
+ }
+ const bad = await callGet(get, "http://localhost/api/ops/x-session?slug=../x");
+ assert.equal(bad.status, 400);
+ const stray = await callGet(get, "http://localhost/api/ops/x-session?channel=x");
+ assert.equal(stray.status, 400);
+});
+
test("/api/auto-queue/control is behind the ops token now", async () => {
const { POST } = await import("../auto-queue/control/route");
const anon = await callPost(POST, { kind: "download", action: "stop" }, {});
diff --git a/editor/app/api/ops/x-session/route.ts b/editor/app/api/ops/x-session/route.ts
@@ -0,0 +1,27 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { xSessionReport } from "yt-dlp-transcript-common/jobs/networkGuard";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/ops/x-session[?slug=<channel>]
+// -> { ok, source, sourceChosen, browserSpec?, profileDir, cookieFile,
+// hasProfile, hasCookies, looksAuthenticated, cookiesUpdatedAt,
+// ageMinutes, maxAgeMinutes, ageChecked, alert, allowed, reason, note? }
+//
+// The X login an X job would use and whether one would start NOW: the
+// fresh-jar rule's inputs (the source, the exported jar's age, the limit
+// social.x.maxCookieAgeMinutes) and its verdict, from xSessionReport — the
+// record the network guard refuses an X job with (common/jobs/networkGuard.ts).
+// `slug` names a channel whose own cookiesFromBrowser may decide the source.
+// Nothing is asked of X and nothing is written: a refresh is a human click on
+// /settings (Refresh cookies / Connect X account).
+export async function GET(request: Request) {
+ return readRoute(request, ["slug"], async (q) => {
+ const slug = q.get("slug")?.trim() || undefined;
+ if (slug && !isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`);
+ return { ...(await xSessionReport({ paths: getPaths(), channelSlug: slug })) };
+ });
+}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -108,6 +108,7 @@
// pnpm ops fetch-windows --file windows.json --wait
// pnpm ops get tags eva-collab
// pnpm ops get services
+// pnpm ops get x-session
// pnpm ops recheck-service --json '{"service":"rumble"}'
// pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'
// pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait
@@ -259,6 +260,11 @@ const GETTERS = {
// The dashboard's cookie refresh alerts: each service whose cookies look
// stale (or are OK again, with the jobs the alert stopped).
services: () => "/api/ops/services",
+ // The X login an X job would use and whether one would start now: the
+ // source, the exported jar's age, social.x.maxCookieAgeMinutes and the
+ // network guard's verdict (common/jobs/networkGuard.ts xSessionReport).
+ "x-session": (slug) =>
+ slug ? `/api/ops/x-session?slug=${encodeURIComponent(slug)}` : "/api/ops/x-session",
// One channel's cleanup row: what each sweep would reclaim, what holds the rest.
cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`,
// What a channel holds, by date, and its gaps (release 19 A9): each video
@@ -308,6 +314,7 @@ const GET_ARG_OPTIONAL = new Set([
"auto-queue",
"scheduler",
"services",
+ "x-session",
"generation-usage",
]);
@@ -937,6 +944,7 @@ export function usage() {
" pnpm ops get storage | sites | workers | auto-queue | scheduler",
" pnpm ops get saved-alternates [<slug>]",
" pnpm ops get services",
+ " pnpm ops get x-session [<slug>]",
" pnpm ops get cleanup <slug>",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
" pnpm ops get transcript <videoId> [--slug <slug>]",
@@ -988,6 +996,16 @@ export function usage() {
" (rumble, youtube, odysee, archive.today, a forum host) whose cookies look",
" stale, or are OK again with the jobs the alert stopped; \"pending\" lists",
" a first Rumble embed 403 waiting for a second video.",
+ "get x-session [<slug>] is the X login an X job would use and whether one",
+ " would start NOW, from the same check that refuses a stale-cookie X job:",
+ " source (\"profile\": the exported jar under transcripts/.x-session;",
+ " \"browser\": cookiesFromBrowser, whose age cannot be read), hasCookies,",
+ " looksAuthenticated, cookiesUpdatedAt, ageMinutes, maxAgeMinutes",
+ " (social.x.maxCookieAgeMinutes; 0 = off), the X cookie alert if it is up,",
+ " allowed, and reason (the refusal an X job would get). <slug> names a",
+ " channel whose own cookiesFromBrowser may decide the source. Nothing is",
+ " asked of X: a refresh is Refresh cookies / Connect X account on",
+ " /settings. Ask it before queueing fetch-posts or capture-posts on X.",
"get cleanup <slug> is one channel's /cleanup row: what each sweep would",
" reclaim (they overlap — never add them), what holds the rest, and the",
" failed-transcriptions count. measured: false means unknown, not zero.",
diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs
@@ -867,6 +867,16 @@ test("get services is a GET on its route; recheck/dismiss/rerun are POSTs named
}
});
+// X SESSION FRESHNESS: what an agent asks before it queues an X fetch.
+test("get x-session is a GET on its route, with an optional channel", () => {
+ const g = parseArgs(["get", "x-session"]);
+ assert.equal(g.method, "GET");
+ assert.equal(g.path, "/api/ops/x-session");
+ assert.equal(parseArgs(["get", "x-session", "some-x"]).path, "/api/ops/x-session?slug=some-x");
+ assert.match(usage(), /pnpm ops get x-session \[<slug>\]/);
+ assert.match(usage(), /maxAgeMinutes/);
+});
+
// RELEASE 36 LANE A: the clip finder's chain and one video's chat replay.
test("fetch-chat and find-clips are POSTs named in the usage; find-clips --wait carries its marker", () => {
for (const action of ["fetch-chat", "find-clips"]) {