// The avatar read and download in a REAL headless Chromium, against a // recorded-style X status page (__fixtures__/x-post-avatars.html) — never // x.com. The browser's every request to x.com is answered by the fixture // through the context's router, anything else not on the test's loopback // server is aborted, and the host resolver maps every other name to nowhere, // so nothing can leave the machine. The pictures are served by a loopback // server at X's profile_images path. // // What it proves: the read finds the author's, the quoted post's and the // parent's avatars in X's markup; the download is the _400x400 size, fetched // ONCE per author through the page's own request context (it carries the // context's cookie), with no second page load and the page left where it was; // an avatars-only run writes no capture record; a normal run shoots the post // and reads the avatars from the same load. And the post's CONTEXT // (xPostContext.ts) off the same page: the parent's and the quoted post's // author, check, date, words and media, into capture.json -- on a normal run, // and on a context-only one (one page load, nothing shot). // // Skips where Playwright or its Chromium is not installed. With // AVATAR_PROOF_DIR set, it leaves a screenshot, the store and a log there. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xAvatarCapture.browser.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { cp, mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; import http from "node:http"; import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { importPlaywright, type PageLike } from "./playwrightRuntime"; import { captureXPosts, type XCaptureDeps } from "./xPostCapture"; import { AVATARS_DIRNAME, readXAvatarIndex } from "./xAvatars"; import { CAPTURE_FILENAME, readPostCapture, SHOT_FILENAME } from "./postCapture"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const FIX = path.join(HERE, "__fixtures__"); const POST_ID = "1850000000000000001"; const PARENT_ID = "1849999999999999990"; type Served = { path: string; cookie?: string; drawnByPage?: boolean }; async function fixtureServer() { const normal = await readFile(path.join(FIX, "x-avatar_normal.jpg")); const big = await readFile(path.join(FIX, "x-avatar_400x400.jpg")); const quoted = await readFile(path.join(FIX, "x-avatar-quoted_400x400.jpg")); const served: Served[] = []; const server = http.createServer((req, res) => { const p = (req.url ?? "").split("?")[0]; served.push({ path: p, ...(req.headers.cookie ? { cookie: req.headers.cookie } : {}), ...(req.headers["x-drawn-by"] ? { drawnByPage: true } : {}), }); const m = /^\/profile_images\/\d+\/([A-Za-z0-9_-]+?)_(normal|mini|400x400)\.jpg$/.exec(p); if (!m) { res.writeHead(404).end(); return; } const body = m[2] !== "400x400" ? normal : m[1] === "Mr_O" ? big : quoted; res.writeHead(200, { "content-type": "image/jpeg", "content-length": body.length }).end(body); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; const html = (await readFile(path.join(FIX, "x-post-avatars.html"), "utf8")).replaceAll("{{ORIGIN}}", origin); return { origin, html, served, close: () => new Promise((r) => server.close(() => r())) }; } type PwPage = PageLike & { url: () => string; mainFrame: () => unknown; on: (event: "framenavigated", cb: (f: { url: () => string }) => void) => void; }; test("in a real Chromium: the avatars read off a recorded-style X page and fetched through its own context", async (t) => { let chromium; try { ({ chromium } = await importPlaywright()); } catch (err) { t.skip(`Playwright is not installed here: ${(err as Error).message.slice(0, 80)}`); return; } const fx = await fixtureServer(); let browser; try { browser = await chromium.launch({ headless: true, // Nothing resolves but the loopback server: x.com is answered by the router. args: ["--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"], }); } catch (err) { await fx.close(); t.skip(`Chromium would not launch: ${(err as Error).message.slice(0, 80)}`); return; } const proofDir = process.env.AVATAR_PROOF_DIR; const log: string[] = []; const onLog = (line: string) => log.push(line); try { const context = (await browser.newContext({ viewport: { width: 1000, height: 900 } })) as unknown as { newPage: () => Promise; route: (url: string, handler: (route: Route) => Promise) => Promise; addCookies: (c: Record[]) => Promise; close: () => Promise; }; type Route = { request: () => { url: () => string; resourceType: () => string }; fulfill: (o: Record) => Promise; continue: () => Promise; abort: () => Promise; }; const docLoads: string[] = []; const blocked: string[] = []; await context.route("**/*", async (route) => { const u = new URL(route.request().url()); if (u.hostname === "x.com") { docLoads.push(u.pathname); await route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: fx.html }); } else if (u.hostname === "127.0.0.1" && u.port === new URL(fx.origin).port) { // The page's own pictures. An https page's http image is mixed // content Chromium upgrades to https, which the loopback server does // not speak: answered from it here, so the page draws them. const r = await fetch(`${fx.origin}${u.pathname}${u.search}`, { headers: { "x-drawn-by": "page" } }); await route.fulfill({ status: r.status, contentType: r.headers.get("content-type") ?? "application/octet-stream", body: Buffer.from(await r.arrayBuffer()), }); } else { blocked.push(u.href); await route.abort(); } }); // The profile's cookie, as the live context carries X's: the download // must arrive with it. await context.addCookies([{ name: "auth_token", value: "fixture-session", domain: "127.0.0.1", path: "/" }]); const page = await context.newPage(); const navs: string[] = []; page.on("framenavigated", (f) => { if (f === page.mainFrame()) navs.push(f.url()); }); const out = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatar-browser-")), "posts-media"); const deps: XCaptureDeps = { openPage: async () => ({ page, close: async () => {} }), downloadMedia: async () => ({ ok: true, files: [] }), pauseMs: () => 0, pause: async () => {}, }; const archived = new Map([ [POST_ID, { text: "", author: "ObviousRises", isReply: true, replyTo: { id: PARENT_ID, author: "parent_person" } }], ]); // 1. avatarsOnly, thread on: the author's, the quoted post's and the parent's. const res = await captureXPosts( { ids: [POST_ID], handle: "ObviousRises", outDir: out, signal: new AbortController().signal, avatarsOnly: true, thread: true, archived, onLog }, deps, ); assert.deepEqual(res.outcomes, []); assert.deepEqual(res.avatars?.stored, ["ObviousRises", "quoted_person", "parent_person"], log.join("\n")); assert.deepEqual(res.avatars?.failed, []); // One page load, and the page is where it was. assert.deepEqual(docLoads, [`/i/status/${POST_ID}`]); assert.deepEqual(navs, [`https://x.com/i/status/${POST_ID}`]); assert.equal(page.url(), `https://x.com/i/status/${POST_ID}`); assert.deepEqual(blocked, []); // Each author's 400×400, once, through the context (its cookie on it). const bigs = fx.served.filter((s) => s.path.endsWith("_400x400.jpg")); assert.deepEqual( bigs.map((s) => s.path).sort(), [ "/profile_images/1712345678901234567/Mr_O_400x400.jpg", "/profile_images/777/pp_400x400.jpg", "/profile_images/888/qq_400x400.jpg", ], ); for (const s of bigs) assert.match(s.cookie ?? "", /auth_token=fixture-session/, s.path); // Not one of them is a picture the page drew: those are the small sizes. assert.ok(bigs.every((s) => !s.drawnByPage)); assert.ok(fx.served.some((s) => s.drawnByPage && s.path.endsWith("Mr_O_normal.jpg")), "the page drew the 48px one"); // The reply under the post is never read. assert.ok(!fx.served.some((s) => s.path.includes("rr_400x400"))); const store = path.join(out, AVATARS_DIRNAME); const index = await readXAvatarIndex(store); assert.deepEqual(Object.keys(index), ["ObviousRises", "parent_person", "quoted_person"]); assert.equal(index.ObviousRises.url, `${fx.origin}/profile_images/1712345678901234567/Mr_O_400x400.jpg`); assert.equal(index.ObviousRises.postId, POST_ID); assert.deepEqual( await readFile(path.join(store, "ObviousRises.jpg")), await readFile(path.join(FIX, "x-avatar_400x400.jpg")), "the stored picture is the 400×400, not the 48px one the page drew", ); // No capture record: posts-media holds the store and nothing else. assert.deepEqual(await readdir(out), [AVATARS_DIRNAME]); // 2. A normal run on the same page: the shot, and the avatar already // stored is not fetched again. const before = fx.served.filter((s) => s.path.endsWith("_400x400.jpg")).length; const res2 = await captureXPosts( { ids: [POST_ID], handle: "ObviousRises", outDir: out, signal: new AbortController().signal, media: false, articles: false, onLog }, deps, ); assert.equal(res2.outcomes[0]?.state, "captured", log.join("\n")); assert.deepEqual(res2.avatars?.skipped, ["ObviousRises"]); assert.equal(fx.served.filter((s) => s.path.endsWith("_400x400.jpg")).length, before); assert.deepEqual(docLoads, [`/i/status/${POST_ID}`, `/i/status/${POST_ID}`]); const shot = await readFile(path.join(out, POST_ID, SHOT_FILENAME)); assert.equal(shot.readUInt32BE(0), 0x89504e47); // The context, read off the same load: the archive not saying, the // parent is the article above. const ctx = (await readPostCapture(path.join(out, POST_ID)))?.context; assert.ok(ctx, log.join("\n")); assert.deepEqual(ctx.parent, { id: PARENT_ID, url: `https://x.com/parent_person/status/${PARENT_ID}`, handle: "parent_person", author: "A Private Person", verified: true, badge: "blue", date: "2026-10-30T12:00:00.000Z", text: "So what happened next?", media: [], from: "above", }); assert.deepEqual(ctx.quoted, { id: "1849000000000000005", url: "https://x.com/quoted_person/status/1849000000000000005", handle: "quoted_person", author: "Quoted Person", date: "2026-10-29T08:00:00.000Z", text: "The receipt itself.", media: [{ kind: "image", url: `${fx.origin}/media/QQ_receipt.jpg?format=jpg&name=small` }], }); // 3. contextOnly, into a channel with no capture yet: one page load, // nothing shot, the context and the avatars only; the archive's parent id. const out3 = path.join(path.dirname(out), "posts-media-context"); const res3 = await captureXPosts( { ids: [POST_ID], handle: "ObviousRises", outDir: out3, signal: new AbortController().signal, contextOnly: true, archived, onLog }, deps, ); assert.deepEqual(res3.outcomes, []); assert.equal(res3.context?.read, 1, log.join("\n")); assert.deepEqual(docLoads, [`/i/status/${POST_ID}`, `/i/status/${POST_ID}`, `/i/status/${POST_ID}`]); assert.deepEqual(await readdir(path.join(out3, POST_ID)), [CAPTURE_FILENAME]); const rec3 = await readPostCapture(path.join(out3, POST_ID)); assert.equal(rec3?.shot, undefined); assert.equal(rec3?.context?.parent?.from, "reply-to"); assert.equal(rec3?.context?.parent?.id, PARENT_ID); assert.equal(rec3?.context?.quoted?.handle, "quoted_person"); assert.deepEqual(Object.keys(await readXAvatarIndex(path.join(out3, AVATARS_DIRNAME))), ["ObviousRises", "parent_person", "quoted_person"]); assert.deepEqual(blocked, []); if (proofDir) { await mkdir(proofDir, { recursive: true }); await writeFile(path.join(proofDir, "fixture-page.png"), await page.screenshot({ type: "png", fullPage: true })); await cp(path.join(out, POST_ID, SHOT_FILENAME), path.join(proofDir, "fixture-post-shot.png")); await cp(store, path.join(proofDir, "_avatars"), { recursive: true }); await writeFile( path.join(proofDir, "fixture-proof.log"), [ `fixture origin: ${fx.origin} (x.com answered by the context router; everything else unresolvable)`, `document loads (x.com): ${JSON.stringify(docLoads)}`, `main-frame navigations: ${JSON.stringify(navs)}`, `page.url() after the runs: ${page.url()}`, `blocked requests: ${JSON.stringify(blocked)}`, "served by the loopback server (path, cookie):", ...fx.served.map( (s) => ` ${s.path}${s.drawnByPage ? " [drawn by the page]" : ""}${s.cookie ? ` [cookie: ${s.cookie}]` : ""}`, ), `avatars.json: ${JSON.stringify(index, null, 2)}`, "run log:", ...log.map((l) => ` ${l}`), "", ].join("\n"), ); } await context.close(); } finally { await browser.close(); await fx.close(); } });