commit 6ba247b6417c5cafe546f6c4e9f66e29ccfe17a0
parent de545b34e235ee585a5854d6da2df466744560a7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 19:46:37 -0500
common: the X avatar store -- posts-media/_avatars/<handle>.<ext> and avatars.json
A post card shows an initial letter because the posts archive keeps no
profile pictures. social/xAvatars.ts is the store umtool reads as plain JSON:
channels/<slug>/posts-media/_avatars/<handle>.<ext> (jpg|png|webp|gif) and
avatars.json, { "<handle>": { file, url, capturedAt, postId } }. Keys keep the
handle's case as X prints it; lookups ignore case and a re-capture under
another case replaces the entry and its file. Handles ^[A-Za-z0-9_]{1,30}$;
writes atomic, the index read-modify-written under the per-file lock, and an
unreadable index is refused rather than overwritten.
upgradeXAvatarUrl maps every size X serves (_normal, _bigger, _mini,
_reasonably_small, _x96, _200x200, _400x400, no suffix) to _400x400, keeping
the extension; X's default egg, another host or another path is null.
postCaptureDir refuses "_avatars", so it is never taken for a post.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
3 files changed, 392 insertions(+), 2 deletions(-)
diff --git a/common/social/postCapture.ts b/common/social/postCapture.ts
@@ -30,6 +30,7 @@ import { readdir, stat } from "node:fs/promises";
import path from "node:path";
import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server";
import type { PostAvailability } from "../lib/posts";
+import { AVATARS_DIRNAME } from "./xAvatars";
export const POSTS_MEDIA_DIRNAME = "posts-media";
export const CAPTURE_FILENAME = "capture.json";
@@ -56,9 +57,10 @@ export function postsMediaDir(channelRoot: string): string {
// One post's capture directory. The id is checked here, at the one place a
// post id becomes a path: a platform-native id is digits (X) or a short
-// alphanumeric key (Bluesky), never a separator.
+// alphanumeric key (Bluesky), never a separator. `_avatars` is the authors'
+// pictures beside them (xAvatars.ts), never a post.
export function postCaptureDir(outDir: string, id: string): string {
- if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) {
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id) || id === AVATARS_DIRNAME) {
throw new Error(`"${id}" is not a post id`);
}
return path.join(outDir, id);
diff --git a/common/social/xAvatars.test.ts b/common/social/xAvatars.test.ts
@@ -0,0 +1,160 @@
+// The avatar store and the URL rule (xAvatars.ts). Temp dirs only.
+//
+// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/xAvatars.test.ts
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ AVATARS_DIRNAME,
+ AVATARS_INDEX_FILENAME,
+ isXAvatarHandle,
+ lookupXAvatar,
+ readXAvatarIndex,
+ upgradeXAvatarUrl,
+ writeXAvatar,
+ xAvatarExtension,
+ xAvatarFile,
+ xAvatarsDir,
+} from "./xAvatars";
+import { postCaptureDir, postsMediaDir } from "./postCapture";
+
+const JPG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 1, 2, 3]);
+const PB = "https://pbs.twimg.com/profile_images/1712345678901234567/AbC-dEf_";
+
+test("url: every size X serves maps to _400x400, the extension and query kept", () => {
+ for (const suffix of ["normal", "bigger", "mini", "reasonably_small", "x96", "200x200", "400x400"]) {
+ assert.equal(upgradeXAvatarUrl(`${PB}${suffix}.jpg`), `${PB}400x400.jpg`, suffix);
+ }
+ // No suffix: the original upload, any size — asked for at 400 too.
+ assert.equal(
+ upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/abc.png"),
+ "https://pbs.twimg.com/profile_images/123/abc_400x400.png",
+ );
+ // A name with an underscore of its own, and no extension at all.
+ assert.equal(
+ upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/my_pic_normal.jpeg"),
+ "https://pbs.twimg.com/profile_images/123/my_pic_400x400.jpeg",
+ );
+ assert.equal(
+ upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/abc_normal"),
+ "https://pbs.twimg.com/profile_images/123/abc_400x400",
+ );
+ assert.equal(
+ upgradeXAvatarUrl("https://pbs.twimg.com/profile_images/123/abc_normal.webp?v=2"),
+ "https://pbs.twimg.com/profile_images/123/abc_400x400.webp?v=2",
+ );
+});
+
+test("url: X's default egg, another host, another path or no URL is no avatar", () => {
+ assert.equal(upgradeXAvatarUrl("https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png"), null);
+ assert.equal(upgradeXAvatarUrl("https://pbs.twimg.com/sticky/default_profile_images/default_profile_400x400.png"), null);
+ assert.equal(upgradeXAvatarUrl("https://evil.example/profile_images/123/abc_normal.jpg"), null);
+ assert.equal(upgradeXAvatarUrl("https://pbs.twimg.com/media/Gabc123?format=jpg&name=small"), null);
+ assert.equal(upgradeXAvatarUrl("data:image/png;base64,AAAA"), null);
+ assert.equal(upgradeXAvatarUrl("not a url"), null);
+ // Loopback is allowed: a test's fixture server.
+ assert.equal(
+ upgradeXAvatarUrl("http://127.0.0.1:4321/profile_images/123/abc_normal.jpg"),
+ "http://127.0.0.1:4321/profile_images/123/abc_400x400.jpg",
+ );
+});
+
+test("extension: the response's type, else the URL's, else jpg", () => {
+ assert.equal(xAvatarExtension(`${PB}400x400.jpg`, "image/png"), "png");
+ assert.equal(xAvatarExtension(`${PB}400x400.jpg`, "image/jpeg; charset=binary"), "jpg");
+ assert.equal(xAvatarExtension(`${PB}400x400.jpeg`), "jpg");
+ assert.equal(xAvatarExtension(`${PB}400x400.webp`, "application/octet-stream"), "webp");
+ assert.equal(xAvatarExtension(`${PB}400x400.gif`), "gif");
+ assert.equal(xAvatarExtension(`${PB}400x400`), "jpg");
+ assert.equal(xAvatarExtension(`${PB}400x400.bmp`), "jpg");
+});
+
+test("handles: X's own shape only", () => {
+ for (const h of ["ObviousRises", "a", "under_score_1", "x".repeat(30)]) assert.equal(isXAvatarHandle(h), true, h);
+ for (const h of ["", "x".repeat(31), "../etc", "a.b", "a-b", "a b", "avatars.json"]) assert.equal(isXAvatarHandle(h), false, h);
+});
+
+test("layout: posts-media/_avatars, and _avatars is never taken for a post id", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "xavatars-layout-"));
+ assert.equal(xAvatarsDir(postsMediaDir(root)), path.join(root, "posts-media", AVATARS_DIRNAME));
+ assert.throws(() => postCaptureDir(postsMediaDir(root), AVATARS_DIRNAME), /not a post id/);
+ assert.doesNotThrow(() => postCaptureDir(postsMediaDir(root), "_avatars2"));
+});
+
+test("store: the picture and its entry, in the exact shape umtool reads", async () => {
+ const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME);
+ const got = await writeXAvatar(dir, {
+ handle: "ObviousRises",
+ bytes: JPG,
+ url: `${PB}400x400.jpg`,
+ contentType: "image/jpeg",
+ postId: "1850000000000000001",
+ capturedAt: "2026-11-02T20:00:00.000Z",
+ });
+ assert.equal(got.handle, "ObviousRises");
+ assert.deepEqual(await readdir(dir).then((n) => n.sort()), ["ObviousRises.jpg", AVATARS_INDEX_FILENAME]);
+ assert.deepEqual(new Uint8Array(await readFile(path.join(dir, "ObviousRises.jpg"))), JPG);
+ assert.deepEqual(JSON.parse(await readFile(path.join(dir, AVATARS_INDEX_FILENAME), "utf8")), {
+ ObviousRises: {
+ file: "ObviousRises.jpg",
+ url: `${PB}400x400.jpg`,
+ capturedAt: "2026-11-02T20:00:00.000Z",
+ postId: "1850000000000000001",
+ },
+ });
+ assert.equal(await xAvatarFile(dir, "obviousrises"), path.join(dir, "ObviousRises.jpg"));
+ assert.equal(await xAvatarFile(dir, "nobody"), null);
+});
+
+test("store: merged with what is there; another case replaces the entry and its file", async () => {
+ const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME);
+ const w = (handle: string, ext = "jpg", postId = "1") =>
+ writeXAvatar(dir, { handle, bytes: JPG, url: `${PB}400x400.${ext}`, postId, capturedAt: "2026-11-02T20:00:00.000Z" });
+ await w("alice");
+ await w("Bob", "png");
+ // Two at once: the read-modify-writes do not drop each other.
+ await Promise.all([w("carol"), w("dave"), w("erin")]);
+ let index = await readXAvatarIndex(dir);
+ assert.deepEqual(Object.keys(index), ["alice", "Bob", "carol", "dave", "erin"]);
+
+ // A re-capture as X prints it now: one entry, the old file gone.
+ await w("BOB", "jpg", "2");
+ index = await readXAvatarIndex(dir);
+ assert.deepEqual(Object.keys(index), ["alice", "BOB", "carol", "dave", "erin"]);
+ assert.equal(index.BOB.postId, "2");
+ assert.equal(lookupXAvatar(index, "@bob")?.handle, "BOB");
+ assert.equal(lookupXAvatar(index, "nobody"), null);
+ const files = (await readdir(dir)).sort();
+ assert.ok(!files.includes("Bob.png"), files.join(","));
+ assert.ok(files.includes("BOB.jpg"));
+ assert.ok(!files.some((f) => f.includes(".tmp-")), "no temp file left");
+});
+
+test("store: a bad handle, a bad post id or no bytes is refused; an unreadable index is never overwritten", async () => {
+ const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME);
+ const ok = { handle: "alice", bytes: JPG, url: `${PB}400x400.jpg`, postId: "1" };
+ await assert.rejects(writeXAvatar(dir, { ...ok, handle: "../x" }), /not an X handle/);
+ await assert.rejects(writeXAvatar(dir, { ...ok, handle: "avatars.json" }), /not an X handle/);
+ await assert.rejects(writeXAvatar(dir, { ...ok, postId: "../1" }), /not a post id/);
+ await assert.rejects(writeXAvatar(dir, { ...ok, bytes: new Uint8Array() }), /empty/);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, AVATARS_INDEX_FILENAME), "{ truncated");
+ await assert.rejects(writeXAvatar(dir, ok), /unparseable; not overwriting/);
+ assert.equal(await readFile(path.join(dir, AVATARS_INDEX_FILENAME), "utf8"), "{ truncated");
+ // A reader just finds nothing.
+ assert.deepEqual(await readXAvatarIndex(dir), {});
+});
+
+test("store: entries not of the shape, or under a key that is no handle, are left out on read", async () => {
+ const dir = path.join(await mkdtemp(path.join(os.tmpdir(), "xavatars-")), AVATARS_DIRNAME);
+ await mkdir(dir, { recursive: true });
+ const good = { file: "a.jpg", url: "u", capturedAt: "t", postId: "1" };
+ await writeFile(
+ path.join(dir, AVATARS_INDEX_FILENAME),
+ JSON.stringify({ a: good, "b/c": good, d: { file: 3 }, e: null }),
+ );
+ assert.deepEqual(await readXAvatarIndex(dir), { a: good });
+});
diff --git a/common/social/xAvatars.ts b/common/social/xAvatars.ts
@@ -0,0 +1,228 @@
+// X authors' profile pictures, kept beside a channel's post captures so a post
+// card can show the author's face instead of an initial letter.
+//
+// THE STORE (umtool reads it as plain JSON; keep the shape):
+//
+// channels/<slug>/posts-media/_avatars/<handle>.<ext> ext: jpg | png | webp | gif
+// channels/<slug>/posts-media/_avatars/avatars.json
+// { "<handle>": { "file": "<handle>.<ext>",
+// "url": "<the _400x400 url it was fetched from>",
+// "capturedAt": "<ISO>",
+// "postId": "<the post page it was read from>" } }
+//
+// Keys keep the handle's case as X prints it; a lookup ignores case, and a
+// re-capture under another case REPLACES the entry (and its file), never adds a
+// second one. Handles are X's: `^[A-Za-z0-9_]{1,30}$`. Every write is atomic
+// (tmp + rename) and a read-modify-write of the index under the process's
+// per-file lock, so a write never drops another handle.
+//
+// `_avatars` sits among the post-id directories of posts-media/ and is never
+// one: postCaptureDir refuses the name (postCapture.ts), and nothing that walks
+// posts-media/ takes its children for post ids (the readers go by archived or
+// cited id).
+//
+// Capturing them is xAvatarCapture.ts (in the post page capture-posts already
+// loads); this module is the store and the URL rule only — no browser.
+//
+// SERVER-ONLY (node:fs).
+
+import { rm, stat } from "node:fs/promises";
+import path from "node:path";
+import {
+ readJsonFile,
+ withJsonFileLock,
+ writeFileAtomic,
+ writeJsonAtomic,
+} from "../lib/jsonFile-server";
+
+export const AVATARS_DIRNAME = "_avatars";
+export const AVATARS_INDEX_FILENAME = "avatars.json";
+
+export type XAvatarEntry = {
+ file: string;
+ url: string;
+ capturedAt: string;
+ postId: string;
+};
+
+export type XAvatarIndex = Record<string, XAvatarEntry>;
+
+const HANDLE_RE = /^[A-Za-z0-9_]{1,30}$/;
+const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+
+export function isXAvatarHandle(handle: string): boolean {
+ return HANDLE_RE.test(handle);
+}
+
+// `<posts-media>/_avatars`.
+export function xAvatarsDir(postsMediaDir: string): string {
+ return path.join(postsMediaDir, AVATARS_DIRNAME);
+}
+
+// The sizes X serves a profile picture at, as the suffix before the extension.
+const SIZE_SUFFIXES = ["normal", "bigger", "mini", "reasonably_small", "x96", "200x200", "400x400"];
+const PROFILE_IMAGE_PATH = new RegExp(
+ `^(.*/profile_images/\\d+/)([^/]+?)(?:_(?:${SIZE_SUFFIXES.join("|")}))?(\\.[A-Za-z0-9]+)?$`,
+);
+
+// Hosts an avatar is fetched from: X's image CDN, and loopback (a test's
+// fixture server — never a third-party host a page could name).
+function avatarHostAllowed(host: string): boolean {
+ return host === "pbs.twimg.com" || host === "127.0.0.1" || host === "localhost" || host === "[::1]";
+}
+
+// A profile picture's URL at 400×400, the largest fixed size X serves (the
+// no-suffix original can be any size). `_normal` (48), `_bigger` (73), `_mini`
+// (24), `_reasonably_small` (128), `_x96`, `_200x200`, `_400x400` and the
+// no-suffix original all map to it; the extension and any query stay. X's
+// default "egg" (abs.twimg.com/sticky/default_profile_images/…) is no
+// picture of anyone and is not stored: null — as is anything that is not a
+// profile_images URL on X's CDN.
+export function upgradeXAvatarUrl(src: string): string | null {
+ let u: URL;
+ try {
+ u = new URL(src);
+ } catch {
+ return null;
+ }
+ if (u.protocol !== "https:" && u.protocol !== "http:") return null;
+ if (/\/default_profile_images\//.test(u.pathname)) return null;
+ if (!avatarHostAllowed(u.hostname === "::1" ? "[::1]" : u.hostname)) return null;
+ const m = PROFILE_IMAGE_PATH.exec(u.pathname);
+ if (!m) return null;
+ u.pathname = `${m[1]}${m[2]}_400x400${m[3] ?? ""}`;
+ return u.toString();
+}
+
+const TYPE_EXT: Record<string, string> = {
+ "image/jpeg": "jpg",
+ "image/jpg": "jpg",
+ "image/pjpeg": "jpg",
+ "image/png": "png",
+ "image/webp": "webp",
+ "image/gif": "gif",
+};
+
+// The stored file's extension: the response's type when it names one of the
+// four, else the URL's, else jpg (what X serves profile pictures as).
+export function xAvatarExtension(url: string, contentType?: string | null): string {
+ const t = (contentType ?? "").split(";")[0].trim().toLowerCase();
+ if (TYPE_EXT[t]) return TYPE_EXT[t];
+ let pathname = url;
+ try {
+ pathname = new URL(url).pathname;
+ } catch {
+ /* a bare path */
+ }
+ const ext = /\.([A-Za-z0-9]+)$/.exec(pathname)?.[1]?.toLowerCase();
+ if (ext === "jpeg" || ext === "jpg") return "jpg";
+ if (ext === "png" || ext === "webp" || ext === "gif") return ext;
+ return "jpg";
+}
+
+function validEntry(handle: string, v: unknown): v is XAvatarEntry {
+ if (!isXAvatarHandle(handle) || !v || typeof v !== "object") return false;
+ const e = v as Partial<XAvatarEntry>;
+ return typeof e.file === "string" && typeof e.url === "string" && typeof e.capturedAt === "string" && typeof e.postId === "string";
+}
+
+type IndexRead = { ok: true; index: XAvatarIndex } | { ok: false; reason: "unreadable" | "unparseable" };
+
+async function readIndexStrict(dir: string): Promise<IndexRead> {
+ const got = await readJsonFile(path.join(dir, AVATARS_INDEX_FILENAME));
+ if (!got.ok) return got.reason === "absent" ? { ok: true, index: {} } : { ok: false, reason: got.reason };
+ const v = got.value;
+ if (!v || typeof v !== "object" || Array.isArray(v)) return { ok: false, reason: "unparseable" };
+ const index: XAvatarIndex = {};
+ for (const [k, e] of Object.entries(v as Record<string, unknown>)) {
+ if (validEntry(k, e)) index[k] = { file: e.file, url: e.url, capturedAt: e.capturedAt, postId: e.postId };
+ }
+ return { ok: true, index };
+}
+
+// The store's index; {} when there is none (or it cannot be read — a lookup
+// then simply finds nothing). Entries that are not the shape are left out.
+export async function readXAvatarIndex(dir: string): Promise<XAvatarIndex> {
+ const got = await readIndexStrict(dir);
+ return got.ok ? got.index : {};
+}
+
+// The entry for `handle`, whatever case it was stored under.
+export function lookupXAvatar(
+ index: XAvatarIndex,
+ handle: string,
+): { handle: string; entry: XAvatarEntry } | null {
+ const want = handle.replace(/^@/, "").toLowerCase();
+ for (const [k, entry] of Object.entries(index)) {
+ if (k.toLowerCase() === want) return { handle: k, entry };
+ }
+ return null;
+}
+
+// The picture's absolute path, when the store has one for `handle` and the
+// file is there.
+export async function xAvatarFile(dir: string, handle: string): Promise<string | null> {
+ const hit = lookupXAvatar(await readXAvatarIndex(dir), handle);
+ if (!hit) return null;
+ const file = path.join(dir, path.basename(hit.entry.file));
+ return (await stat(file).catch(() => null))?.isFile() ? file : null;
+}
+
+export type WriteXAvatarInput = {
+ handle: string;
+ bytes: Uint8Array;
+ // The URL the bytes came from (the _400x400 one).
+ url: string;
+ contentType?: string | null;
+ // The post page the avatar was read from.
+ postId: string;
+ capturedAt?: string;
+};
+
+// Store one avatar: the picture as `<handle>.<ext>`, then its entry merged
+// into avatars.json (an entry for the same handle in another case, and its
+// file, replaced). Refuses a handle that is not X's, and an index it cannot
+// read (it is never overwritten from ignorance).
+export async function writeXAvatar(dir: string, a: WriteXAvatarInput): Promise<{ handle: string; entry: XAvatarEntry }> {
+ const handle = a.handle.replace(/^@/, "");
+ if (!isXAvatarHandle(handle)) throw new Error(`"${a.handle}" is not an X handle`);
+ if (!POST_ID_RE.test(a.postId)) throw new Error(`"${a.postId}" is not a post id`);
+ if (!a.bytes || a.bytes.length === 0) throw new Error(`The avatar for @${handle} is empty`);
+ const file = `${handle}.${xAvatarExtension(a.url, a.contentType)}`;
+ const entry: XAvatarEntry = {
+ file,
+ url: a.url,
+ capturedAt: a.capturedAt ?? new Date().toISOString(),
+ postId: a.postId,
+ };
+ const indexPath = path.join(dir, AVATARS_INDEX_FILENAME);
+ await withJsonFileLock(indexPath, async () => {
+ const got = await readIndexStrict(dir);
+ if (!got.ok) throw new Error(`${indexPath} is ${got.reason}; not overwriting it`);
+ await writeFileAtomic(path.join(dir, file), Buffer.from(a.bytes), { mkdir: true });
+ const index = got.index;
+ for (const [k, old] of Object.entries(index)) {
+ if (k.toLowerCase() !== handle.toLowerCase()) continue;
+ delete index[k];
+ if (old.file !== file) await removeOldFile(dir, path.basename(old.file), file);
+ }
+ index[handle] = entry;
+ const sorted: XAvatarIndex = {};
+ for (const k of Object.keys(index).sort((x, y) => x.toLowerCase().localeCompare(y.toLowerCase()) || x.localeCompare(y))) {
+ sorted[k] = index[k];
+ }
+ await writeJsonAtomic(indexPath, sorted);
+ });
+ return { handle, entry };
+}
+
+// The replaced entry's picture, unless it IS the new one (a case-insensitive
+// filesystem names `Foo.jpg` and `foo.jpg` the same file).
+async function removeOldFile(dir: string, oldName: string, newName: string): Promise<void> {
+ if (!oldName || oldName === AVATARS_INDEX_FILENAME) return;
+ const oldPath = path.join(dir, oldName);
+ const [o, n] = await Promise.all([stat(oldPath).catch(() => null), stat(path.join(dir, newName)).catch(() => null)]);
+ if (!o) return;
+ if (n && o.ino === n.ino && o.dev === n.dev) return;
+ await rm(oldPath, { force: true });
+}