Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 5730b052e1ea9113d3848297fd27bf98198f51a9
parent b4658a0846d9b8726f7214f8ea6b138750d26a27
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 13:43:06 -0500

posts: Instagram posts are private by default, and Instagram has a guard of its own

social.instagram.visibility (absent = private) keeps an Instagram channel out
of every public site, by the rule X's setting uses. The network guard asks a
per-platform table: X's entry is the code it was; Instagram's refuses every
Instagram job while its alert is up (a login, challenge or checkpoint
redirect) and while it cools down after a rate limit (60 min). The alert is
cleared by a person's Recheck, which sends no request; the recheck timer never
asks it.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/controller/recheckServiceCookies.ts | 11+++++++++++
Mcommon/controller/serviceCookieTimer.test.ts | 11+++++++++++
Mcommon/controller/serviceCookieTimer.ts | 3+++
Acommon/jobs/instagramGuard.test.ts | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/instagramGuard.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/networkGuard.ts | 53++++++++++++++++++++++++++++++++++++++++++-----------
Acommon/lib/instagram/visibility.test.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/postsVisibility.ts | 31++++++++++++++++++++++++++++---
Mcommon/lib/serviceCookies-server.ts | 25++++++++++++++++++++++---
Mcommon/lib/serviceCookies.ts | 23++++++++++++++++++++---
Mcommon/lib/settingsDocs.ts | 2++
Mcommon/lib/settingsSchema.ts | 19++++++++++++++++++-
Mcommon/publish/inputSig.ts | 4++++
Mcommon/social/xCookieSource.ts | 30++++++++++++++++++++++++++++++
14 files changed, 473 insertions(+), 21 deletions(-)

