// 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//posts-media/_avatars/. ext: jpg | png | webp | gif // channels//posts-media/_avatars/avatars.json // { "": { "file": ".", // "url": "", // "capturedAt": "", // "postId": "" } } // // 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; 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); } // `/_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 = { "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; 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 { 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)) { 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 { 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 { 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 `.`, 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 { 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 }); }