repo.ts

16.1 KB · raw

1import { inflateSync } from "node:zlib";2import { blake3 } from "@noble/hashes/blake3.js";3import { bytesToHex } from "@noble/hashes/utils.js";4import type { Bucket } from "./reader.ts";56export type SaveFile = { path: string; hash: string; executable: boolean };78/** The save record Koh 3 writes to `<repo>/saves/<id>` (§9.2). */9export type SaveRecord = {10	id: string;11	parent: string;12	message: string;13	created_at: number;14	machine: string;15	is_checkpoint: boolean;16	size_bytes: number;17	agent: string;18	session: string;19	restores: string;20	replayed_from: string;21	/** Root manifest of a format-2 record; absent on a version-1 record, whose `files` it replaces. */22	manifest?: string;23	files: SaveFile[];24};2526/** A flag, clear or strip event, as Koh 3 writes it to `<repo>/events/<id>` (§9.2, §10). */27export type EventRecord = {28	id: string;29	kind: "flag" | "clear" | "strip";30	save_id: string;31	path: string;32	reason: string;33	created_at: number;34	machine: string;35};3637/** One built file of a release (§11.2). */38export type ReleaseFile = {39	platform: string;40	name: string;41	size: number;42	blake3: string;43	sha256: string;44};4546/** The release record Koh 3 writes to `<repo>/releases/<version>/release.json` (§11.2). */47export type ReleaseRecord = {48	format: 1;49	repo: string;50	version: string;51	save: string;52	published_at: number;53	machine: string;54	notes: string;55	files: ReleaseFile[];56};5758/** §11.1's platform names, Kepr 2's exact list: Peach Android and existing build files depend on them. */59export const PLATFORMS = [60	"linux-x86_64",61	"linux-aarch64",62	"macos-aarch64",63	"macos-x86_64",64	"windows-x86_64",65	"android-arm64",66	"android-x86",67] as const;6869/** A save record as it arrived, less the files §5.5 quarantines, named here escaped. */70export type ArrivingSave = SaveRecord & { quarantined: string[] };7172/** An object's stored zlib bytes, verified against its hash, and its inflated size. */73export type VerifiedObject = { compressed: Uint8Array; size: number };7475export class BucketError extends Error {}7677/** An object that inflates past Koh's own file limit; the paths pointing at it are quarantined. */78export class OversizedObject extends BucketError {}7980const MAX_OBJECT = 512 * 1024 * 1024;8182// Twelve hex characters, or six: Koh 2's early saves keep their shorter IDs through migration83// (§30, 2026-09-23).84export const SAVE_ID = /^(?:[0-9a-f]{6}|[0-9a-f]{12})$/;85const REPO_NAME = /^[A-Za-z0-9._-]+$/;86const CONTROL_CHAR = /\p{Cc}/u;87const HEX64 = /^[0-9a-f]{64}$/;88const VERSION = /^[A-Za-z0-9.-]{1,32}$/;89// A file name that is safe as one key segment and inside a quoted Content-Disposition filename.90const FILE_NAME = /^[^/\\"\p{Cc}]{1,255}$/u;91const decoder = new TextDecoder();92// A run of whole UTF-8 sequences (RFC 3629), or one byte outside them, over a record read one93// character per byte.94const UTF8_RUN =95	/((?:[^\x80-\xff]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xec\xee\xef][\x80-\xbf]{2}|\xed[\x80-\x9f][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf]{2}|[\xf1-\xf3][\x80-\xbf]{3}|\xf4[\x80-\x8f][\x80-\xbf]{2})+)|[\s\S]/g;96// A surrogate pair escape, a lone surrogate escape, or any other escape (`\\` included), whole.97const JSON_ESCAPE =98	/\\u[dD][89abAB][0-9a-fA-F]{2}\\u[dD][c-fC-F][0-9a-fA-F]{2}|\\u[dD][89a-fA-F][0-9a-fA-F]{2}|\\[\s\S]/g;99100type Heads = Map<string, string>;101102/**103 * Every repo in the bucket: a top-level folder with a `head`. A folder without one is not a repo104 * yet, as when a first offer or a rename (which copies `head` last) is still under way. Fills105 * `heads` with the head each has, so a sync need not ask the bucket for it again.106 */107export async function listRepos(bucket: Bucket, heads: Heads = new Map()): Promise<string[]> {108	const names = (await bucket.folders()).filter(isRepoName);109	const found = await Promise.all(names.map((name) => bucket.get(`${name}/head`)));110	const repos = names.filter((_, i) => found[i] !== null);111	for (const [i, repo] of names.entries()) {112		const bytes = found[i];113		if (bytes !== null) heads.set(repo, decoder.decode(bytes).trim());114	}115	return repos;116}117118function isRepoName(name: string): boolean {119	return REPO_NAME.test(name) && name !== "." && name !== "..";120}121122// Checked here rather than in route handlers, so no caller can build a key from unchecked input.123function requireRepo(repo: string): void {124	if (!isRepoName(repo)) throw new BucketError(`not a repo name: "${repo}"`);125}126127function requireSaveId(id: string): void {128	if (!SAVE_ID.test(id)) throw new BucketError(`not a save ID: "${id}"`);129}130131/** Applies §9.2's format rule: a missing key is version 1; a version Kepr doesn't read is refused. */132export async function checkFormat(bucket: Bucket, repo: string): Promise<void> {133	requireRepo(repo);134	const bytes = await bucket.get(`${repo}/format`);135	if (bytes === null) return;136	const format = decoder.decode(bytes).trim();137	if (format !== "koh-remote 1" && format !== "koh-remote 2") {138		throw new BucketError(`${repo} uses remote format "${format}"; update Kepr to read it`);139	}140}141142/** A head's text against §9.2's save ID rule, wherever it came from: the bucket or a listing. */143export function checkHead(repo: string, head: string): string {144	requireRepo(repo);145	if (!SAVE_ID.test(head)) throw new BucketError(`${repo}/head is not a save ID: "${head}"`);146	return head;147}148149export async function readHead(bucket: Bucket, repo: string): Promise<string | null> {150	requireRepo(repo);151	const bytes = await bucket.get(`${repo}/head`);152	if (bytes === null) return null;153	return checkHead(repo, decoder.decode(bytes).trim());154}155156export async function readSave(bucket: Bucket, repo: string, id: string): Promise<ArrivingSave> {157	requireRepo(repo);158	requireSaveId(id);159	const bytes = await bucket.get(`${repo}/saves/${id}`);160	if (bytes === null) throw new BucketError(`${repo}/saves/${id} is missing`);161	const record = parseSaveRecord(JSON.parse(decodeRecord(bytes)));162	if (record.id !== id) throw new BucketError(`${repo}/saves/${id} holds save ${record.id}`);163	return {164		...record,165		files: record.files.filter((file) => isSafePath(file.path)),166		quarantined: record.files167			.filter((file) => !isSafePath(file.path))168			.map((file) => escapePath(file.path)),169	};170}171172/** One folder body from a format-2 repo, checked against its key as steal checks it (§9.4). */173export async function readManifest(bucket: Bucket, repo: string, hash: string): Promise<string> {174	requireRepo(repo);175	if (!HEX64.test(hash)) throw new BucketError(`not a manifest hash: "${hash}"`);176	const bytes = await bucket.get(`${repo}/manifests/${hash}`);177	if (bytes === null) throw new BucketError(`${repo}/manifests/${hash} is missing`);178	if (bytesToHex(blake3(bytes)) !== hash) {179		throw new BucketError(`${repo}/manifests/${hash} does not match its hash`);180	}181	return decoder.decode(bytes);182}183184/**185 * A record's text, read as Koh reads it (\u00A75.5): an unpaired surrogate escape stands for its three186 * bytes, and each byte outside a valid UTF-8 sequence becomes the lone surrogate U+DC00 + byte, so187 * the path holding it fails `isWellFormed` while a genuine U+FFFD stays legal.188 */189function decodeRecord(bytes: Uint8Array): string {190	const text = Buffer.from(bytes)191		.toString("latin1")192		.replace(JSON_ESCAPE, (sequence) => {193			if (sequence.length !== 6 || sequence[1] !== "u") return sequence;194			const unit = Number.parseInt(sequence.slice(2), 16);195			return String.fromCharCode(196				0xe0 | (unit >> 12),197				0x80 | ((unit >> 6) & 0x3f),198				0x80 | (unit & 0x3f),199			);200		});201	return text.replace(UTF8_RUN, (run, valid: string | undefined) =>202		valid === undefined203			? String.fromCharCode(0xdc00 + run.charCodeAt(0))204			: decoder.decode(Buffer.from(valid, "latin1")),205	);206}207208function objectKey(repo: string, hash: string): string {209	requireRepo(repo);210	if (!HEX64.test(hash)) throw new BucketError(`not an object hash: "${hash}"`);211	return `${repo}/objects/${hash}`;212}213214/** An object's stored, compressed size, asked without reading it. */215export function objectSize(bucket: Bucket, repo: string, hash: string): Promise<number> {216	return bucket.size(objectKey(repo, hash));217}218219/**220 * Fetches an object, inflates it and checks its Blake3 against its key, as steal does (§9.4). The221 * inflated bytes never leave this call, so reads in parallel hold one inflated object at a time.222 */223export async function readObject(224	bucket: Bucket,225	repo: string,226	hash: string,227): Promise<VerifiedObject> {228	const compressed = await bucket.get(objectKey(repo, hash));229	if (compressed === null) throw new BucketError(`${repo}/objects/${hash} is missing`);230	let bytes: Uint8Array;231	try {232		bytes = new Uint8Array(inflateSync(compressed, { maxOutputLength: MAX_OBJECT }));233	} catch (cause) {234		if (cause instanceof RangeError) {235			throw new OversizedObject(`${repo}/objects/${hash} inflates past 512 MiB`);236		}237		throw cause;238	}239	if (bytesToHex(blake3(bytes)) !== hash) {240		throw new BucketError(`${repo}/objects/${hash} does not match its hash`);241	}242	return { compressed, size: bytes.length };243}244245export async function listEventIds(bucket: Bucket, repo: string): Promise<string[]> {246	requireRepo(repo);247	const prefix = `${repo}/events/`;248	// A folder remote's half-written temp files can show up in a listing; only IDs are events.249	return (await bucket.list(prefix))250		.map((key) => key.slice(prefix.length))251		.filter((id) => SAVE_ID.test(id));252}253254export async function readEvent(bucket: Bucket, repo: string, id: string): Promise<EventRecord> {255	requireRepo(repo);256	requireSaveId(id);257	const bytes = await bucket.get(`${repo}/events/${id}`);258	if (bytes === null) throw new BucketError(`${repo}/events/${id} is missing`);259	const record = parseEventRecord(JSON.parse(decodeRecord(bytes)));260	if (record.id !== id) throw new BucketError(`${repo}/events/${id} holds event ${record.id}`);261	return record;262}263264/** §11.1's version rule, minus `.` and `..`, which would name a folder rather than a version. */265export function isVersion(value: string): boolean {266	return VERSION.test(value) && value !== "." && value !== "..";267}268269export function isPlatform(value: string): boolean {270	return (PLATFORMS as readonly string[]).includes(value);271}272273/** The body of `<repo>/releases/latest`, trimmed, or null when the repo has never released. */274export async function readReleasesLatest(bucket: Bucket, repo: string): Promise<string | null> {275	requireRepo(repo);276	const bytes = await bucket.get(`${repo}/releases/latest`);277	if (bytes === null) return null;278	const version = decoder.decode(bytes).trim();279	if (!isVersion(version))280		throw new BucketError(`${repo}/releases/latest is not a version: "${version}"`);281	return version;282}283284/** Every version with a `release.json`: a version without one doesn't exist (§11.2). */285export async function listReleaseVersions(bucket: Bucket, repo: string): Promise<string[]> {286	requireRepo(repo);287	return (await bucket.list(`${repo}/releases/`))288		.map((key) => key.split("/"))289		.filter((parts) => parts.length === 4 && parts[3] === "release.json")290		.map((parts) => parts[2] as string)291		.filter(isVersion);292}293294export async function readRelease(295	bucket: Bucket,296	repo: string,297	version: string,298): Promise<ReleaseRecord> {299	requireRelease(repo, version);300	const key = `${repo}/releases/${version}/release.json`;301	const bytes = await bucket.get(key);302	if (bytes === null) throw new BucketError(`${key} is missing`);303	return checkRelease(repo, version, JSON.parse(decoder.decode(bytes)));304}305306/** A parsed `<repo>/releases/<version>/release.json`, if the sync would accept it (§11.2). */307export function checkRelease(repo: string, version: string, value: unknown): ReleaseRecord {308	requireRelease(repo, version);309	const record = parseReleaseRecord(value);310	if (record.repo !== repo || record.version !== version) {311		throw new BucketError(312			`${repo}/releases/${version}/release.json holds ${record.repo} ${record.version}`,313		);314	}315	return record;316}317318function requireRelease(repo: string, version: string): void {319	requireRepo(repo);320	if (!isVersion(version)) throw new BucketError(`not a release version: "${version}"`);321}322323function parseReleaseRecord(value: unknown): ReleaseRecord {324	const r = value as Record<string, unknown>;325	const valid =326		typeof value === "object" &&327		value !== null &&328		r.format === 1 &&329		typeof r.repo === "string" &&330		typeof r.version === "string" &&331		typeof r.save === "string" &&332		SAVE_ID.test(r.save) &&333		isCount(r.published_at) &&334		typeof r.machine === "string" &&335		typeof r.notes === "string" &&336		Array.isArray(r.files) &&337		r.files.every(isReleaseFile) &&338		// One file per platform per version (§11.2).339		new Set(r.files.map((file) => file.platform)).size === r.files.length;340	if (!valid) throw new BucketError("release record does not match §11.2");341	return value as ReleaseRecord;342}343344function isReleaseFile(value: unknown): value is ReleaseFile {345	const f = value as Record<string, unknown>;346	return (347		typeof value === "object" &&348		value !== null &&349		typeof f.platform === "string" &&350		isPlatform(f.platform) &&351		typeof f.name === "string" &&352		FILE_NAME.test(f.name) &&353		f.name !== "." &&354		f.name !== ".." &&355		isCount(f.size) &&356		typeof f.blake3 === "string" &&357		HEX64.test(f.blake3) &&358		typeof f.sha256 === "string" &&359		HEX64.test(f.sha256)360	);361}362363function parseSaveRecord(value: unknown): SaveRecord {364	const r = value as Record<string, unknown>;365	const valid =366		typeof value === "object" &&367		value !== null &&368		["message", "machine", "agent", "session"].every((key) => typeof r[key] === "string") &&369		typeof r.id === "string" &&370		SAVE_ID.test(r.id) &&371		["parent", "restores", "replayed_from"].every((key) => isOptionalSaveId(r[key])) &&372		isCount(r.created_at) &&373		isCount(r.size_bytes) &&374		typeof r.is_checkpoint === "boolean" &&375		Array.isArray(r.files) &&376		r.files.every(isSaveFile) &&377		new Set(r.files.map((file) => file.path)).size === r.files.length &&378		// A format-2 record names its root manifest in place of a file list; one that names an379		// invalid hash is refused, as Koh's steal refuses it (§9.2).380		(r.manifest === undefined || (typeof r.manifest === "string" && HEX64.test(r.manifest)));381	if (!valid) throw new BucketError("save record does not match the Koh 3 schema");382	return value as SaveRecord;383}384385function parseEventRecord(value: unknown): EventRecord {386	const r = value as Record<string, unknown>;387	const valid =388		typeof value === "object" &&389		value !== null &&390		typeof r.id === "string" &&391		SAVE_ID.test(r.id) &&392		isOptionalSaveId(r.save_id) &&393		typeof r.path === "string" &&394		// A flag or clear is about one save and no path; a strip names a path, and one save or395		// (with no ID) all. Sync ignores a strip whose path is illegal, as Koh does (§5.5).396		(r.kind === "strip" ||397			((r.kind === "flag" || r.kind === "clear") && r.save_id !== "" && r.path === "")) &&398		typeof r.reason === "string" &&399		typeof r.machine === "string" &&400		isCount(r.created_at);401	if (!valid) throw new BucketError("event record does not match the Koh 3 schema");402	return value as EventRecord;403}404405function isOptionalSaveId(value: unknown): boolean {406	return value === "" || (typeof value === "string" && SAVE_ID.test(value));407}408409function isCount(value: unknown): boolean {410	return Number.isSafeInteger(value) && (value as number) >= 0;411}412413/** §5.5's legal path, clause for clause with Koh's `legal_path`: no empty, `.` or `..` segments, no backslash or control character, well-formed UTF-8. */414export function isSafePath(path: string): boolean {415	return (416		path.isWellFormed() &&417		!path.includes("\\") &&418		!CONTROL_CHAR.test(path) &&419		path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..")420	);421}422423/** A name printable without its controls reaching the page, as Koh's `escape_path` prints it. */424export function escapePath(path: string): string {425	return path426		.replace(/[\\\p{Cc}\udc80-\udcff]/gu, (char) => {427			const code = char.charCodeAt(0);428			if (char === "\\") return "\\\\";429			// A byte `decodeRecord` found outside UTF-8.430			if (code >= 0xdc80) return `\\x${(code - 0xdc00).toString(16)}`;431			const hex = code.toString(16).padStart(2, "0");432			return code >= 0x80 ? `\\u00${hex}` : `\\x${hex}`;433		})434		.toWellFormed();435}436437function isSaveFile(value: unknown): value is SaveFile {438	const f = value as Record<string, unknown>;439	return (440		typeof value === "object" &&441		value !== null &&442		typeof f.path === "string" &&443		typeof f.hash === "string" &&444		HEX64.test(f.hash) &&445		typeof f.executable === "boolean"446	);447}