diff --git a/common/controller/recheckServiceCookies.ts b/common/controller/recheckServiceCookies.ts @@ -274,6 +274,17 @@ export async function recheckServiceCookies(opts: { `${login.browser ?? "the browser cookiesFromBrowser names"}, pass its check, then Recheck. Recheck sends X no request.`, ); } + case "instagram": { + // THE OPERATOR'S WORD, and no request: nothing on disk says whether + // Instagram's check is passed (slice 1 keeps no Instagram jar), so a + // Recheck is a person saying it is. The timer never comes here + // (serviceCookieTimer.ts holdBack). + if (!entry?.raisedAt || entry.clearedAt) { + return out("clean", `${label} has no cookie alert up. Recheck sends Instagram no request.`); + } + log(`Rechecking ${label}: your word that its check is passed, no request to Instagram.`); + return clean("on your word; no request sent. If the check was not passed, the next Instagram job raises it again"); + } case "archive": { const url = target?.url; if (!url) { diff --git a/common/controller/serviceCookieTimer.test.ts b/common/controller/serviceCookieTimer.test.ts @@ -310,3 +310,14 @@ test("the timer: a tick still in flight when the next is due skips it; the next assert.ok(serviceCookieTimerView().lastTickAt); assert.equal(logs.filter((l) => /still running/.test(l)).length, 0); }); + +test("Instagram's alert is a person's to clear: the timer never rechecks it, raised or listed as a probe", async () => { + const h = harness((s) => { + applyServiceCookieSignal(s, { service: "instagram", kind: "challenge", line: "HTTP redirect to challenge page" }, { channel: "example-ig" }, NOW - 3600_000); + }); + h.deps.settings = () => ({ recheckIntervalMinutes: 180, probeServices: ["instagram"] }); + const actions = await runServiceCookieTick(h.deps); + assert.deepEqual(h.calls, []); + assert.equal(actions.find((a) => a.service === "instagram")?.action, "skipped"); + assert.match(actions.find((a) => a.service === "instagram")?.message ?? "", /person's Recheck only/); +}); diff --git a/common/controller/serviceCookieTimer.ts b/common/controller/serviceCookieTimer.ts @@ -107,6 +107,9 @@ export async function runServiceCookieTick(deps: ServiceCookieTickDeps): Promise // Why a service is not asked now, or null. const holdBack = async (svc: string): Promise<string | null> => { + // Instagram's alert is a person's to clear (Recheck or Dismiss on the + // dashboard): the timer never asks it, alert up or not. + if (serviceFamily(svc) === "instagram") return "Instagram's alert is cleared by a person's Recheck only"; if (rechecking(svc)) return "a recheck of it is already queued or running"; if (serviceFamily(svc) === "ytdlp") { if (busy(svc)) return `a job is queued or running on its queue (its answer is the probe)`; diff --git a/common/jobs/instagramGuard.test.ts b/common/jobs/instagramGuard.test.ts @@ -0,0 +1,140 @@ +// 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<void> { + 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("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\)/); +}); diff --git a/common/jobs/instagramGuard.ts b/common/jobs/instagramGuard.ts @@ -0,0 +1,67 @@ +// INSTAGRAM'S HALF OF THE NETWORK GUARD (lane instagram; jobs/networkGuard.ts +// PLATFORM_GUARDS). Asked of every job aimed at Instagram, at enqueue and +// again at its start: +// +// 1. NOT WHILE ITS ALERT IS UP. A redirect to Instagram's login, challenge +// or checkpoint page raises the Instagram alert (lib/serviceCookies.ts): +// the next request after one is the one that gets an account locked, so +// every Instagram job is refused until a person's Recheck (or Dismiss). +// 2. NOT WHILE IT COOLS DOWN. The first 429 (or "wait a few minutes") ends +// the run that met it and records a 60-minute `instagram` platform +// cooldown (jobs/downloadBackoff.ts recordPlatformCooldown); nothing +// Instagram starts before it ends, and nothing retries by itself. +// +// There is no jar rule here: slice 1 keeps no Instagram jar. + +import type { Paths } from "../lib/paths"; +import { INSTAGRAM_SERVICE, serviceFixText, type ServiceCookieEntry } from "../lib/serviceCookies"; +import { raisedServiceAlert } from "../lib/serviceCookies-server"; +import { platformCooldownRemainingMs } from "./downloadBackoff"; + +export const INSTAGRAM_PLATFORM = "instagram"; + +// How long Instagram is left alone after it answered a rate limit. +export const INSTAGRAM_RATE_LIMIT_HOLD_MS = 60 * 60_000; + +export function instagramCooldownSentence(remainingMs: number, now: number): string { + const until = new Date(now + remainingMs).toISOString().slice(11, 16); + return ( + `Instagram answered a rate limit a short while ago: no Instagram job starts before ${until} UTC ` + + `(${Math.ceil(remainingMs / 60_000)} min from now). Ask again then; nothing retries by itself.` + ); +} + +export function instagramAlertSentence(raised: Pick<ServiceCookieEntry, "kind" | "raisedAt" | "since" | "evidence">): string { + const at = (raised.raisedAt ?? raised.since).slice(11, 16); + const what = raised.kind === "auth-failure" ? "its login page" : "a challenge or checkpoint page"; + return ( + `Instagram answered with ${what} at ${at} UTC (${raised.evidence.line}) and its alert is up, ` + + `so no Instagram job starts: ${serviceFixText(INSTAGRAM_SERVICE)}.` + ); +} + +export type InstagramGuardResult = { ok: true } | { ok: false; message: string; alert: boolean }; + +export type InstagramGuardDeps = { + raisedAlert: (paths: Paths) => Promise<ServiceCookieEntry | null>; + cooldownMs: (paths: Paths) => Promise<number>; +}; + +const DEFAULT_DEPS: InstagramGuardDeps = { + raisedAlert: (paths) => raisedServiceAlert(paths, INSTAGRAM_SERVICE), + cooldownMs: (paths) => platformCooldownRemainingMs(INSTAGRAM_PLATFORM, paths).catch(() => 0), +}; + +export async function instagramJobGuard(opts: { + paths: Paths; + now?: number; + deps?: Partial<InstagramGuardDeps>; +}): Promise<InstagramGuardResult> { + const deps = { ...DEFAULT_DEPS, ...opts.deps }; + const now = opts.now ?? Date.now(); + const raised = await deps.raisedAlert(opts.paths); + if (raised) return { ok: false, message: instagramAlertSentence(raised), alert: true }; + const ms = await deps.cooldownMs(opts.paths); + if (ms > 0) return { ok: false, message: instagramCooldownSentence(ms, now), alert: false }; + return { ok: true }; +} diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts @@ -7,6 +7,10 @@ // 2. X ONLY WHILE NO X ALERT IS UP. A challenge or login wall from X raises // the X cookie alert (lib/serviceCookies.ts); until Recheck or Dismiss // clears it, every job aimed at X is refused before it asks anything. +// INSTAGRAM THE SAME (lane instagram): its alert refuses every Instagram +// job until a person's Recheck, and so does its cooldown after a rate +// limit (jobs/instagramGuard.ts). Which platforms have a guard is ONE +// table, PLATFORM_GUARDS below. // 3. X ONLY ON A FRESH JAR. With the "profile" login source, a job aimed at X // starts only when the exported cookie jar was written within // `social.x.maxCookieAgeMinutes` (default 60; 0 = off) and carries a login. @@ -26,7 +30,8 @@ import { channelConfigSchema } from "../lib/channelConfigSchema"; import { downloadQueueKey } from "../lib/queueKeys"; import { getSettings, type SiteSettings } from "../lib/settings"; import { resolveCookiePolicy } from "../lib/cookiePolicy"; -import { serviceFixText, X_SERVICE } from "../lib/serviceCookies"; +import { INSTAGRAM_SERVICE, serviceFixText, X_SERVICE } from "../lib/serviceCookies"; +import { instagramJobGuard } from "./instagramGuard"; import { configuredCookieBrowser, noteServiceStoppedJob, @@ -279,16 +284,11 @@ export type NetworkGuardResult = | { ok: true; notes: string[] } | { ok: false; error: string }; -// Asked at ENQUEUE (no job yet) and at START (`job` set: a refusal by the X -// alert is recorded against the alert, so "Re-run stopped jobs" offers it). -export async function guardNetworkJob( - opts: NetworkJobOpts & { job?: { id: string } }, -): Promise<NetworkGuardResult> { - if (!kindIsNetwork(opts.kind)) return { ok: true, notes: [] }; - const empty = emptyQueueRefusal(opts.kind, opts.queueKey); - if (empty) return { ok: false, error: empty }; - const platform = await networkJobPlatform(opts); - if (platform !== "twitter") return { ok: true, notes: [] }; +// One platform's guard: asked with the job's options, at enqueue and at start. +type PlatformGuard = (opts: NetworkJobOpts & { job?: { id: string } }) => Promise<NetworkGuardResult>; + +// X's (rules 2 and 3 above). +async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promise<NetworkGuardResult> { const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug }); if (x.ok) { // The jar passed at a job's START: a jar-age banner from an earlier @@ -311,3 +311,34 @@ export async function guardNetworkJob( } return { ok: false, error: x.message }; } + +// Instagram's: its alert, then its cooldown (jobs/instagramGuard.ts). +async function guardInstagramJob(opts: NetworkJobOpts & { job?: { id: string } }): Promise<NetworkGuardResult> { + const g = await instagramJobGuard({ paths: opts.paths }); + if (g.ok) return { ok: true, notes: [] }; + if (g.alert && opts.job) { + await noteServiceStoppedJob(opts.paths, INSTAGRAM_SERVICE, { id: opts.job.id, kind: opts.kind }); + } + return { ok: false, error: g.message }; +} + +// THE PLATFORMS THAT HAVE A GUARD, by the platform a job asks +// (networkJobPlatform). A platform absent here runs on its queue and gap alone. +export const PLATFORM_GUARDS: Readonly<Record<string, PlatformGuard>> = Object.freeze({ + twitter: guardXJob, + instagram: guardInstagramJob, +}); + +// Asked at ENQUEUE (no job yet) and at START (`job` set: a refusal by the +// platform's alert is recorded against the alert, so "Re-run stopped jobs" +// offers it). +export async function guardNetworkJob( + opts: NetworkJobOpts & { job?: { id: string } }, +): Promise<NetworkGuardResult> { + if (!kindIsNetwork(opts.kind)) return { ok: true, notes: [] }; + const empty = emptyQueueRefusal(opts.kind, opts.queueKey); + if (empty) return { ok: false, error: empty }; + const platform = await networkJobPlatform(opts); + const guard = platform && Object.hasOwn(PLATFORM_GUARDS, platform) ? PLATFORM_GUARDS[platform] : undefined; + return guard ? guard(opts) : { ok: true, notes: [] }; +} diff --git a/common/lib/instagram/visibility.test.ts b/common/lib/instagram/visibility.test.ts @@ -0,0 +1,75 @@ +// Instagram posts are PRIVATE unless social.instagram.visibility says public — +// the same rule as X's, with the other default. X's rule is pinned unchanged. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + instagramPostsVisibility, + isInstagramPostsChannel, + isXPostsChannel, + postsVisibleTo, + publishedMemberSlugs, +} from "../postsVisibility"; +import { sanitizeSocial } from "../../social/xCookieSource"; +import { isSourcelessPostsChannel } from "../sourcelessPosts"; + +const IG = { sourceKind: "social" as const, platform: "instagram" as const }; +const X = { sourceKind: "social" as const, platform: "twitter" as const }; +const BLUESKY = { sourceKind: "social" as const, platform: "bluesky" as const }; +const publicSite = { audience: undefined }; +const privateSite = { audience: "private" as const }; +const IG_PUBLIC = { social: { instagram: { visibility: "public" } } }; + +test("an instagram channel is a social channel on platform instagram, and is not an X channel", () => { + assert.equal(isInstagramPostsChannel(IG), true); + assert.equal(isInstagramPostsChannel(X), false); + assert.equal(isInstagramPostsChannel({ platform: "instagram" }), false); + assert.equal(isInstagramPostsChannel(null), false); + assert.equal(isXPostsChannel(IG), false); + // A source-less published channel is X's only: an Instagram channel with no URL is not one. + assert.equal(isSourcelessPostsChannel(IG as never), false); +}); + +test("social.instagram.visibility: absent and unknown read as private", () => { + assert.equal(instagramPostsVisibility({}), "private"); + assert.equal(instagramPostsVisibility({ social: {} }), "private"); + assert.equal(instagramPostsVisibility({ social: { instagram: { visibility: "hidden" } } }), "private"); + assert.equal(instagramPostsVisibility({ social: { instagram: { visibility: "private" } } }), "private"); + assert.equal(instagramPostsVisibility(IG_PUBLIC), "public"); +}); + +test("by default a public site leaves an instagram channel out and a private site carries it", () => { + assert.equal(postsVisibleTo(publicSite, IG, {}), false); + assert.equal(postsVisibleTo(privateSite, IG, {}), true); + assert.equal(postsVisibleTo(publicSite, IG, IG_PUBLIC), true); + // X's setting says nothing about Instagram, and Instagram's nothing about X. + assert.equal(postsVisibleTo(publicSite, IG, { social: { x: { visibility: "public" } } }), false); + assert.equal(postsVisibleTo(publicSite, X, {}), true); + assert.equal(postsVisibleTo(publicSite, X, IG_PUBLIC), true); + assert.equal(postsVisibleTo(publicSite, X, { social: { x: { visibility: "private" } } }), false); + assert.equal(postsVisibleTo(privateSite, X, { social: { x: { visibility: "private" } } }), true); + assert.equal(postsVisibleTo(publicSite, BLUESKY, {}), true); +}); + +test("a site's published members leave its instagram channels out unless it is private", () => { + const configs: Record<string, typeof IG | typeof X | typeof BLUESKY> = { ig: IG, x: X, sky: BLUESKY }; + const site = { audience: undefined, channels: [{ slug: "ig" }, { slug: "x" }, { slug: "sky" }] }; + assert.deepEqual(publishedMemberSlugs(site as never, (s) => configs[s], {}), ["x", "sky"]); + assert.deepEqual(publishedMemberSlugs(site as never, (s) => configs[s], IG_PUBLIC), ["ig", "x", "sky"]); + assert.deepEqual(publishedMemberSlugs({ ...site, audience: "private" } as never, (s) => configs[s], {}), ["ig", "x", "sky"]); +}); + +test("the social block keeps instagram's two keys and drops the rest", () => { + assert.deepEqual(sanitizeSocial({}), { x: {} }); + assert.deepEqual(sanitizeSocial({ instagram: {} }), { x: {} }); + assert.deepEqual(sanitizeSocial({ instagram: { visibility: "public", allowLoggedOut: true, other: 1 } }), { + x: {}, + instagram: { visibility: "public", allowLoggedOut: true }, + }); + assert.deepEqual(sanitizeSocial({ instagram: { visibility: "nope", allowLoggedOut: "yes" } }), { x: {} }); + assert.deepEqual(sanitizeSocial({ instagram: { allowLoggedOut: false } }), { x: {} }); + // X's keys are untouched by Instagram's. + assert.deepEqual(sanitizeSocial({ x: { visibility: "private" }, instagram: { visibility: "private" } }), { + x: { visibility: "private" }, + instagram: { visibility: "private" }, + }); +}); diff --git a/common/lib/postsVisibility.ts b/common/lib/postsVisibility.ts @@ -26,11 +26,16 @@ // hasPostsCorpus), so a public site whose only posts were X posts ships an // empty posts manifest and no Posts toggle. // +// INSTAGRAM (lane instagram) has the same rule with the other default: an +// Instagram channel (a social channel on platform "instagram") is built only +// into a PRIVATE site unless `social.instagram.visibility` is "public". Absent +// is PRIVATE. +// // Pure: no fs, no settings read. The callers pass the settings and the configs. import { isSocialChannel, type ChannelConfig } from "./channelConfig"; import { isPrivateSite, type Site } from "./siteSchema"; -import type { XPostsVisibility } from "../social/xCookieSource"; +import type { InstagramPostsVisibility, XPostsVisibility } from "../social/xCookieSource"; import { isWaybackPagesChannel } from "./waybackPages/config"; import { isXTargetUrl } from "./waybackPages/urls"; import { isXTrendingChannel } from "./xTrending/config"; @@ -66,17 +71,37 @@ export function xPostsVisibility(settings: { return settings.social?.x?.visibility === "private" ? "private" : "public"; } +// An Instagram channel: the posts of a social channel whose platform is +// Instagram. +export function isInstagramPostsChannel(config: VisibilityConfig | null | undefined): boolean { + return isSocialChannel(config) && config?.platform === "instagram"; +} + +// `social.instagram.visibility`, resolved: absent (or anything unknown) is +// "private". +export function instagramPostsVisibility(settings: VisibilitySettings): InstagramPostsVisibility { + return settings.social?.instagram?.visibility === "public" ? "public" : "private"; +} + +// What the rule reads of the settings. +export type VisibilitySettings = { + social?: { x?: { visibility?: unknown }; instagram?: { visibility?: unknown } }; +}; + // Whether `site` may carry the posts of the channel `config` describes. A // channel with no readable config is not an X channel as far as this rule // knows, and is left to whatever already decides its fate. export function postsVisibleTo( site: Pick<Site, "audience">, config: VisibilityConfig | null | undefined, - settings: { social?: { x?: { visibility?: unknown } } }, + settings: VisibilitySettings, ): boolean { // An X trending library (lane x-trending) is private: NO site carries it, // a private one included, whatever the X visibility setting says. if (isXTrendingChannel(config)) return false; + if (isInstagramPostsChannel(config)) { + return instagramPostsVisibility(settings) === "public" || isPrivateSite(site); + } if (!isXPostsChannel(config)) return true; if (xPostsVisibility(settings) === "public") return true; return isPrivateSite(site); @@ -90,7 +115,7 @@ export function publishedMemberSlugs( configOf: ( slug: string, ) => VisibilityConfig | null | undefined, - settings: { social?: { x?: { visibility?: unknown } } }, + settings: VisibilitySettings, ): string[] { return site.channels .map((c) => c.slug) diff --git a/common/lib/serviceCookies-server.ts b/common/lib/serviceCookies-server.ts @@ -19,6 +19,7 @@ import { getSettings } from "./settings"; import { detectPlatform } from "./platform"; import { ARCHIVE_TODAY_SERVICE, + INSTAGRAM_SERVICE, X_SERVICE, applyServiceCookieClean, applyServiceCookieSignal, @@ -360,11 +361,29 @@ export async function noteXServiceOutcome( paths: Pick<Paths, "transcriptsDir">, outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string }, ): Promise<string | null> { + return noteBlockingServiceOutcome(paths, X_SERVICE, outcome); +} + +// One gallery-dl run against Instagram, the same way: a redirect to its +// login, challenge or checkpoint page raises Instagram's alert (one is +// enough), which refuses every Instagram job until a person's Recheck. +export async function noteInstagramServiceOutcome( + paths: Pick<Paths, "transcriptsDir">, + outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string }, +): Promise<string | null> { + return noteBlockingServiceOutcome(paths, INSTAGRAM_SERVICE, outcome); +} + +async function noteBlockingServiceOutcome( + paths: Pick<Paths, "transcriptsDir">, + service: string, + outcome: { challengeLine?: string; kind?: "challenge" | "auth-failure"; url?: string; channel?: string }, +): Promise<string | null> { try { if (outcome.challengeLine) { await noteServiceCookieSignal( paths, - { service: X_SERVICE, kind: outcome.kind ?? "challenge", line: outcome.challengeLine.trim().slice(0, 300) }, + { service, kind: outcome.kind ?? "challenge", line: outcome.challengeLine.trim().slice(0, 300) }, { ...(outcome.url ? { url: outcome.url } : {}), ...(outcome.channel ? { channel: outcome.channel } : {}), @@ -373,10 +392,10 @@ export async function noteXServiceOutcome( return null; } const now = Date.now(); - if (!(await cleanWouldChange(paths, X_SERVICE, now))) return null; + if (!(await cleanWouldChange(paths, service, now))) return null; return await noteServiceCookieClean( paths, - X_SERVICE, + service, outcome.url ? { url: outcome.url, ...(outcome.channel ? { channel: outcome.channel } : {}) } : undefined, { now }, ); diff --git a/common/lib/serviceCookies.ts b/common/lib/serviceCookies.ts @@ -55,7 +55,14 @@ export const ARCHIVE_TODAY_SERVICE = "archive.today"; // challenge is the one that gets an account locked. export const X_SERVICE = "x"; -export type ServiceFamily = "ytdlp" | "forum" | "archive" | "x"; +// Instagram (lane instagram): a redirect to its login, challenge or checkpoint +// page in gallery-dl's output. Like X's, WHILE ITS ALERT IS UP NO INSTAGRAM +// JOB STARTS (common/jobs/networkGuard.ts) — and unlike every other service +// nothing clears it but a person: Recheck (or Dismiss) on the dashboard, which +// sends Instagram no request. The recheck timer never asks it. +export const INSTAGRAM_SERVICE = "instagram"; + +export type ServiceFamily = "ytdlp" | "forum" | "archive" | "x" | "instagram"; export function isYtdlpCookieService(s: string): s is YtdlpCookieService { return (YTDLP_COOKIE_SERVICES as readonly string[]).includes(s); @@ -65,7 +72,7 @@ export function isYtdlpCookieService(s: string): s is YtdlpCookieService { // (lowercased, no www.). Anything else is not a service. export function isServiceKey(s: unknown): s is string { if (typeof s !== "string" || s.length === 0 || s.length > 100) return false; - if (isYtdlpCookieService(s) || s === ARCHIVE_TODAY_SERVICE || s === X_SERVICE) return true; + if (isYtdlpCookieService(s) || s === ARCHIVE_TODAY_SERVICE || s === X_SERVICE || s === INSTAGRAM_SERVICE) return true; return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(s); } @@ -73,6 +80,7 @@ export function serviceFamily(service: string): ServiceFamily { if (isYtdlpCookieService(service)) return "ytdlp"; if (service === ARCHIVE_TODAY_SERVICE) return "archive"; if (service === X_SERVICE) return "x"; + if (service === INSTAGRAM_SERVICE) return "instagram"; return "forum"; } @@ -93,6 +101,8 @@ export function serviceLabel(service: string): string { return "archive.today"; case X_SERVICE: return "X"; + case INSTAGRAM_SERVICE: + return "Instagram"; default: return /(^|\.)kiwifarms\./.test(service) ? `Kiwi Farms (${service})` : service; } @@ -123,6 +133,12 @@ export function serviceFixText(service: string, browser?: string, kind?: Service "pass X's check by hand — Connect X account on /cookies and clear it in the window (with the " + "browser login: open x.com in that browser) — then press Refresh cookies there; no X job starts until then" ); + case INSTAGRAM_SERVICE: + return ( + "pass Instagram's check by hand, in the browser (or with the cookies file's account) the channel's " + + "cookie source names, then press Recheck on the dashboard; no Instagram job starts until then, and " + + "Recheck sends Instagram no request" + ); default: return `use “Connect forum session” on the thread's channel page and clear the check in the window`; } @@ -413,7 +429,7 @@ export function isAlertRaised(e: ServiceCookieEntry | undefined): boolean { } // A raised alert that REFUSES the service's jobs (jobs/networkGuard.ts — X -// only): every raised kind but jar-age, whose refusal is the fresh-jar rule's +// and Instagram): every raised kind but jar-age, whose refusal is the fresh-jar rule's // own and which clears the moment the jar is fresh. export function isBlockingAlert(e: ServiceCookieEntry | undefined): boolean { return isAlertRaised(e) && e!.kind !== "jar-age"; @@ -757,6 +773,7 @@ export function buildServiceCookieAlerts( canRecheck: serviceFamily(e.service) === "archive" || serviceFamily(e.service) === "x" || + serviceFamily(e.service) === "instagram" || !!state.lastGood[e.service] || !!e.evidence.url, stoppedJobs, diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -55,6 +55,7 @@ import { SOCIAL_SETTINGS_FIELD_DOCS, X_SOCIAL_SETTINGS_FIELD_DOCS, XENFORO_SOCIAL_SETTINGS_FIELD_DOCS, + INSTAGRAM_SOCIAL_SETTINGS_FIELD_DOCS, SYNC_SCHEDULER_SETTINGS_FIELD_DOCS, defaultSiteSettings, siteSettingsSchema, @@ -220,6 +221,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, defaults: fromObject(d.social.x), }, { path: "social.xenforo", docs: XENFORO_SOCIAL_SETTINGS_FIELD_DOCS }, + { path: "social.instagram", docs: INSTAGRAM_SOCIAL_SETTINGS_FIELD_DOCS }, ], socialLinks: [{ path: "socialLinks[]", docs: SOCIAL_LINK_FIELD_DOCS }], remoteArchives: [{ path: "remoteArchives[]", docs: REMOTE_ARCHIVE_FIELD_DOCS }], diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -145,12 +145,13 @@ import { previewBranchProblem } from "./pagesDeploy"; import { sanitizeSocial, type SocialSettings, + type InstagramSocialSettings, type XenforoSocialSettings, type XSocialSettings, } from "../social/xCookieSource"; export type { Worker } from "./workers"; -export type { SocialSettings, XSocialSettings, XenforoSocialSettings } from "../social/xCookieSource"; +export type { SocialSettings, XSocialSettings, XenforoSocialSettings, InstagramSocialSettings } from "../social/xCookieSource"; import { sanitizeJobGapSeconds } from "./jobGap"; export { JOB_GAP_DEFAULT_SECONDS, JOB_GAP_MAX_SECONDS, jobGapSecondsFor } from "./jobGap"; @@ -160,6 +161,22 @@ export { JOB_GAP_DEFAULT_SECONDS, JOB_GAP_MAX_SECONDS, jobGapSecondsFor } from " export const SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<SocialSettings> = { x: "X / Twitter. See `social.x` below.", xenforo: "Forum threads (XenForo). See `social.xenforo` below. Absent: nothing set.", + instagram: "Instagram. See `social.instagram` below. Absent: nothing set (posts private, no logged-out reads).", +}; + +export const INSTAGRAM_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<InstagramSocialSettings> = { + visibility: + "Where Instagram posts may appear. `\"private\"` (the default; absent): every Instagram channel's " + + "posts (a channel with `sourceKind: \"social\"` and `platform: \"instagram\"`) are left out of " + + "every PUBLIC site build, the channel with them, and built only into PRIVATE sites (`site.json` " + + "`audience`). `\"public\"`: built into every site that has the channel. Nothing on disk changes " + + "and fetching does not; a site already published changes on its next build and deploy. The rule " + + "is common/lib/postsVisibility.ts. `pnpm ops settings` sets it.", + allowLoggedOut: + "`true` lets an Instagram channel that has no cookie source of its own (`cookiesFromBrowser` in " + + "its config) be read LOGGED OUT. ABSENT (the default): such a channel refuses to fetch and says " + + "where to set the source. Whether Instagram answers a logged-out read at all is unproven: leave " + + "this off until one probe has shown it does. Stored only when true.", }; export const XENFORO_SOCIAL_SETTINGS_FIELD_DOCS: FieldDocs<XenforoSocialSettings> = { diff --git a/common/publish/inputSig.ts b/common/publish/inputSig.ts @@ -160,6 +160,8 @@ export async function siteInputSig(i: SiteSigInputs): Promise<string> { `settings\t${JSON.stringify({ archiveStorage: settings.archiveStorage ?? null, xVisibility: settings.social?.x?.visibility ?? null, + // Only when set: a corpus that never chose it keeps the signature it had. + ...(settings.social?.instagram?.visibility ? { instagramVisibility: settings.social.instagram.visibility } : {}), buildArchives: settings.buildArchives ?? null, })}`, ); @@ -205,6 +207,8 @@ export function indexSettingsSig(settings: Partial<IndexSettingsInputs>): string buildArchives: settings.buildArchives ?? null, archiveStorage: settings.archiveStorage ?? null, xVisibility: settings.social?.x?.visibility ?? null, + // Only when set: a corpus that never chose it keeps the signature it had. + ...(settings.social?.instagram?.visibility ? { instagramVisibility: settings.social.instagram.visibility } : {}), maxTranscriptPageBytes: settings.maxTranscriptPageBytes ?? null, locations: (settings.storage?.locations ?? []).map((l) => [l.id, l.root]), }), diff --git a/common/social/xCookieSource.ts b/common/social/xCookieSource.ts @@ -82,10 +82,32 @@ export type XenforoSocialSettings = { retryOnBlock?: RetryOnBlock; }; +// Instagram's settings (lane instagram). +export type InstagramPostsVisibility = "public" | "private"; + +export const INSTAGRAM_POSTS_VISIBILITIES: readonly InstagramPostsVisibility[] = ["private", "public"]; + +export function isInstagramPostsVisibility(v: unknown): v is InstagramPostsVisibility { + return v === "public" || v === "private"; +} + +export type InstagramSocialSettings = { + // WHERE INSTAGRAM POSTS MAY APPEAR. Absent = "private": an Instagram + // channel's posts are built only into PRIVATE sites. The rule is + // lib/postsVisibility.ts, the same shape as X's with the other default. + visibility?: InstagramPostsVisibility; + // Let an Instagram channel with no cookie source of its own be read LOGGED + // OUT. Stored only when true; absent = such a channel refuses to fetch. + // Whether Instagram answers a logged-out read at all is unproven. + allowLoggedOut?: boolean; +}; + export type SocialSettings = { x: XSocialSettings; // Absent: nothing set. xenforo?: XenforoSocialSettings; + // Absent: nothing set (private, and no logged-out reads). + instagram?: InstagramSocialSettings; }; // Total over `unknown`, as every settings coercion is: anything that is not a @@ -101,6 +123,13 @@ export function sanitizeSocial(value: unknown): SocialSettings { const xf = (r.xenforo && typeof r.xenforo === "object" && !Array.isArray(r.xenforo) ? r.xenforo : {}) as Record<string, unknown>; + const ig = (r.instagram && typeof r.instagram === "object" && !Array.isArray(r.instagram) + ? r.instagram + : {}) as Record<string, unknown>; + const instagram: InstagramSocialSettings = { + ...(isInstagramPostsVisibility(ig.visibility) ? { visibility: ig.visibility } : {}), + ...(ig.allowLoggedOut === true ? { allowLoggedOut: true } : {}), + }; const retryOnBlock = parseRetryOnBlock(xf.retryOnBlock); const maxCookieAgeMinutes = parseXMaxCookieAgeMinutes(x.maxCookieAgeMinutes); return { @@ -110,6 +139,7 @@ export function sanitizeSocial(value: unknown): SocialSettings { ...(maxCookieAgeMinutes !== undefined ? { maxCookieAgeMinutes } : {}), }, ...(retryOnBlock ? { xenforo: { retryOnBlock } } : {}), + ...(Object.keys(instagram).length > 0 ? { instagram } : {}), }; }