// `archilyzer evidence pack|stamp|upgrade|verify` — a posts channel's archived // posts as a self-contained, checksummed and timestamped evidence package. // // archilyzer evidence pack [,…] [--handle ] [--since YYYY-MM-DD] // [--until YYYY-MM-DD] [--out ] [--media|--no-media] [--stamp|--no-stamp] // [--dry-run] [--json] // archilyzer evidence stamp # an unstamped package (--no-stamp, or a stamp that failed) // archilyzer evidence upgrade # the pending stamp, once the calendars have attested it // archilyzer evidence verify # every file against SHA256SUMS, then the stamp's state // // The need (operator, 5 Nov): public evidence that an account's X posts existed, // while archive.org's Save Page Now refuses x.com as a site (HTTP 523). The // archive already holds the posts; this packages them so a third party can check // them without this repo: one normalised record per post (every archived field // kept under `raw`), a CSV, the post media copied byte for byte, a README, a // SHA256SUMS over every file, and an OpenTimestamps proof of SHA256SUMS — which // proves the package (and so every file it lists) existed no later than the // Bitcoin block the calendars commit it to. // // READ ONLY over the corpus. Each channel's text is guarded // (`assertChannelTextReadable`); the media are COPIED (never linked, never // touched); the output may not be inside the corpus, a channel or its media; the // package is built in a sibling staging dir and renamed into place, so a cut run // leaves no half package where the package should be. // // The stamp is the official OpenTimestamps client (`ots`, Python): `ots stamp` // submits the digest once to each of its default calendars (one request each, // no retries). Install it with `uv tool install opentimestamps-client` (or // `pipx install opentimestamps-client`); ARCHILYZER_OTS_BIN names another binary. import { createHash } from "node:crypto"; import { createReadStream, constants as fsConstants } from "node:fs"; import { copyFile, lstat, mkdir, readFile, readdir, realpath, rename, rmdir, stat, utimes, writeFile, } from "node:fs/promises"; import { spawn, spawnSync } from "node:child_process"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import type { FlagValue } from "./_parseFlags"; // The capture layout's one definition (posts-media//capture.json). This // module is the second reader of captures the export guard allows // (social/postCapture.test.ts): a private package, written outside the // corpus, that nothing in the export or publish layer imports. import { CAPTURE_FILENAME, postsMediaDir } from "../social/postCapture"; import "../lib/childKillGuard"; export const SUMS_FILE = "SHA256SUMS"; export const OTS_FILE = "SHA256SUMS.ots"; export const PACK_VERSION = 1; // --------------------------------------------------------------------------- // Types export type ChannelSource = { slug: string; config: Record | null; fetchState: Record | null; shards: { file: string; bytes: number; sha256: string; lines: number; malformed: number }[]; records: number; }; type Loaded = { channel: string; shard: string; raw: Record; }; export type PackFile = { path: string; // relative to the package, "/"-separated bytes: number; sha256: string; // What the archive's capture.json recorded for this file, when it names it. archivedSha256?: string; sourceUrl?: string; from: string; // the channel whose posts-media it was copied from }; export type PackRecord = { id: string; url: string; platform: string; author: string; authorName?: string; createdAt: string; kind: "post" | "reply" | "quote" | "repost"; text: string; lang?: string; threadId?: string; replyTo?: unknown; quoted?: unknown; repostOf?: unknown; links: unknown[]; engagement?: unknown; mediaCount?: number; channels: string[]; capturedAt: string | null; capture: Record | null; availability: Record | null; // The archived record of the post this one answers / quotes / reposts, when // the packaged channels hold it (any author): context as archived. context?: { replyTo?: Record; quoted?: Record; repostOf?: Record }; files: PackFile[]; raw: Record; // The same post as another packaged channel archived it, when that record differs. rawElsewhere?: { channel: string; raw: Record }[]; }; export type PackOptions = { channelsDir: string; transcriptsDir: string; slugs: string[]; handle?: string; since?: string; until?: string; out: string; media: boolean; stamp: boolean; dryRun: boolean; now?: Date; // Test seams. guardText?: (slug: string) => Promise; ots?: OtsRunner; toolCommit?: string | null; }; export type StampResult = | { status: "pending" | "attested"; calendars: string[]; blocks: number[]; info: string } | { status: "skipped" | "unavailable" | "failed"; error?: string }; export type PackResult = { out: string; dryRun: boolean; channels: { slug: string; records: number; shards: number }[]; posts: number; byKind: Record; contextRecords: number; mediaFiles: number; mediaBytes: number; mediaMismatches: string[]; firstPostAt: string | null; lastPostAt: string | null; files: number; sumsSha256: string | null; stamp: StampResult; }; export class EvidenceRefusal extends Error {} // --------------------------------------------------------------------------- // Small pure helpers (unit-tested) const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/; const DAY = /^\d{4}-\d{2}-\d{2}$/; export function isSafePostId(id: unknown): id is string { return typeof id === "string" && SAFE_ID.test(id); } export function parseDay(v: string | undefined): string | undefined | null { if (v === undefined) return undefined; if (!DAY.test(v)) return null; const d = new Date(`${v}T00:00:00Z`); return Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== v ? null : v; } export function normHandle(h: string): string { return h.trim().replace(/^@/, "").toLowerCase(); } function str(v: unknown): string | undefined { return typeof v === "string" ? v : undefined; } function obj(v: unknown): Record | undefined { return v && typeof v === "object" && !Array.isArray(v) ? (v as Record) : undefined; } export function postKind(raw: Record): PackRecord["kind"] { if (raw.isRepost === true || obj(raw.repostOf)) return "repost"; if (raw.isReply === true || obj(raw.replyTo)) return "reply"; if (obj(raw.quoted)) return "quote"; return "post"; } /** Whether a record falls in the filter: the author's handle and the UTC day of createdAt. */ export function inScope( raw: Record, f: { handle?: string; since?: string; until?: string }, ): boolean { if (f.handle && normHandle(str(raw.author) ?? "") !== normHandle(f.handle)) return false; const day = (str(raw.createdAt) ?? "").slice(0, 10); if (f.since && !(day >= f.since)) return false; if (f.until && !(day <= f.until)) return false; return true; } /** One CSV field, RFC 4180: quoted when it holds a quote, a comma or a line break. Verbatim otherwise. */ export function csvField(v: unknown): string { const s = v === undefined || v === null ? "" : String(v); return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; } export function csvRow(fields: unknown[]): string { return fields.map(csvField).join(",") + "\r\n"; } export const CSV_HEADER = [ "id", "url", "created_at", "author", "author_name", "kind", "text", "reply_to_url", "quoted_url", "repost_of_url", "media_files", "captured_at", "channels", ]; function refUrl(v: unknown): string { const o = obj(v); return str(o?.url) ?? (str(o?.id) ? `id:${str(o?.id)}` : ""); } export function csvForRecords(records: PackRecord[]): string { let out = csvRow(CSV_HEADER); for (const r of records) { out += csvRow([ r.id, r.url, r.createdAt, r.author, r.authorName ?? "", r.kind, r.text, refUrl(r.replyTo), refUrl(r.quoted), refUrl(r.repostOf), r.files.map((f) => f.path).join(" "), r.capturedAt ?? "", r.channels.join(" "), ]); } return out; } /** * One SHA256SUMS line as GNU coreutils writes and `sha256sum -c` reads it: a * name holding a backslash or a line break is escaped and the line starts with * a backslash. */ export function sumsLine(sha256: string, rel: string): string { if (/[\\\n\r]/.test(rel)) { const esc = rel.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r"); return `\\${sha256} ${esc}\n`; } return `${sha256} ${rel}\n`; } /** Parse SHA256SUMS back (the lines sumsLine writes). */ export function parseSums(text: string): Map { const out = new Map(); for (const line of text.split("\n")) { if (!line) continue; let l = line; let escaped = false; if (l.startsWith("\\")) { escaped = true; l = l.slice(1); } const m = /^([0-9a-f]{64}) [ *](.*)$/.exec(l); if (!m) throw new Error(`SHA256SUMS: a line does not parse: ${JSON.stringify(line.slice(0, 80))}`); let name = m[2]; if (escaped) name = name.replace(/\\(\\|n|r)/g, (_, c: string) => (c === "n" ? "\n" : c === "r" ? "\r" : "\\")); out.set(name, m[1]); } return out; } /** Files the sums do not cover: the sums themselves and the stamp (and the client's .bak of it). */ export function excludedFromSums(rel: string): boolean { return rel === SUMS_FILE || rel === OTS_FILE || rel.startsWith(`${OTS_FILE}.`); } export async function sha256File(file: string): Promise { const h = createHash("sha256"); for await (const chunk of createReadStream(file)) h.update(chunk as Buffer); return h.digest("hex"); } export function sha256Text(text: string | Buffer): string { return createHash("sha256").update(text).digest("hex"); } /** Every regular file under dir, relative and "/"-separated, in byte order. */ export async function listFiles(dir: string, rel = ""): Promise { const out: string[] = []; const entries = await readdir(path.join(dir, rel), { withFileTypes: true }); for (const e of entries) { const r = rel ? `${rel}/${e.name}` : e.name; if (e.isDirectory()) out.push(...(await listFiles(dir, r))); else if (e.isFile()) out.push(r); else throw new EvidenceRefusal(`${r} is neither a file nor a directory (a package holds only files)`); } return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); } /** Write SHA256SUMS over every file in dir (but the sums and the stamp); returns its own sha256. */ export async function writeSums(dir: string, known: Map = new Map()): Promise<{ sha256: string; files: number }> { const files = (await listFiles(dir)).filter((f) => !excludedFromSums(f)); let text = ""; for (const f of files) text += sumsLine(known.get(f) ?? (await sha256File(path.join(dir, f))), f); await writeFile(path.join(dir, SUMS_FILE), text, "utf8"); return { sha256: sha256Text(text), files: files.length }; } // --------------------------------------------------------------------------- // Paths and refusals function expandHome(p: string): string { return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p; } /** The real path of p, resolved through its nearest existing ancestor. */ export async function realpathLoose(p: string): Promise { const abs = path.resolve(p); const rest: string[] = []; let cur = abs; for (;;) { try { const real = await realpath(cur); return path.join(real, ...rest.reverse()); } catch { const parent = path.dirname(cur); if (parent === cur) return abs; rest.push(path.basename(cur)); cur = parent; } } } export function isInside(child: string, parent: string): boolean { const rel = path.relative(parent, child); return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel)); } export function defaultOutDir(label: string, now: Date): string { const day = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`; return path.join(os.homedir(), "reports", "evidence", `${label}-${day}`); } async function readJson(file: string): Promise { try { return JSON.parse(await readFile(file, "utf8")); } catch { return null; } } async function isDir(p: string): Promise { try { return (await stat(p)).isDirectory(); } catch { return false; } } // --------------------------------------------------------------------------- // Reading the channels async function readChannel( channelsDir: string, slug: string, ): Promise<{ source: ChannelSource; records: Loaded[] }> { const root = path.join(channelsDir, slug); const postsDir = path.join(root, "posts"); if (!(await isDir(postsDir))) { throw new EvidenceRefusal(`${slug}: not a posts channel (no posts/ in ${root})`); } const shardFiles = (await readdir(postsDir)).filter((f) => f.endsWith(".jsonl")).sort(); const byId = new Map(); const shards: ChannelSource["shards"] = []; for (const file of shardFiles) { const buf = await readFile(path.join(postsDir, file)); let lines = 0; let malformed = 0; for (const line of buf.toString("utf8").split("\n")) { const t = line.trim(); if (!t) continue; lines++; let raw: unknown; try { raw = JSON.parse(t); } catch { malformed++; continue; } const o = obj(raw); if (!o || !isSafePostId(o.id) || typeof o.createdAt !== "string") { malformed++; continue; } // A later shard wins (readAllPosts' rule: an interrupted write can leave a post in two). byId.set(o.id as string, { channel: slug, shard: file, raw: o }); } shards.push({ file: `posts/${file}`, bytes: buf.length, sha256: sha256Text(buf), lines, malformed }); } const config = obj(await readJson(path.join(root, "config.json"))) ?? null; const fetchState = obj(await readJson(path.join(root, "posts-state.json"))) ?? null; return { source: { slug, config, fetchState, shards, records: byId.size }, records: [...byId.values()], }; } function byCreated(a: { createdAt: string; id: string }, b: { createdAt: string; id: string }): number { return a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0; } function sameJson(a: unknown, b: unknown): boolean { return JSON.stringify(a) === JSON.stringify(b); } // --------------------------------------------------------------------------- // Pack type PlannedCopy = { src: string; rel: string; from: string; archivedSha256?: string; sourceUrl?: string; bytes: number }; async function planMedia( channelsDir: string, id: string, channels: string[], captures: Map | null>, ): Promise { const out: PlannedCopy[] = []; const seen = new Set(); for (const ch of channels) { const dir = path.join(postsMediaDir(path.join(channelsDir, ch)), id); if (!(await isDir(dir))) continue; const capture = captures.get(ch) ?? null; const named = new Map(); // Every file the capture names — `shot`, `thread`, `media[]`, an article's — // is an object with a `name` (and the `sha256` it was saved with). for (const v of Object.values(capture ?? {})) { for (const m of Array.isArray(v) ? v.map(obj) : [obj(v)]) { const name = str(m?.name); if (name && !named.has(name)) named.set(name, { sha256: str(m?.sha256), url: str(m?.url) }); } } for (const name of (await readdir(dir)).sort()) { if (seen.has(name)) continue; const src = path.join(dir, name); let st; try { st = await stat(src); // follows a link: the bytes are what is copied } catch { continue; } if (!st.isFile()) continue; seen.add(name); const n = named.get(name); out.push({ src, rel: `media/${id}/${name}`, from: ch, bytes: st.size, ...(n?.sha256 ? { archivedSha256: n.sha256 } : {}), ...(n?.url ? { sourceUrl: n.url } : {}), }); } } return out; } export async function pack(opts: PackOptions): Promise { const now = opts.now ?? new Date(); if (!opts.slugs.length) throw new EvidenceRefusal("evidence pack: which channels? Pass one or more slugs, comma-separated."); for (const s of opts.slugs) { if (!/^[A-Za-z0-9._-]+$/.test(s) || s === "." || s === "..") throw new EvidenceRefusal(`evidence pack: "${s}" is not a channel slug`); } // THE OUTPUT GUARD: never inside the corpus, a channel, or a channel's media (which may be on another drive). const out = path.resolve(expandHome(opts.out)); const outReal = await realpathLoose(out); const forbidden = [opts.transcriptsDir, opts.channelsDir]; for (const s of opts.slugs) { forbidden.push(path.join(opts.channelsDir, s)); forbidden.push(postsMediaDir(path.join(opts.channelsDir, s))); forbidden.push(path.join(opts.channelsDir, s, "media")); } for (const f of forbidden) { const real = await realpathLoose(f); if (isInside(outReal, real) || isInside(out, path.resolve(f))) { throw new EvidenceRefusal(`evidence pack: refusing to write inside the corpus (${out} is under ${f}); pick an --out outside it`); } } if (!opts.dryRun) { try { const st = await lstat(out); if (!st.isDirectory() || (await readdir(out)).length > 0) { throw new EvidenceRefusal(`evidence pack: ${out} already exists and is not an empty directory; a package is never written over another`); } } catch (err) { if (err instanceof EvidenceRefusal) throw err; } } // Read every channel (the text guard first). const sources: ChannelSource[] = []; const loaded = new Map(); // id -> per channel, in argument order for (const slug of opts.slugs) { if (!(await isDir(path.join(opts.channelsDir, slug)))) { throw new EvidenceRefusal(`evidence pack: no channel "${slug}" in ${opts.channelsDir}`); } if (opts.guardText) await opts.guardText(slug); const { source, records } = await readChannel(opts.channelsDir, slug); sources.push(source); for (const r of records) { const list = loaded.get(r.raw.id as string) ?? []; list.push(r); loaded.set(r.raw.id as string, list); } } const availability = new Map>(); for (const slug of opts.slugs) { const a = obj(await readJson(path.join(opts.channelsDir, slug, "posts-availability.json"))); if (a) availability.set(slug, a); } const filter = { handle: opts.handle, since: opts.since, until: opts.until }; const records: PackRecord[] = []; const copies: { rec: PackRecord; plan: PlannedCopy }[] = []; let contextRecords = 0; for (const [id, list] of loaded) { const primary = list[0]; if (!inScope(primary.raw, filter)) continue; const raw = primary.raw; const channels = list.map((l) => l.channel); const captures = new Map | null>(); for (const ch of channels) { captures.set(ch, obj(await readJson(path.join(postsMediaDir(path.join(opts.channelsDir, ch)), id, CAPTURE_FILENAME))) ?? null); } const capture = channels.map((c) => captures.get(c)).find((c) => c) ?? null; const avail = channels.map((c) => obj(availability.get(c)?.[id])).find((a) => a) ?? null; const context: NonNullable = {}; for (const key of ["replyTo", "quoted", "repostOf"] as const) { const refId = str(obj(raw[key])?.id); const target = refId ? loaded.get(refId)?.[0] : undefined; if (target && !inScope(target.raw, filter)) { context[key] = target.raw; contextRecords++; } } const rec: PackRecord = { id, url: str(raw.url) ?? "", platform: str(raw.platform) ?? "", author: str(raw.author) ?? "", ...(str(raw.authorName) ? { authorName: str(raw.authorName) } : {}), createdAt: raw.createdAt as string, kind: postKind(raw), text: str(raw.text) ?? "", ...(str(raw.lang) ? { lang: str(raw.lang) } : {}), ...(str(raw.threadId) ? { threadId: str(raw.threadId) } : {}), ...(raw.replyTo !== undefined ? { replyTo: raw.replyTo } : {}), ...(raw.quoted !== undefined ? { quoted: raw.quoted } : {}), ...(raw.repostOf !== undefined ? { repostOf: raw.repostOf } : {}), links: Array.isArray(raw.links) ? raw.links : [], ...(raw.engagement !== undefined ? { engagement: raw.engagement } : {}), ...(typeof raw.mediaCount === "number" ? { mediaCount: raw.mediaCount } : {}), channels, capturedAt: str(capture?.capturedAt) ?? null, capture, availability: avail, ...(Object.keys(context).length ? { context } : {}), files: [], raw, }; const elsewhere = list.slice(1).filter((l) => !sameJson(l.raw, raw)); if (elsewhere.length) rec.rawElsewhere = elsewhere.map((l) => ({ channel: l.channel, raw: l.raw })); if (opts.media) { for (const plan of await planMedia(opts.channelsDir, id, channels, captures)) copies.push({ rec, plan }); } records.push(rec); } records.sort(byCreated); const byKind: Record = {}; for (const r of records) byKind[r.kind] = (byKind[r.kind] ?? 0) + 1; const mediaBytes = copies.reduce((n, c) => n + c.plan.bytes, 0); const result: PackResult = { out, dryRun: opts.dryRun, channels: sources.map((s) => ({ slug: s.slug, records: s.records, shards: s.shards.length })), posts: records.length, byKind, contextRecords, mediaFiles: copies.length, mediaBytes, mediaMismatches: [], firstPostAt: records[0]?.createdAt ?? null, lastPostAt: records.at(-1)?.createdAt ?? null, files: 0, sumsSha256: null, stamp: { status: "skipped" }, }; if (opts.dryRun) return result; if (!records.length) throw new EvidenceRefusal("evidence pack: no post matches (check --handle, --since and --until); nothing written"); // Build in a sibling staging dir, then rename into place. const parent = path.dirname(out); await mkdir(parent, { recursive: true }); const staging = path.join(parent, `.${path.basename(out)}.partial-${process.pid}`); await mkdir(staging); const known = new Map(); for (const { rec, plan } of copies) { const dest = path.join(staging, plan.rel); await mkdir(path.dirname(dest), { recursive: true }); await copyFile(plan.src, dest, fsConstants.COPYFILE_EXCL); const st = await stat(plan.src); await utimes(dest, st.atime, st.mtime); const sha256 = await sha256File(dest); known.set(plan.rel, sha256); const file: PackFile = { path: plan.rel, bytes: plan.bytes, sha256, from: plan.from, ...(plan.archivedSha256 ? { archivedSha256: plan.archivedSha256 } : {}), ...(plan.sourceUrl ? { sourceUrl: plan.sourceUrl } : {}), }; if (plan.archivedSha256 && plan.archivedSha256 !== sha256) result.mediaMismatches.push(plan.rel); rec.files.push(file); } const postsJsonl = records.map((r) => JSON.stringify(r)).join("\n") + "\n"; await writeFile(path.join(staging, "posts.jsonl"), postsJsonl, "utf8"); await writeFile(path.join(staging, "posts.csv"), csvForRecords(records), "utf8"); const manifest = { version: PACK_VERSION, kind: "archilyzer-evidence-pack", generatedAt: now.toISOString(), tool: { name: "archilyzer evidence pack", commit: opts.toolCommit ?? null }, filter: { channels: opts.slugs, handle: opts.handle ?? null, since: opts.since ?? null, until: opts.until ?? null, media: opts.media }, counts: { posts: records.length, byKind, contextRecords, mediaFiles: copies.length, mediaBytes, mediaArchivedHashMismatches: result.mediaMismatches, }, range: { first: result.firstPostAt, last: result.lastPostAt }, channels: sources.map((s) => ({ slug: s.slug, name: str(s.config?.name) ?? null, platform: str(s.config?.platform) ?? null, url: str(s.config?.url) ?? null, socialHandle: str(s.config?.socialHandle) ?? null, postFetcher: str(s.config?.postFetcher) ?? null, lastSyncedAt: str(s.config?.lastSyncedAt) ?? null, lastFetchedAt: str(s.fetchState?.lastFetchedAt) ?? null, records: s.records, shards: s.shards, })), }; await writeFile(path.join(staging, "pack.json"), JSON.stringify(manifest, null, 2) + "\n", "utf8"); await writeFile(path.join(staging, "README.md"), readme(manifest, result), "utf8"); const sums = await writeSums(staging, known); result.files = sums.files; result.sumsSha256 = sums.sha256; try { await rmdir(out); // an empty dir the operator made for it (checked above) } catch { /* absent */ } await rename(staging, out); if (opts.stamp) result.stamp = await stampDir(out, opts.ots ?? defaultOtsRunner()); return result; } function human(bytes: number): string { const u = ["B", "KB", "MB", "GB", "TB"]; let n = bytes; let i = 0; while (n >= 1000 && i < u.length - 1) { n /= 1000; i++; } return `${i ? n.toFixed(1) : n} ${u[i]}`; } type Manifest = { generatedAt: string; filter: { channels: string[]; handle: string | null; since: string | null; until: string | null; media: boolean }; channels: { slug: string; name: string | null; url: string | null; postFetcher: string | null; lastFetchedAt: string | null }[]; tool: { commit: string | null }; }; export function readme(m: Manifest, r: PackResult): string { const who = m.filter.handle ? `@${m.filter.handle.replace(/^@/, "")}` : "every author in the channels"; const range = r.firstPostAt ? `${r.firstPostAt} to ${r.lastPostAt}` : "none"; const kinds = Object.entries(r.byKind) .map(([k, n]) => `${n} ${k}${n === 1 ? "" : "s"}`) .join(", "); return `# Evidence package: archived posts of ${who} Generated ${m.generatedAt} by \`archilyzer evidence pack\`${m.tool.commit ? ` (Archilyzer commit ${m.tool.commit})` : ""}. This folder is a copy of posts as an Archilyzer archive recorded them when it fetched them from the platform, made so that anyone can check it without the archive or its software. - **${r.posts} posts** (${kinds}), created ${range} (UTC). - **${r.mediaFiles} media files** (${human(r.mediaBytes)})${m.filter.media ? "" : " — media were left out (--no-media)"}. - ${r.contextRecords} archived records of other authors' posts these answer, quote or repost, as context. - Filter: ${m.filter.handle ? `author @${m.filter.handle}` : "every author"}${m.filter.since ? `, from ${m.filter.since}` : ""}${m.filter.until ? `, to ${m.filter.until}` : ""} (dates are the post's UTC day). ## Where the posts came from ${m.channels .map( (c) => `- \`${c.slug}\`${c.name ? ` (${c.name})` : ""}${c.url ? `: ${c.url}` : ""}${c.postFetcher ? `, fetched with ${c.postFetcher}` : ""}${c.lastFetchedAt ? `, last fetched ${c.lastFetchedAt}` : ""}`, ) .join("\n")} \`pack.json\` lists each source file read (the channel's month shards of posts) with its size and SHA-256 at the time of packing. ## The files | File | What it is | |---|---| | \`posts.jsonl\` | One JSON record per post, oldest first: id, url, author, createdAt, kind, text, reply/quote/repost references, engagement as archived, the channels that archived it, the capture record (\`capture\`, when the post was opened and shot in a browser — \`capturedAt\` is that time), its last availability check, and its media files with their SHA-256. **\`raw\` is the archived record exactly as stored**, every field; \`context\` holds the archived record of a post it answers or quotes when the archive holds it. | | \`posts.csv\` | The same posts as a table: id, url, created_at, author, author_name, kind, text, reply_to_url, quoted_url, repost_of_url, media_files, captured_at, channels. RFC 4180 (UTF-8, CRLF rows, fields with quotes, commas or line breaks quoted). Text is verbatim: a spreadsheet may read a cell starting with \`=\`, \`+\`, \`-\` or \`@\` as a formula. | | \`media//\` | The post's files as archived, byte for byte (pictures and videos the post carried, \`shot.png\` — a screenshot of the post's page at capture time — and \`capture.json\`, the capture's own record, which names each file's SHA-256 when it was saved). | | \`pack.json\` | How this package was made: the filter, the counts, the source channels and source files. | | \`SHA256SUMS\` | The SHA-256 of every file above. | | \`SHA256SUMS.ots\` | An OpenTimestamps proof that \`SHA256SUMS\` existed at a point in time. | ## How to verify 1. **The files are what was packaged.** In this folder: \`\`\`sh sha256sum -c SHA256SUMS # every line must say OK \`\`\` 2. **The package existed no later than a Bitcoin block.** \`SHA256SUMS.ots\` commits the SHA-256 of \`SHA256SUMS\` (\`sha256sum SHA256SUMS\` prints it; this README is listed in it, so it cannot name it) to public OpenTimestamps calendars, which commit it to the Bitcoin blockchain within a few hours. With the OpenTimestamps client (\`pip install opentimestamps-client\`, or \`uv tool install opentimestamps-client\`): \`\`\`sh ots upgrade SHA256SUMS.ots # once, a few hours after packing: fetch the Bitcoin attestation ots info SHA256SUMS.ots # the proof's path, ending in the block height it is attested in ots verify SHA256SUMS.ots # checks it against a Bitcoin node (bitcoind) on this machine \`\`\` Without a Bitcoin node, drop \`SHA256SUMS\` and \`SHA256SUMS.ots\` on https://opentimestamps.org, or compare the merkle root \`ots info\` ends with against the block's header on any block explorer. Because \`SHA256SUMS\` names every file's hash, the timestamp covers every file in the folder: a file changed after the timestamp no longer matches its line. 3. **The media are what the archive saved.** Each \`media//capture.json\` names the SHA-256 the archive computed when it saved each file; \`posts.jsonl\` repeats it as \`archivedSha256\` beside the copy's \`sha256\`.${r.mediaMismatches.length ? ` ${r.mediaMismatches.length} files differ from it (named in \`pack.json\`, \`counts.mediaArchivedHashMismatches\`).` : " Every one matches."} ## What this does and does not show It shows that these records and files existed, in this form, no later than the time the timestamp attests, and that the archive recorded them as fetched from the URLs given. It is not a capture by an independent third party: the posts were fetched by this archive's own tools (see \`pack.json\`). Where a public archive (the Wayback Machine, archive.today) holds a copy of a post, that copy is independent corroboration. `; } // --------------------------------------------------------------------------- // OpenTimestamps export type OtsRunner = (args: string[], cwd: string) => Promise<{ code: number; stdout: string; stderr: string }>; export function otsBin(env: NodeJS.ProcessEnv = process.env): string | null { if (env.ARCHILYZER_OTS_BIN) return env.ARCHILYZER_OTS_BIN; const which = spawnSync("sh", ["-c", "command -v ots"], { encoding: "utf8" }); const found = which.status === 0 ? which.stdout.trim() : ""; if (found) return found; const local = path.join(os.homedir(), ".local", "bin", "ots"); return spawnSync(local, ["--version"], { encoding: "utf8" }).status === 0 ? local : null; } export function defaultOtsRunner(bin: string | null = otsBin()): OtsRunner { return (args, cwd) => new Promise((resolve) => { if (!bin) { resolve({ code: 127, stdout: "", stderr: "the OpenTimestamps client (ots) is not installed: uv tool install opentimestamps-client" }); return; } const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] }); let stdout = ""; let stderr = ""; child.stdout.on("data", (d) => (stdout += d)); child.stderr.on("data", (d) => (stderr += d)); const timer = setTimeout(() => child.kill("SIGTERM"), 120_000); child.on("error", (err) => { clearTimeout(timer); resolve({ code: 127, stdout, stderr: stderr + String(err) }); }); child.on("close", (code) => { clearTimeout(timer); resolve({ code: code ?? 1, stdout, stderr }); }); }); } /** The attestations `ots info` names: the calendars still pending, and the Bitcoin blocks. */ export function parseOtsInfo(info: string): { calendars: string[]; blocks: number[] } { const calendars = [...new Set([...info.matchAll(/PendingAttestation\('([^']+)'\)/g)].map((m) => m[1]))]; const blocks = [...new Set([...info.matchAll(/BitcoinBlockHeaderAttestation\((\d+)\)/g)].map((m) => Number(m[1])))].sort( (a, b) => a - b, ); return { calendars, blocks }; } async function otsInfo(dir: string, ots: OtsRunner): Promise { const info = await ots(["info", OTS_FILE], dir); if (info.code !== 0) return { status: "failed", error: `ots info: ${(info.stderr || info.stdout).trim()}` }; const { calendars, blocks } = parseOtsInfo(info.stdout); return { status: blocks.length ? "attested" : "pending", calendars, blocks, info: info.stdout }; } async function exists(p: string): Promise { try { await lstat(p); return true; } catch { return false; } } /** `ots stamp SHA256SUMS` in dir (one request to each of the client's calendars), then its state. */ export async function stampDir(dir: string, ots: OtsRunner): Promise { if (!(await exists(path.join(dir, SUMS_FILE)))) return { status: "failed", error: `${dir} has no ${SUMS_FILE}` }; if (await exists(path.join(dir, OTS_FILE))) return { status: "failed", error: `${dir} is stamped already (${OTS_FILE}); use evidence upgrade` }; const run = await ots(["stamp", SUMS_FILE], dir); if (run.code === 127) return { status: "unavailable", error: run.stderr.trim() }; if (run.code !== 0 || !(await exists(path.join(dir, OTS_FILE)))) { return { status: "failed", error: `ots stamp exited ${run.code}: ${(run.stderr || run.stdout).trim()}` }; } return otsInfo(dir, ots); } /** `ots upgrade SHA256SUMS.ots`: the calendars' Bitcoin attestation once they have one. */ export async function upgradeDir(dir: string, ots: OtsRunner): Promise { if (!(await exists(path.join(dir, OTS_FILE)))) { return { status: "failed", error: `${dir} has no ${OTS_FILE}; run archilyzer evidence stamp ${dir} first` }; } const before = await otsInfo(dir, ots); if (before.status === "attested") return before; // The client exits non-zero while the timestamp is still pending; the info after says which it is. const run = await ots(["upgrade", OTS_FILE], dir); if (run.code === 127) return { status: "unavailable", error: run.stderr.trim() }; return otsInfo(dir, ots); } export type VerifyResult = { ok: boolean; checked: number; missing: string[]; changed: string[]; unlisted: string[]; sumsSha256: string; stamp: StampResult | { status: "absent" }; }; export async function verifyDir(dir: string, ots: OtsRunner): Promise { const sumsText = await readFile(path.join(dir, SUMS_FILE), "utf8"); const sums = parseSums(sumsText); const present = new Set((await listFiles(dir)).filter((f) => !excludedFromSums(f))); const missing: string[] = []; const changed: string[] = []; for (const [rel, want] of sums) { if (!present.has(rel)) { missing.push(rel); continue; } if ((await sha256File(path.join(dir, rel))) !== want) changed.push(rel); } const unlisted = [...present].filter((f) => !sums.has(f)); const stamp = (await exists(path.join(dir, OTS_FILE))) ? await otsInfo(dir, ots) : ({ status: "absent" } as const); return { ok: !missing.length && !changed.length && !unlisted.length, checked: sums.size, missing, changed, unlisted, sumsSha256: sha256Text(sumsText), stamp, }; } // --------------------------------------------------------------------------- // CLI function flagStr(v: FlagValue | undefined): string | undefined { return typeof v === "string" ? v : undefined; } function toolCommit(): string | null { const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const r = spawnSync("git", ["-C", repo, "rev-parse", "HEAD"], { encoding: "utf8" }); return r.status === 0 ? r.stdout.trim() : null; } function stampLine(s: StampResult | { status: "absent" }): string { switch (s.status) { case "pending": return `stamp: pending — submitted to ${s.calendars.length} calendar${s.calendars.length === 1 ? "" : "s"} (${s.calendars.join(", ")}); run \`archilyzer evidence upgrade \` in a few hours for the Bitcoin attestation`; case "attested": return `stamp: attested in Bitcoin block ${s.blocks.join(", ")}`; case "absent": return "stamp: none (no SHA256SUMS.ots)"; case "skipped": return "stamp: skipped"; default: return `stamp: ${s.status}${s.error ? ` — ${s.error}` : ""}`; } } export async function packMain( positionals: string[], flags: Record, deps: { channelsDir: string; transcriptsDir: string; guardText?: (slug: string) => Promise; ots?: OtsRunner; log?: (s: string) => void; error?: (s: string) => void }, ): Promise { const log = deps.log ?? console.log; const error = deps.error ?? console.error; const slugs = positionals.flatMap((p) => p.split(",")).map((s) => s.trim()).filter(Boolean); if (flags.media === true && flags["no-media"] === true) { error("evidence pack: --media and --no-media together"); return 2; } if (flags.stamp === true && flags["no-stamp"] === true) { error("evidence pack: --stamp and --no-stamp together"); return 2; } const since = parseDay(flagStr(flags.since)); const until = parseDay(flagStr(flags.until)); if (since === null || until === null) { error("evidence pack: --since and --until are dates, YYYY-MM-DD"); return 2; } if (since && until && since > until) { error("evidence pack: --since is after --until"); return 2; } const handle = flagStr(flags.handle)?.trim().replace(/^@/, "") || undefined; const now = new Date(); const out = flagStr(flags.out) ?? defaultOutDir(handle ?? slugs[0] ?? "posts", now); try { const r = await pack({ channelsDir: deps.channelsDir, transcriptsDir: deps.transcriptsDir, slugs, handle, since, until, out, media: flags["no-media"] !== true, stamp: flags["no-stamp"] !== true, dryRun: flags["dry-run"] === true, now, guardText: deps.guardText, ots: deps.ots, toolCommit: toolCommit(), }); if (flags.json === true) { log(JSON.stringify(r, null, 2)); } else { log(`${r.dryRun ? "would write" : "wrote"} ${r.out}`); for (const c of r.channels) log(` ${c.slug}: ${c.records} archived records in ${c.shards} shard${c.shards === 1 ? "" : "s"}`); log( ` ${r.posts} posts (${Object.entries(r.byKind).map(([k, n]) => `${n} ${k}`).join(", ") || "none"}), ${r.firstPostAt ?? "-"} to ${r.lastPostAt ?? "-"}; ${r.contextRecords} context records`, ); log(` ${r.mediaFiles} media files, ${human(r.mediaBytes)}${r.mediaMismatches.length ? `; ${r.mediaMismatches.length} differ from the hash their capture recorded` : ""}`); if (!r.dryRun) { log(` ${r.files} files in SHA256SUMS; sha256(SHA256SUMS) = ${r.sumsSha256}`); log(` ${stampLine(r.stamp)}`); } } if (!r.dryRun && flags["no-stamp"] !== true && r.stamp.status !== "pending" && r.stamp.status !== "attested") { error(`evidence pack: the package is written, but it is not stamped (${r.stamp.status}); run archilyzer evidence stamp ${r.out}`); return 1; } return 0; } catch (err) { if (err instanceof EvidenceRefusal || (err as Error)?.name === "ChannelTextUnreadableError") { error((err as Error).message); return 2; } throw err; } } export async function dirMain( verb: "stamp" | "upgrade" | "verify", positionals: string[], flags: Record, deps: { ots?: OtsRunner; log?: (s: string) => void; error?: (s: string) => void } = {}, ): Promise { const log = deps.log ?? console.log; const error = deps.error ?? console.error; const [d] = positionals; if (!d) { error(`evidence ${verb}: which package? Pass its directory.`); return 2; } const dir = path.resolve(expandHome(d)); if (!(await exists(path.join(dir, SUMS_FILE)))) { error(`evidence ${verb}: ${dir} has no ${SUMS_FILE} — not an evidence package`); return 2; } const ots = deps.ots ?? defaultOtsRunner(); if (verb === "verify") { const v = await verifyDir(dir, ots); if (flags.json === true) log(JSON.stringify(v, null, 2)); else { log(`${v.ok ? "OK" : "FAILED"}: ${v.checked} files in SHA256SUMS; sha256(SHA256SUMS) = ${v.sumsSha256}`); for (const f of v.missing) log(` missing: ${f}`); for (const f of v.changed) log(` changed: ${f}`); for (const f of v.unlisted) log(` not in SHA256SUMS: ${f}`); log(` ${stampLine(v.stamp)}`); } return v.ok ? 0 : 1; } const s = verb === "stamp" ? await stampDir(dir, ots) : await upgradeDir(dir, ots); if (flags.json === true) log(JSON.stringify(s, null, 2)); else log(stampLine(s)); return s.status === "pending" || s.status === "attested" ? 0 : 1; }