import { test } from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { mkdtemp, mkdir, readFile, readdir, rm, writeFile, stat } from "node:fs/promises"; import { spawnSync } from "node:child_process"; import os from "node:os"; import path from "node:path"; import { CSV_HEADER, OTS_FILE, SUMS_FILE, csvField, dirMain, inScope, pack, packMain, parseDay, parseOtsInfo, parseSums, postKind, sumsLine, verifyDir, type OtsRunner, } from "./evidence-pack"; // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test bin/evidence-pack.test.ts // // `archilyzer evidence pack` over a temp corpus: two posts channels (an account // and its replies, overlapping), their media, and the OTS client stubbed — it // writes a placeholder SHA256SUMS.ots and `ots info` answers a pending line. const sha = (b: string | Buffer) => createHash("sha256").update(b).digest("hex"); const PENDING_INFO = "File sha256 hash: 00\nTimestamp:\nappend aa\nsha256\n -> verify PendingAttestation('https://a.pool.opentimestamps.org')\n -> verify PendingAttestation('https://b.pool.opentimestamps.org')\n"; function stubOts(calls: string[][] = []): OtsRunner { return async (args, cwd) => { calls.push(args); if (args[0] === "stamp") { await writeFile(path.join(cwd, OTS_FILE), Buffer.from([0x00, 0x4f, 0x70])); return { code: 0, stdout: "", stderr: "Submitting to remote calendar https://a.pool.opentimestamps.org\n" }; } if (args[0] === "info") return { code: 0, stdout: PENDING_INFO, stderr: "" }; if (args[0] === "upgrade") return { code: 1, stdout: "", stderr: "Timestamp not complete\n" }; return { code: 2, stdout: "", stderr: "?" }; }; } function rec(over: Record): Record { return { id: "1", slug: "acct-x/1", channelSlug: "acct-x", author: "Acct", createdAt: "2026-10-01T10:00:00.000Z", uploadDate: "20261001", text: "hello", url: "https://x.com/Acct/status/1", platform: "twitter", isReply: false, isRepost: false, links: [], threadId: "1", authorName: "THE ACCOUNT", engagement: { likes: 3 }, ...over, }; } async function fixture(): Promise<{ root: string; transcripts: string; channels: string }> { const root = await mkdtemp(path.join(os.tmpdir(), "evidence-pack-")); const transcripts = path.join(root, "transcripts"); const channels = path.join(transcripts, "channels"); const a = path.join(channels, "acct-x"); const b = path.join(channels, "acct-x-replies"); await mkdir(path.join(a, "posts"), { recursive: true }); await mkdir(path.join(b, "posts"), { recursive: true }); await writeFile(path.join(a, "config.json"), JSON.stringify({ sourceKind: "social", platform: "twitter", name: "Acct (X)", url: "https://x.com/Acct", socialHandle: "Acct" })); await writeFile(path.join(b, "config.json"), JSON.stringify({ sourceKind: "social", platform: "twitter", name: "Acct replies", postFetcher: "x-gallery-dl" })); await writeFile(path.join(a, "posts-state.json"), JSON.stringify({ lastFetchedAt: "2026-11-05T03:22:28.024Z" })); const lines = (rs: Record[]) => rs.map((r) => JSON.stringify(r)).join("\n") + "\n"; await writeFile( path.join(a, "posts", "2026-10.jsonl"), lines([ rec({ id: "1", text: 'He said "no", then,\nleft.' }), rec({ id: "2", createdAt: "2026-10-20T00:00:00.000Z", text: "RT @x: y", isRepost: true, repostOf: { platform: "twitter", id: "9", author: "x" } }), rec({ id: "3", createdAt: "2026-10-25T00:00:00.000Z", quoted: { platform: "twitter", id: "50", url: "https://x.com/o/status/50" }, mediaCount: 1 }), rec({ id: "4", createdAt: "2026-11-02T00:00:00.000Z", text: "stale four" }), ]) + "{not json\n", ); // Post 4 is in both shards (an interrupted write): the later shard wins. await writeFile(path.join(a, "posts", "2026-11.jsonl"), lines([rec({ id: "4", createdAt: "2026-11-02T00:00:00.000Z", text: "four" })])); await writeFile( path.join(b, "posts", "2026-10.jsonl"), lines([ // the same post 3, archived with other engagement rec({ id: "3", channelSlug: "acct-x-replies", createdAt: "2026-10-25T00:00:00.000Z", quoted: { platform: "twitter", id: "50", url: "https://x.com/o/status/50" }, mediaCount: 1, engagement: { likes: 9 } }), rec({ id: "50", author: "Other", createdAt: "2026-10-24T00:00:00.000Z", text: "the quoted post", url: "https://x.com/o/status/50" }), rec({ id: "5", createdAt: "2026-10-26T00:00:00.000Z", isReply: true, replyTo: { platform: "twitter", id: "50", author: "Other" }, text: "a reply" }), rec({ id: "../evil", createdAt: "2026-10-26T00:00:00.000Z" }), ]), ); // Media for post 3: in both channels, with a capture.json naming one file's hash. const m3 = path.join(a, "posts-media", "3"); await mkdir(m3, { recursive: true }); await writeFile(path.join(m3, "3_1.jpg"), "JPEGBYTES"); await writeFile(path.join(m3, "shot.png"), "PNGBYTES"); await writeFile( path.join(m3, "capture.json"), JSON.stringify({ version: 1, id: "3", capturedAt: "2026-11-04T03:32:55.079Z", state: "captured", shot: { name: "shot.png", sha256: sha("PNGBYTES") }, media: [{ name: "3_1.jpg", sha256: sha("JPEGBYTES"), url: "https://pbs.twimg.com/media/A" }] }), ); const m3b = path.join(b, "posts-media", "3"); await mkdir(m3b, { recursive: true }); await writeFile(path.join(m3b, "3_1.jpg"), "OTHER-COPY"); await writeFile(path.join(m3b, "shot-thread.png"), "THREADSHOT"); // A post whose recorded hash disagrees with its file. const m4 = path.join(a, "posts-media", "4"); await mkdir(m4, { recursive: true }); await writeFile(path.join(m4, "4_1.mp4"), "VIDEO"); await writeFile(path.join(m4, "capture.json"), JSON.stringify({ capturedAt: "2026-11-04T00:00:00.000Z", media: [{ name: "4_1.mp4", sha256: sha("SOMETHING ELSE") }] })); await writeFile(path.join(a, "posts-availability.json"), JSON.stringify({ "1": { availability: "available", checkedAt: "2026-11-04T02:40:57.558Z", history: [] } })); return { root, transcripts, channels }; } function opts(f: { root: string; transcripts: string; channels: string }, over: Partial[0]> = {}) { return { channelsDir: f.channels, transcriptsDir: f.transcripts, slugs: ["acct-x", "acct-x-replies"], handle: "Acct", out: path.join(f.root, "out", "pkg"), media: true, stamp: true, dryRun: false, now: new Date("2026-11-05T12:00:00Z"), ots: stubOts(), toolCommit: "abc123", ...over, }; } test("helpers: dates, kinds, scope, CSV quoting, sums lines", () => { assert.equal(parseDay("2026-11-05"), "2026-11-05"); assert.equal(parseDay("2026-02-30"), null); assert.equal(parseDay("20261105"), null); assert.equal(parseDay(undefined), undefined); assert.equal(postKind({ isRepost: true }), "repost"); assert.equal(postKind({ isReply: false, replyTo: { id: "1" } }), "reply"); assert.equal(postKind({ quoted: { id: "1" } }), "quote"); assert.equal(postKind({}), "post"); const r = { author: "@ACCT", createdAt: "2026-10-31T23:59:59.000Z" }; assert.equal(inScope(r, { handle: "acct" }), true); assert.equal(inScope(r, { handle: "other" }), false); assert.equal(inScope(r, { since: "2026-10-31", until: "2026-10-31" }), true); assert.equal(inScope(r, { since: "2026-11-01" }), false); assert.equal(csvField("plain"), "plain"); assert.equal(csvField('a "b", c'), '"a ""b"", c"'); assert.equal(csvField("two\nlines"), '"two\nlines"'); assert.equal(csvField("=1+1"), "=1+1"); assert.equal(csvField(undefined), ""); assert.equal(sumsLine("ab", "media/1/x.jpg"), "ab media/1/x.jpg\n"); assert.equal(sumsLine("ab", "a\\b\nc"), "\\ab a\\\\b\\nc\n"); const h = "0".repeat(64); assert.deepEqual([...parseSums(sumsLine(h, "a\\b\nc") + sumsLine(h, "x y"))], [["a\\b\nc", h], ["x y", h]]); assert.deepEqual(parseOtsInfo(PENDING_INFO + "verify BitcoinBlockHeaderAttestation(921000)\n"), { calendars: ["https://a.pool.opentimestamps.org", "https://b.pool.opentimestamps.org"], blocks: [921000], }); }); test("pack: one record a post across the channels, raw kept, context, media copied, sums right", async () => { const f = await fixture(); try { const calls: string[][] = []; const r = await pack(opts(f, { ots: stubOts(calls) })); // 1,2,3,4 from acct-x; 5 from replies; 50 is Other's (context only); ../evil is dropped. assert.equal(r.posts, 5); assert.deepEqual(r.byKind, { post: 2, repost: 1, quote: 1, reply: 1 }); assert.equal(r.contextRecords, 2); // 3 quotes 50, 5 answers 50 assert.equal(r.firstPostAt, "2026-10-01T10:00:00.000Z"); assert.equal(r.lastPostAt, "2026-11-02T00:00:00.000Z"); assert.deepEqual(calls.map((c) => c[0]), ["stamp", "info"]); assert.equal(r.stamp.status, "pending"); const out = r.out; const jsonl = (await readFile(path.join(out, "posts.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); assert.deepEqual(jsonl.map((x) => x.id), ["1", "2", "3", "5", "4"]); const p1 = jsonl[0]; assert.equal(p1.text, 'He said "no", then,\nleft.'); assert.equal(p1.raw.slug, "acct-x/1"); assert.equal(p1.raw.uploadDate, "20261001"); assert.deepEqual(p1.availability, { availability: "available", checkedAt: "2026-11-04T02:40:57.558Z", history: [] }); const p3 = jsonl[2]; assert.deepEqual(p3.channels, ["acct-x", "acct-x-replies"]); assert.equal(p3.raw.engagement.likes, 3); // the first channel's record assert.equal(p3.rawElsewhere[0].channel, "acct-x-replies"); assert.equal(p3.rawElsewhere[0].raw.engagement.likes, 9); assert.equal(p3.context.quoted.text, "the quoted post"); assert.equal(p3.capturedAt, "2026-11-04T03:32:55.079Z"); // The first channel's files win; a name only the second has is added. assert.deepEqual(p3.files.map((x: { path: string }) => x.path), [ "media/3/3_1.jpg", "media/3/capture.json", "media/3/shot.png", "media/3/shot-thread.png", ]); const jpg = p3.files[0]; assert.equal(jpg.sha256, sha("JPEGBYTES")); assert.equal(jpg.archivedSha256, sha("JPEGBYTES")); assert.equal(jpg.sourceUrl, "https://pbs.twimg.com/media/A"); assert.equal(await readFile(path.join(out, "media/3/3_1.jpg"), "utf8"), "JPEGBYTES"); assert.equal(await readFile(path.join(out, "media/3/shot-thread.png"), "utf8"), "THREADSHOT"); assert.deepEqual(r.mediaMismatches, ["media/4/4_1.mp4"]); assert.equal(jsonl[3].context.replyTo.author, "Other"); assert.equal(jsonl[4].text, "four"); // CSV: header, a quoted multi-line field, CRLF rows. const csv = await readFile(path.join(out, "posts.csv"), "utf8"); assert.ok(csv.startsWith(CSV_HEADER.join(",") + "\r\n")); assert.ok(csv.includes('"He said ""no"", then,\nleft."')); assert.ok(csv.includes("media/3/3_1.jpg media/3/capture.json media/3/shot.png media/3/shot-thread.png")); // SHA256SUMS covers every file but itself and the stamp, and each line is right. const sums = parseSums(await readFile(path.join(out, SUMS_FILE), "utf8")); assert.ok(!sums.has(SUMS_FILE) && !sums.has(OTS_FILE)); assert.ok(sums.has("README.md") && sums.has("pack.json") && sums.has("posts.jsonl") && sums.has("posts.csv")); for (const [rel, h] of sums) assert.equal(sha(await readFile(path.join(out, rel))), h, rel); assert.equal(sums.size, r.files); assert.equal(sha(await readFile(path.join(out, SUMS_FILE))), r.sumsSha256); if (spawnSync("sha256sum", ["--version"]).status === 0) { assert.equal(spawnSync("sha256sum", ["-c", "--quiet", SUMS_FILE], { cwd: out }).status, 0); } const manifest = JSON.parse(await readFile(path.join(out, "pack.json"), "utf8")); assert.equal(manifest.channels[0].lastFetchedAt, "2026-11-05T03:22:28.024Z"); assert.equal(manifest.channels[0].shards[0].malformed, 1); assert.equal(manifest.tool.commit, "abc123"); const readme = await readFile(path.join(out, "README.md"), "utf8"); assert.ok(readme.includes("ots verify SHA256SUMS.ots") && readme.includes("sha256sum -c SHA256SUMS")); // No staging dir is left beside it. assert.deepEqual(await readdir(path.dirname(out)), ["pkg"]); // verify: clean, then a changed and an added file are named. const v = await verifyDir(out, stubOts()); assert.equal(v.ok, true); assert.equal(v.stamp.status, "pending"); await writeFile(path.join(out, "media/3/shot.png"), "TAMPERED"); await writeFile(path.join(out, "extra.txt"), "x"); const v2 = await verifyDir(out, stubOts()); assert.deepEqual([v2.ok, v2.changed, v2.unlisted], [false, ["media/3/shot.png"], ["extra.txt"]]); } finally { await rm(f.root, { recursive: true, force: true }); } }); test("pack: --since/--until, --no-media, --dry-run writes nothing, no handle keeps every author", async () => { const f = await fixture(); try { const dry = await pack(opts(f, { dryRun: true, handle: undefined })); assert.equal(dry.posts, 6); // Other's post 50 too assert.equal(dry.contextRecords, 0); assert.equal(dry.mediaFiles, 6); await assert.rejects(stat(dry.out)); const r = await pack(opts(f, { since: "2026-10-20", until: "2026-10-31", media: false, stamp: false })); assert.deepEqual(r.byKind, { repost: 1, quote: 1, reply: 1 }); assert.equal(r.mediaFiles, 0); assert.equal(r.stamp.status, "skipped"); assert.deepEqual((await readdir(r.out)).sort(), ["README.md", "SHA256SUMS", "pack.json", "posts.csv", "posts.jsonl"]); const jsonl = (await readFile(path.join(r.out, "posts.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); assert.ok(jsonl.every((x) => x.files.length === 0)); assert.ok(jsonl.find((x) => x.id === "3").capture); // capture metadata kept without media } finally { await rm(f.root, { recursive: true, force: true }); } }); test("refusals: inside the corpus, over a package, an unreadable channel, not a posts channel, no match", async () => { const f = await fixture(); try { await assert.rejects(pack(opts(f, { out: path.join(f.transcripts, "evidence") })), /inside the corpus/); await assert.rejects(pack(opts(f, { out: path.join(f.channels, "acct-x", "posts-media", "pkg") })), /inside the corpus/); const out = path.join(f.root, "taken"); await mkdir(out); await writeFile(path.join(out, "x"), "x"); await assert.rejects(pack(opts(f, { out })), /not an empty directory/); await assert.rejects( pack(opts(f, { guardText: async (s) => { if (s === "acct-x-replies") throw Object.assign(new Error(`${s}: its text is not readable`), { name: "ChannelTextUnreadableError" }); } })), /text is not readable/, ); await mkdir(path.join(f.channels, "videos"), { recursive: true }); await assert.rejects(pack(opts(f, { slugs: ["videos"] })), /not a posts channel/); await assert.rejects(pack(opts(f, { slugs: ["nope"] })), /no channel "nope"/); await assert.rejects(pack(opts(f, { handle: "nobody" })), /no post matches/); // None of it wrote anything. assert.deepEqual((await readdir(f.root)).sort(), ["taken", "transcripts"]); // The CLI layer: a refusal is exit 2 with its sentence; bad flags are usage errors. const errs: string[] = []; const deps = { channelsDir: f.channels, transcriptsDir: f.transcripts, ots: stubOts(), log: () => {}, error: (s: string) => errs.push(s) }; assert.equal(await packMain(["acct-x"], { out: path.join(f.transcripts, "e") }, deps), 2); assert.match(errs.at(-1)!, /inside the corpus/); assert.equal(await packMain(["acct-x"], { since: "Nov 1" }, deps), 2); assert.equal(await packMain(["acct-x"], { media: true, "no-media": true }, deps), 2); // A stamp that fails leaves the package and exits 1. const unavailable: OtsRunner = async () => ({ code: 127, stdout: "", stderr: "not installed" }); const pkg = path.join(f.root, "pkg2"); assert.equal(await packMain(["acct-x,acct-x-replies"], { handle: "@Acct", out: pkg }, { ...deps, ots: unavailable }), 1); assert.ok((await readdir(pkg)).includes(SUMS_FILE)); assert.match(errs.at(-1)!, /not stamped \(unavailable\)/); // …and `evidence stamp` stamps it later, once; upgrade says it is still pending. const logs: string[] = []; const d = { ots: stubOts(), log: (s: string) => logs.push(s), error: (s: string) => errs.push(s) }; assert.equal(await dirMain("stamp", [pkg], {}, d), 0); assert.match(logs.at(-1)!, /pending — submitted to 2 calendars/); assert.equal(await dirMain("stamp", [pkg], {}, d), 1); assert.equal(await dirMain("upgrade", [pkg], {}, d), 0); assert.match(logs.at(-1)!, /pending/); assert.equal(await dirMain("verify", [pkg], {}, d), 0); assert.equal(await dirMain("verify", [f.root], {}, d), 2); } finally { await rm(f.root, { recursive: true, force: true }); } });