// settings.remoteArchives — the PUBLISHED ARCHIVES this machine reads as // sources (demo epic D1: "a public archive is a first-class source"). // // A published archive is any origin serving the machine contract at // `/corpus.json` (common/lib/corpus.ts): jeralyzer.pages.dev, or a friend's. // Connecting one is the operator typing its origin once; from then on the // editor's Create form, umtool's Source chip and the MCP all offer it, its // sweeps cite it, and its clip windows are fetched for its channels — with no // local corpus and no site.json made by hand. // // THE ONE RESOLVER. This module is the pure half (the shape, the sanitizer, the // origin rule, the env default); remoteArchives-server.ts reads corpus.json and // a channel's facts over HTTP. The editor (settings + its ops action), umtool's // source picker (umtool/lib/research/sources.ts) and the MCP's list_sources all // list archives through `connectedArchives`, so the three never disagree about // what is connected. // // NOT `settings.archives`: that key was taken first, by the page-import sources // (archive.today, release 37 lane F — lib/archives/settings.ts). // // Pure, browser-safe: no node:* import. import type { FieldDocs } from "./fieldDocs"; export type RemoteArchive = { // A slug, unique among the connected archives: the archive's own site id // when its corpus.json names one, else made from its host. id: string; // The archive's origin, normalized (archiveOriginOf): http(s), no trailing // slash, no query or fragment. `/corpus.json` is its contract. origin: string; // What its corpus.json calls it (site.title) when it was connected. title: string; // When it was connected, ISO-8601. addedAt: string; }; // A connected archive as the pickers list it: the stored ones, then the one the // environment names (TRANSCRIPT_SITE_URL) when no stored entry has its origin. export type ConnectedArchive = RemoteArchive & { // From TRANSCRIPT_SITE_URL, not settings.json: listed, never written, and // gone when the variable is. fromEnv?: true; }; export const REMOTE_ARCHIVE_FIELD_DOCS: FieldDocs = { id: "A slug, unique among the connected archives: the archive's own `site.id` from its corpus.json when that is " + "free, else one made from its host. What `pnpm ops archives` removes by.", origin: "The archive's origin: an http(s) URL with no trailing slash, query or fragment, where `/corpus.json` is " + "served. Sweeps over it cite it (`remote:`), whatever `generation.citationOrigin` says.", title: "The archive's `site.title`, as its corpus.json said when it was connected.", addedAt: "When it was connected (ISO-8601).", }; const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; /** Whether `v` is an archive id (a lowercase slug, at most 64 characters). */ export function isArchiveId(v: unknown): v is string { return typeof v === "string" && ID_RE.test(v); } /** * An archive origin, normalized — `https://host[/path]` with no trailing * slash — or null when `v` is not one: not http(s), carries credentials, a * query or a fragment, or does not parse. A path is kept (an archive may be * served under one); `/corpus.json` typed on the end is taken off. */ export function archiveOriginOf(v: unknown): string | null { if (typeof v !== "string") return null; let s = v.trim(); if (!s) return null; if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = `https://${s}`; let u: URL; try { u = new URL(s); } catch { return null; } if (u.protocol !== "https:" && u.protocol !== "http:") return null; if (u.username || u.password || u.search || u.hash || !u.hostname) return null; const p = u.pathname.replace(/\/corpus\.json$/i, "").replace(/\/+$/, ""); return `${u.protocol}//${u.host}${p}`; } /** The source handle a sweep over an archive names (mcp/src/sourceRegistry.ts). */ export function archiveHandle(origin: string): string { return `remote:${origin}`; } /** The origin a `remote:` handle names, normalized, or null for any other handle. */ export function originOfHandle(handle: string | null | undefined): string | null { const m = /^remote:(.+)$/s.exec(handle?.trim() ?? ""); return m ? archiveOriginOf(m[1]) : null; } /** A slug for an archive from its host (and path): `jeralyzer.pages.dev` → `jeralyzer-pages-dev`. */ export function archiveIdFromOrigin(origin: string): string { const bare = origin.replace(/^https?:\/\//, "").toLowerCase(); const slug = bare.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64).replace(/-+$/, ""); return slug && ID_RE.test(slug) ? slug : "archive"; } /** * The id a newly connected archive gets: `preferred` (its corpus.json's site * id) when that is a free slug, else one from its origin, made unique with a * numeric suffix. */ export function freeArchiveId(origin: string, taken: Iterable, preferred?: string | null): string { const used = new Set(taken); const base = preferred && ID_RE.test(preferred) ? preferred : archiveIdFromOrigin(origin); if (!used.has(base)) return base; for (let n = 2; ; n++) { const id = `${base.slice(0, 60)}-${n}`; if (!used.has(id)) return id; } } /** * settings.json's `remoteArchives`, sanitized: an array of entries each with a * valid id and origin; a later duplicate (same origin or id) is dropped; a * missing title becomes the origin's host, a missing date the epoch. Total over * `unknown` (the settings reader never throws). */ export function sanitizeRemoteArchives(v: unknown): RemoteArchive[] { if (!Array.isArray(v)) return []; const out: RemoteArchive[] = []; const ids = new Set(); const origins = new Set(); for (const raw of v) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue; const r = raw as Record; const origin = archiveOriginOf(r.origin); if (!origin || origins.has(origin)) continue; const id = isArchiveId(r.id) ? r.id : null; if (!id || ids.has(id)) continue; const title = typeof r.title === "string" && r.title.trim() ? r.title.trim().slice(0, 200) : origin.replace(/^https?:\/\//, ""); const addedAt = typeof r.addedAt === "string" && !Number.isNaN(Date.parse(r.addedAt)) ? new Date(r.addedAt).toISOString() : new Date(0).toISOString(); ids.add(id); origins.add(origin); out.push({ id, origin, title, addedAt }); } return out; } type Env = Record; /** * Every connected archive, as the pickers list them: the stored ones in order, * then — when it names an origin no stored entry has — TRANSCRIPT_SITE_URL's * (the MCP's own remote, AGENTS.md "Working this repo with no local corpus"), * marked `fromEnv`. That is the default a fresh clone gets: one archive, from * the variable it was told to set. */ export function connectedArchives(stored: unknown, env: Env = typeof process !== "undefined" ? (process.env as Env) : {}): ConnectedArchive[] { const list: ConnectedArchive[] = sanitizeRemoteArchives(stored); const fromEnv = archiveOriginOf(env.TRANSCRIPT_SITE_URL); if (fromEnv && !list.some((a) => a.origin === fromEnv)) { list.push({ id: freeArchiveId(fromEnv, list.map((a) => a.id)), origin: fromEnv, title: fromEnv.replace(/^https?:\/\//, ""), addedAt: new Date(0).toISOString(), fromEnv: true, }); } return list; } /** The connected archive at `origin` (normalized first), or null. */ export function findConnectedArchive(list: readonly ConnectedArchive[], origin: string | null | undefined): ConnectedArchive | null { const want = archiveOriginOf(origin); return want ? (list.find((a) => a.origin === want) ?? null) : null; } /** * Why a remote-only channel's archive is not read any more, or null: the * origin its config names (`remoteArchive`) is no longer among the connected * archives — removed from settings since the channel was registered. Its * record is not asked for and no window is fetched for it (demo epic D1 * re-review, item 6). */ export function disconnectedArchiveRefusal(origin: string | null | undefined, list: readonly ConnectedArchive[]): string | null { if (!origin) return null; if (findConnectedArchive(list, origin)) return null; return `its archive ${origin} is no longer connected — connect it again (the editor's /sites, "Connected archives") to fetch its windows`; } /** * The marker a remote-only channel's whole-recording refusal starts with * (controller/remoteOnlyChannel.ts wholeRecordingRefusal): umtool's chain * looks for it to offer the one-press override (`allowWholeRecording`). */ export const WHOLE_RECORDING_REFUSED = "whole recording refused:"; // ─── An archive is untrusted input (demo epic D1 review, blocker 2) ─── // The platforms a clip window of an archive's channel may be fetched from: // the video platforms, each recognised by its HOST (lib/detectPlatform.mjs). // Never the post platforms, and never xenforo, which is recognised by a // thread path on any host. export const RECORD_PAGE_PLATFORMS = ["youtube", "rumble", "odysee", "twitch", "kick", "archiveorg", "bitchute"] as const; // Each platform's own domains, matched EXACTLY or as a parent (`host === d` or // `host` ends in `.d`). lib/detectPlatform.mjs answers "which platform is // this", loosely (`host.endsWith("youtube.com")` is true of evilyoutube.com); // here the question is "may this machine fetch from that host", so the answer // it gives is checked against this table (demo epic D1 re-review, must-fix 1). export const RECORD_PAGE_HOSTS: Record<(typeof RECORD_PAGE_PLATFORMS)[number], readonly string[]> = { youtube: ["youtube.com", "youtu.be"], rumble: ["rumble.com"], odysee: ["odysee.com"], twitch: ["twitch.tv"], kick: ["kick.com"], archiveorg: ["archive.org"], bitchute: ["bitchute.com"], }; /** Whether `host` is one of `platform`'s own domains or a subdomain of one. */ export function isPlatformHost(platform: string, host: string): boolean { const domains = (RECORD_PAGE_HOSTS as Record)[platform]; const h = host.toLowerCase().replace(/\.$/, ""); return !!domains && domains.some((d) => h === d || h.endsWith(`.${d}`)); } // A page URL is refused when it carries a backslash, whitespace or a control // character ANYWHERE — before it is parsed. URL parsers disagree about exactly // these: Node reads `https://youtube.com\@evil.example/` as host youtube.com // (a backslash is a slash to it), Python's urlsplit — what yt-dlp reads it // with — as host evil.example; Node drops a tab or newline inside a host and // trims the ends. So the host judged here would not be the host fetched // (demo epic D1 re-check, the parser differential). const UNSAFE_PAGE_CHARS = /[\\\s\u0000-\u001f\u007f-\u009f\u00a0\u1680\u2000-\u200f\u2028-\u202f\u205f-\u2060\u3000\ufeff]/; export type RecordPage = { href: string; platform: string } | { refused: string }; /** * A remote-only channel's page URL — an archive record's `webpageUrl`, or one * an ask carried for it — judged, and NORMALISED: `{href, platform}` when a * window may be fetched from it, `{refused}` with the sentence when not. The * archive is someone else's JSON: a URL is accepted only when it has no * backslash, whitespace or control character, is http(s) with no credentials, * its host names a known video platform, and that is the channel's own * platform when the channel has one. Refused before any request. * * `href` is what the parser that judged the host wrote back (`new URL().href`: * the host lowercased, a default port dropped, an IDN in punycode), and it is * THE ONLY string a caller hands on — never the one it was given. */ export function recordPage(url: string | null | undefined, channelPlatform: string | null | undefined, detect: (u: string) => string | null): RecordPage { if (!url) return { refused: "no page URL" }; if (UNSAFE_PAGE_CHARS.test(url)) { return { refused: `${JSON.stringify(url)} is not a page URL: it carries a backslash, whitespace or a control character, which URL parsers read differently — the archive's page URL is not fetched` }; } let u: URL; try { u = new URL(url); } catch { return { refused: `"${url}" is not a page URL` }; } if ((u.protocol !== "https:" && u.protocol !== "http:") || u.username || u.password) return { refused: `${u.protocol}//${u.host} is not a page URL a window is fetched from` }; const href = u.href; const platform = detect(href); if (!platform || !(RECORD_PAGE_PLATFORMS as readonly string[]).includes(platform) || !isPlatformHost(platform, u.hostname)) { return { refused: `${u.host} is not a video platform's host (${RECORD_PAGE_PLATFORMS.join(", ")}): the archive's page URL is not fetched` }; } if (channelPlatform && channelPlatform !== platform) { return { refused: `${u.host} is ${platform}, and the channel is ${channelPlatform}'s: the archive's page URL is not fetched` }; } return { href, platform }; } /** Why a remote-only channel's page URL is not fetched, or null when it may be (recordPage's sentence). */ export function recordPageRefusal(url: string | null | undefined, channelPlatform: string | null | undefined, detect: (u: string) => string | null): string | null { const page = recordPage(url, channelPlatform, detect); return "refused" in page ? page.refused : null; } /** Whether `url` is on `origin`'s own scheme, host and port. */ export function sameOrigin(url: string, origin: string): boolean { try { return new URL(url).origin === new URL(origin).origin; } catch { return false; } }