import type { Database } from "bun:sqlite"; import { blake3 } from "@noble/hashes/blake3.js"; import { bytesToHex } from "@noble/hashes/utils.js"; import { isSafePath } from "../bucket/repo.ts"; import type { FileEntry } from "./queries.ts"; /** One immediate entry of a folder manifest (§5.1). Field order is the encoding, so it is the schema. */ export type ManifestEntry = { name: string; kind: "file" | "folder"; hash: string; size: number; executable: boolean; manifest: string; }; const HEX64 = /^[0-9a-f]{64}$/; const encoder = new TextEncoder(); export function hashBody(body: string): string { return bytesToHex(blake3(encoder.encode(body))); } /** A manifest body, refusing a shape no reader could walk. Names are not checked, as in Koh. */ export function parseManifest(body: string): ManifestEntry[] { const value = JSON.parse(body) as { entries?: unknown }; if (typeof value !== "object" || value === null || !Array.isArray(value.entries)) { throw new Error("it has no entries"); } const entries: ManifestEntry[] = []; for (const raw of value.entries) { const e = raw as Record; if (typeof raw !== "object" || raw === null || typeof e.name !== "string" || e.name === "") { throw new Error("it has an entry with no name"); } if (e.kind === "file") { if (typeof e.hash !== "string" || !HEX64.test(e.hash)) { throw new Error(`its entry ${e.name} has an invalid object hash`); } if (!Number.isSafeInteger(e.size) || (e.size as number) < 0) { throw new Error(`its entry ${e.name} has an invalid size`); } if (typeof e.executable !== "boolean") { throw new Error(`its entry ${e.name} has no executable bit`); } entries.push({ name: e.name, kind: "file", hash: e.hash, size: e.size as number, executable: e.executable, manifest: "", }); } else if (e.kind === "folder") { if (typeof e.manifest !== "string" || !HEX64.test(e.manifest)) { throw new Error(`its entry ${e.name} has an invalid manifest hash`); } entries.push({ name: e.name, kind: "folder", hash: "", size: 0, executable: false, manifest: e.manifest, }); } else { throw new Error(`its entry ${e.name} has an unknown kind`); } } return entries; } /** Every file under a manifest, path-joined and sorted as SQLite's BINARY collation sorts paths. */ export function flattenTree(read: (hash: string) => string, root: string): FileEntry[] { const files: FileEntry[] = []; walk(read, root, "", files, []); return files.sort((a, b) => byPath(a.path, b.path)); } function walk( read: (hash: string) => string, hash: string, prefix: string, out: FileEntry[], ancestors: string[], ): void { if (ancestors.includes(hash)) throw new Error(`manifest ${hash} refers to itself`); const deeper = [...ancestors, hash]; for (const entry of parseManifest(read(hash))) { if (entry.kind === "file") { out.push({ path: prefix + entry.name, hash: entry.hash, executable: entry.executable, size: entry.size, }); } else { walk(read, entry.manifest, `${prefix}${entry.name}/`, out, deeper); } } } // Comparing code points is comparing UTF-8 bytes, which is what `ORDER BY path` did. function byPath(a: string, b: string): number { for (let i = 0, j = 0; i < a.length && j < b.length; ) { const x = a.codePointAt(i) as number; const y = b.codePointAt(j) as number; if (x !== y) return x - y; i += x > 0xffff ? 2 : 1; j += y > 0xffff ? 2 : 1; } return a.length - b.length; } /** A stored manifest body, or null when the mirror lacks it. */ export function manifestBody(db: Database, hash: string): string | null { return ( db.query<{ body: string }, [string]>("SELECT body FROM manifests WHERE hash = ?").get(hash) ?.body ?? null ); } // A manifest never changes once stored, so a flattened tree can be kept for the whole process. // A damaged tree is refused rather than cached: the mirror is disposable, and the next sync's // landing is what rewrites it. const flat = new Map(); let flatEntries = 0; const MAX_FLAT = 50_000; /** * The files under a stored manifest, cached by hash. An illegal path (§5.5) is never handed out: * the body is kept verbatim, but no page, tarball or object listing may see the name. */ export function flattenManifest(db: Database, root: string): FileEntry[] { const cached = flat.get(root); if (cached) return cached; const files = flattenTree((hash) => { const body = manifestBody(db, hash); if (body === null) throw new Error(`manifest ${hash} is missing from the mirror`); return body; }, root).filter((file) => isSafePath(file.path)); if (flatEntries + files.length > MAX_FLAT) { flat.clear(); flatEntries = 0; } flat.set(root, files); flatEntries += files.length; return files; } type Trie = { files: Map; folders: Map; }; /** * Builds the folder manifests of a version-1 file list once, writing §5.1's canonical body, and * returns the root hash with every body. The mirror's hashes need not equal Koh's: the list only * has to land once, and identical lists must share a row. */ export function manifestTree( files: { path: string; hash: string; executable: boolean }[], sizeOf: (hash: string) => number | null, ): { root: string; bodies: Map } { const top: Trie = { files: new Map(), folders: new Map() }; for (const file of files) { const size = sizeOf(file.hash); // The object is stored before the save; one that is not cannot be opened, described or // tarred, so it is left out as an oversized object is. if (size === null) continue; const parts = file.path.split("/"); const name = parts.pop() as string; let node = top; for (const part of parts) { let child = node.folders.get(part); if (!child) { child = { files: new Map(), folders: new Map() }; node.folders.set(part, child); } node = child; } node.files.set(name, { hash: file.hash, executable: file.executable }); } const bodies = new Map(); const write = (node: Trie): string => { const entries: ManifestEntry[] = []; for (const [name, child] of node.folders) { entries.push({ name, kind: "folder", hash: "", size: 0, executable: false, manifest: write(child), }); } if (node.files.size > 0) { for (const [name, file] of node.files) { entries.push({ name, kind: "file", hash: file.hash, size: sizeOf(file.hash) as number, executable: file.executable, manifest: "", }); } } // Entries are sorted by name, then kind: a file before a folder of the same name (§5.1). entries.sort((a, b) => { if (a.name !== b.name) return a.name < b.name ? -1 : 1; return (a.kind === "file" ? 0 : 1) - (b.kind === "file" ? 0 : 1); }); const body = JSON.stringify({ entries }); const hash = hashBody(body); bodies.set(hash, body); return hash; }; return { root: write(top), bodies }; }