// INSTAGRAM'S GUARD (jobs/instagramGuard.ts) and its place in the network // guard's per-platform table (jobs/networkGuard.ts PLATFORM_GUARDS): the alert // refuses every Instagram job until a person's Recheck, the cooldown refuses // until it ends, and X's guard is the function it was. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/instagramGuard.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "instagram-guard-")); process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ social: { x: { cookieSource: "profile" } } })); const { getPaths } = await import("../lib/paths"); const { guardNetworkJob, PLATFORM_GUARDS } = await import("./networkGuard"); const { instagramJobGuard, instagramCooldownSentence, INSTAGRAM_RATE_LIMIT_HOLD_MS } = await import("./instagramGuard"); const { noteInstagramServiceOutcome, readServiceCookieState, raisedServiceAlert } = await import("../lib/serviceCookies-server"); const { buildServiceCookieAlerts, isServiceKey, serviceFamily, serviceLabel, INSTAGRAM_SERVICE } = await import("../lib/serviceCookies"); const { recheckServiceCookies } = await import("../controller/recheckServiceCookies"); const { recordPlatformCooldown, platformCooldownRemainingMs } = await import("./downloadBackoff"); const paths = getPaths(); const channels = path.join(paths.transcriptsDir, "channels"); async function channel(slug: string, platform: string, url: string): Promise { await mkdir(path.join(channels, slug), { recursive: true }); await writeFile( path.join(channels, slug, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", platform, name: slug, url }), ); } await channel("example-ig", "instagram", "https://www.instagram.com/example.account/"); await channel("example-sky", "bluesky", "https://bsky.app/profile/example.bsky.social"); await channel("example-x", "twitter", "https://x.com/example"); test.after(async () => { await rm(ROOT, { recursive: true, force: true }); }); const ig = (job?: { id: string }) => guardNetworkJob({ kind: "fetch-posts", queueKey: "platform:instagram", paths, channelSlug: "example-ig", ...(job ? { job } : {}) }); test("the table names X and Instagram, and nothing else", () => { assert.deepEqual(Object.keys(PLATFORM_GUARDS).sort(), ["instagram", "twitter"]); assert.ok(isServiceKey(INSTAGRAM_SERVICE)); assert.equal(serviceFamily(INSTAGRAM_SERVICE), "instagram"); assert.equal(serviceLabel(INSTAGRAM_SERVICE), "Instagram"); // X's and the others' families are what they were. assert.equal(serviceFamily("x"), "x"); assert.equal(serviceFamily("rumble"), "ytdlp"); assert.equal(serviceFamily("forum.example"), "forum"); }); test("with no alert and no cooldown an Instagram job starts; a platform with no guard is not asked", async () => { assert.deepEqual(await ig(), { ok: true, notes: [] }); assert.deepEqual( await guardNetworkJob({ kind: "fetch-posts", queueKey: "platform:bluesky", paths, channelSlug: "example-sky" }), { ok: true, notes: [] }, ); // A name on Object.prototype is not a platform with a guard. assert.deepEqual(await guardNetworkJob({ kind: "fetch-posts", queueKey: "platform:constructor", paths }), { ok: true, notes: [] }); }); test("an Instagram job is never run unqueued either", async () => { const r = await guardNetworkJob({ kind: "fetch-posts", queueKey: "", paths, channelSlug: "example-ig" }); assert.equal(r.ok, false); }); test("a challenge raises Instagram's alert: every Instagram job is refused, at enqueue and at start, until a person's Recheck", async () => { await noteInstagramServiceOutcome(paths, { challengeLine: "[instagram][error] HTTP redirect to challenge page (https://www.instagram.com/challenge/)", kind: "challenge", channel: "example-ig", }); assert.ok(await raisedServiceAlert(paths, INSTAGRAM_SERVICE)); const atEnqueue = await ig(); assert.equal(atEnqueue.ok, false); assert.match((atEnqueue as { error: string }).error, /Instagram answered with a challenge or checkpoint page/); assert.match((atEnqueue as { error: string }).error, /no Instagram job starts/); assert.match((atEnqueue as { error: string }).error, /Recheck sends Instagram no request/); // Whatever queue it was moved to: the channel's platform decides. const moved = await guardNetworkJob({ kind: "capture-posts", queueKey: "somewhere", paths, channelSlug: "example-ig" }); assert.equal(moved.ok, false); // Refused at its start: recorded against the alert for "Re-run stopped jobs". assert.equal((await ig({ id: "job-7" })).ok, false); const entry = (await readServiceCookieState(paths)).services[INSTAGRAM_SERVICE]!; assert.deepEqual(entry.jobs.map((j) => j.id), ["job-7"]); // A clean answer cannot be what clears it (no job runs), and the banner offers Recheck. const view = buildServiceCookieAlerts(await readServiceCookieState(paths), { now: Date.now() }); const alert = view.alerts.find((a) => a.service === INSTAGRAM_SERVICE)!; assert.equal(alert.state, "stale"); assert.equal(alert.canRecheck, true); // Bluesky is not Instagram's business. assert.equal((await guardNetworkJob({ kind: "fetch-posts", queueKey: "platform:bluesky", paths, channelSlug: "example-sky" })).ok, true); // The operator's Recheck: no request, the alert cleared, jobs start again. const out = await recheckServiceCookies({ paths, service: INSTAGRAM_SERVICE }); assert.equal(out.result, "clean"); assert.match(out.message, /no request sent/); assert.equal(await raisedServiceAlert(paths, INSTAGRAM_SERVICE), null); assert.deepEqual(await ig(), { ok: true, notes: [] }); // A Recheck with no alert up says so and changes nothing. assert.match((await recheckServiceCookies({ paths, service: INSTAGRAM_SERVICE })).message, /no cookie alert up/); }); test("a login redirect raises it as a login failure", async () => { await noteInstagramServiceOutcome(paths, { challengeLine: "HTTP redirect to login page", kind: "auth-failure" }); const r = await ig(); assert.equal(r.ok, false); assert.match((r as { error: string }).error, /its login page/); await recheckServiceCookies({ paths, service: INSTAGRAM_SERVICE }); }); test("the 60-minute cooldown refuses every Instagram job until it ends, and says when", async () => { assert.equal(INSTAGRAM_RATE_LIMIT_HOLD_MS, 60 * 60_000); await recordPlatformCooldown("instagram", INSTAGRAM_RATE_LIMIT_HOLD_MS, paths); const left = await platformCooldownRemainingMs("instagram", paths); assert.ok(left > 59 * 60_000 && left <= 60 * 60_000); const r = await ig(); assert.equal(r.ok, false); assert.match((r as { error: string }).error, /Instagram answered a rate limit/); assert.match((r as { error: string }).error, /nothing retries by itself/); // Not an alert: nothing is recorded for "Re-run stopped jobs". await ig({ id: "job-9" }); assert.equal((await readServiceCookieState(paths)).services[INSTAGRAM_SERVICE]?.jobs.some((j) => j.id === "job-9") ?? false, false); // The cooldown is Instagram's alone. assert.equal(await platformCooldownRemainingMs("twitter", paths), 0); }); test("a cooldown that cannot be read refuses: the guard fails closed", async () => { const r = await instagramJobGuard({ paths, deps: { raisedAlert: async () => null, cooldownMs: async () => { throw new Error("EACCES: the state file (invented)"); }, }, }); assert.equal(r.ok, false); assert.match((r as { message: string }).message, /could not be read \(EACCES: the state file \(invented\)\): no Instagram job starts/); }); test("ONE 401/403 is pending and refuses nothing; a SECOND with no clean read between raises the alert; a clean read between forgets the first", async () => { const refuse = () => noteInstagramServiceOutcome(paths, { challengeLine: "HttpError: '401 Unauthorized' for '…'", kind: "refusal", channel: "example-ig" }); await refuse(); assert.equal(await raisedServiceAlert(paths, INSTAGRAM_SERVICE), null, "one refusal is the hour's hold, not the alert"); assert.equal((await readServiceCookieState(paths)).services[INSTAGRAM_SERVICE]?.kind, "refusal"); // A clean read between: forgotten. await noteInstagramServiceOutcome(paths, { url: "https://www.instagram.com/example.account/" }); assert.equal((await readServiceCookieState(paths)).services[INSTAGRAM_SERVICE], undefined); await refuse(); assert.equal(await raisedServiceAlert(paths, INSTAGRAM_SERVICE), null); // The second in a row, hours later (the hold between them is an hour): the alert. await refuse(); const raised = await raisedServiceAlert(paths, INSTAGRAM_SERVICE); assert.equal(raised?.kind, "refusal"); const r = await instagramJobGuard({ paths, deps: { cooldownMs: async () => 0 } }); assert.equal(r.ok, false); assert.match((r as { message: string }).message, /a second refusal \(401\/403\) in a row/); await recheckServiceCookies({ paths, service: INSTAGRAM_SERVICE }); }); test("the guard's two answers, with injected state", async () => { const now = Date.parse("2026-01-02T03:00:00Z"); assert.deepEqual(await instagramJobGuard({ paths, now, deps: { raisedAlert: async () => null, cooldownMs: async () => 0 } }), { ok: true }); const cooling = await instagramJobGuard({ paths, now, deps: { raisedAlert: async () => null, cooldownMs: async () => 30 * 60_000 } }); assert.deepEqual(cooling, { ok: false, message: instagramCooldownSentence(30 * 60_000, now), alert: false }); assert.match(instagramCooldownSentence(30 * 60_000, now), /before 03:30 UTC \(30 min from now\)/); });