repo.ts

15.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	files: SaveFile[];22};2324/** A flag, clear or strip event, as Koh 3 writes it to `<repo>/events/<id>` (§9.2, §10). */25export type EventRecord = {26	id: string;27	kind: "flag" | "clear" | "strip";28	save_id: string;29	path: string;30	reason: string;31	created_at: number;32	machine: string;33};3435/** One built file of a release (§11.2). */36export type ReleaseFile = {37	platform: string;38	name: string;39	size: number;40	blake3: string;41	sha256: string;42};4344/** The release record Koh 3 writes to `<repo>/releases/<version>/release.json` (§11.2). */45export type ReleaseRecord = {46	format: 1;47	repo: string;48	version: string;49	save: string;50	published_at: number;51	machine: string;52	notes: string;53	files: ReleaseFile[];54};5556/** §11.1's platform names, Kepr 2's exact list: Peach Android and existing build files depend on them. */57export const PLATFORMS = [58	"linux-x86_64",59	"linux-aarch64",60	"macos-aarch64",61	"macos-x86_64",62	"windows-x86_64",63	"android-arm64",64	"android-x86",65] as const;6667/** A save record as it arrived, less the files §5.5 quarantines, named here escaped. */68export type ArrivingSave = SaveRecord & { quarantined: string[] };6970/** An object's stored zlib bytes, verified against its hash, and its inflated size. */71export type VerifiedObject = { compressed: Uint8Array; size: number };7273export class BucketError extends Error {}7475/** An object that inflates past Koh's own file limit; the paths pointing at it are quarantined. */76export class OversizedObject extends BucketError {}7778const MAX_OBJECT = 512 * 1024 * 1024;7980// Twelve hex characters, or six: Koh 2's early saves keep their shorter IDs through migration81// (§30, 2026-09-23).82export const SAVE_ID = /^(?:[0-9a-f]{6}|[0-9a-f]{12})$/;83const REPO_NAME = /^[A-Za-z0-9._-]+$/;84const CONTROL_CHAR = /\p{Cc}/u;85const HEX64 = /^[0-9a-f]{64}$/;86const VERSION = /^[A-Za-z0-9.-]{1,32}$/;87// A file name that is safe as one key segment and inside a quoted Content-Disposition filename.88const FILE_NAME = /^[^/\\"\p{Cc}]{1,255}$/u;89const decoder = new TextDecoder();90// A run of whole UTF-8 sequences (RFC 3629), or one byte outside them, over a record read one91// character per byte.92const UTF8_RUN =93	/((?:[^\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;94// A surrogate pair escape, a lone surrogate escape, or any other escape (`\\` included), whole.95const JSON_ESCAPE =96	/\\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;9798type Heads = Map<string, string>;99100/**101 * Every repo in the bucket: a top-level folder with a `head`. A folder without one is not a repo102 * yet, as when a first offer or a rename (which copies `head` last) is still under way. Fills103 * `heads` with the head each has, so a sync need not ask the bucket for it again.104 */105export async function listRepos(bucket: Bucket, heads: Heads = new Map()): Promise<string[]> {106	const names = (await bucket.folders()).filter(isRepoName);107	const found = await Promise.all(names.map((name) => bucket.get(`${name}/head`)));108	const repos = names.filter((_, i) => found[i] !== null);109	for (const [i, repo] of names.entries()) {110		const bytes = found[i];111		if (bytes !== null) heads.set(repo, decoder.decode(bytes).trim());112	}113	return repos;114}115116function isRepoName(name: string): boolean {117	return REPO_NAME.test(name) && name !== "." && name !== "..";118}119120// Checked here rather than in route handlers, so no caller can build a key from unchecked input.121function requireRepo(repo: string): void {122	if (!isRepoName(repo)) throw new BucketError(`not a repo name: "${repo}"`);123}124125function requireSaveId(id: string): void {126	if (!SAVE_ID.test(id)) throw new BucketError(`not a save ID: "${id}"`);127}128129/** Applies §9.2's format rule: a missing key is version 1; anything but `koh-remote 1` is refused. */130export async function checkFormat(bucket: Bucket, repo: string): Promise<void> {131	requireRepo(repo);132	const bytes = await bucket.get(`${repo}/format`);133	if (bytes === null) return;134	const format = decoder.decode(bytes).trim();135	if (format !== "koh-remote 1") {136		throw new BucketError(`${repo} uses remote format "${format}"; update Kepr to read it`);137	}138}139140/** A head's text against §9.2's save ID rule, wherever it came from: the bucket or a listing. */141export function checkHead(repo: string, head: string): string {142	requireRepo(repo);143	if (!SAVE_ID.test(head)) throw new BucketError(`${repo}/head is not a save ID: "${head}"`);144	return head;145}146147export async function readHead(bucket: Bucket, repo: string): Promise<string | null> {148	requireRepo(repo);149	const bytes = await bucket.get(`${repo}/head`);150	if (bytes === null) return null;151	return checkHead(repo, decoder.decode(bytes).trim());152}153154export async function readSave(bucket: Bucket, repo: string, id: string): Promise<ArrivingSave> {155	requireRepo(repo);156	requireSaveId(id);157	const bytes = await bucket.get(`${repo}/saves/${id}`);158	if (bytes === null) throw new BucketError(`${repo}/saves/${id} is missing`);159	const record = parseSaveRecord(JSON.parse(decodeRecord(bytes)));160	if (record.id !== id) throw new BucketError(`${repo}/saves/${id} holds save ${record.id}`);161	return {162		...record,163		files: record.files.filter((file) => isSafePath(file.path)),164		quarantined: record.files165			.filter((file) => !isSafePath(file.path))166			.map((file) => escapePath(file.path)),167	};168}169170/**171 * A record's text, read as Koh reads it (\u00A75.5): an unpaired surrogate escape stands for its three172 * bytes, and each byte outside a valid UTF-8 sequence becomes the lone surrogate U+DC00 + byte, so173 * the path holding it fails `isWellFormed` while a genuine U+FFFD stays legal.174 */175function decodeRecord(bytes: Uint8Array): string {176	const text = Buffer.from(bytes)177		.toString("latin1")178		.replace(JSON_ESCAPE, (sequence) => {179			if (sequence.length !== 6 || sequence[1] !== "u") return sequence;180			const unit = Number.parseInt(sequence.slice(2), 16);181			return String.fromCharCode(182				0xe0 | (unit >> 12),183				0x80 | ((unit >> 6) & 0x3f),184				0x80 | (unit & 0x3f),185			);186		});187	return text.replace(UTF8_RUN, (run, valid: string | undefined) =>188		valid === undefined189			? String.fromCharCode(0xdc00 + run.charCodeAt(0))190			: decoder.decode(Buffer.from(valid, "latin1")),191	);192}193194function objectKey(repo: string, hash: string): string {195	requireRepo(repo);196	if (!HEX64.test(hash)) throw new BucketError(`not an object hash: "${hash}"`);197	return `${repo}/objects/${hash}`;198}199200/** An object's stored, compressed size, asked without reading it. */201export function objectSize(bucket: Bucket, repo: string, hash: string): Promise<number> {202	return bucket.size(objectKey(repo, hash));203}204205/**206 * Fetches an object, inflates it and checks its Blake3 against its key, as steal does (§9.4). The207 * inflated bytes never leave this call, so reads in parallel hold one inflated object at a time.208 */209export async function readObject(210	bucket: Bucket,211	repo: string,212	hash: string,213): Promise<VerifiedObject> {214	const compressed = await bucket.get(objectKey(repo, hash));215	if (compressed === null) throw new BucketError(`${repo}/objects/${hash} is missing`);216	let bytes: Uint8Array;217	try {218		bytes = new Uint8Array(inflateSync(compressed, { maxOutputLength: MAX_OBJECT }));219	} catch (cause) {220		if (cause instanceof RangeError) {221			throw new OversizedObject(`${repo}/objects/${hash} inflates past 512 MiB`);222		}223		throw cause;224	}225	if (bytesToHex(blake3(bytes)) !== hash) {226		throw new BucketError(`${repo}/objects/${hash} does not match its hash`);227	}228	return { compressed, size: bytes.length };229}230231export async function listEventIds(bucket: Bucket, repo: string): Promise<string[]> {232	requireRepo(repo);233	const prefix = `${repo}/events/`;234	// A folder remote's half-written temp files can show up in a listing; only IDs are events.235	return (await bucket.list(prefix))236		.map((key) => key.slice(prefix.length))237		.filter((id) => SAVE_ID.test(id));238}239240export async function readEvent(bucket: Bucket, repo: string, id: string): Promise<EventRecord> {241	requireRepo(repo);242	requireSaveId(id);243	const bytes = await bucket.get(`${repo}/events/${id}`);244	if (bytes === null) throw new BucketError(`${repo}/events/${id} is missing`);245	const record = parseEventRecord(JSON.parse(decodeRecord(bytes)));246	if (record.id !== id) throw new BucketError(`${repo}/events/${id} holds event ${record.id}`);247	return record;248}249250/** §11.1's version rule, minus `.` and `..`, which would name a folder rather than a version. */251export function isVersion(value: string): boolean {252	return VERSION.test(value) && value !== "." && value !== "..";253}254255export function isPlatform(value: string): boolean {256	return (PLATFORMS as readonly string[]).includes(value);257}258259/** The body of `<repo>/releases/latest`, trimmed, or null when the repo has never released. */260export async function readReleasesLatest(bucket: Bucket, repo: string): Promise<string | null> {261	requireRepo(repo);262	const bytes = await bucket.get(`${repo}/releases/latest`);263	if (bytes === null) return null;264	const version = decoder.decode(bytes).trim();265	if (!isVersion(version))266		throw new BucketError(`${repo}/releases/latest is not a version: "${version}"`);267	return version;268}269270/** Every version with a `release.json`: a version without one doesn't exist (§11.2). */271export async function listReleaseVersions(bucket: Bucket, repo: string): Promise<string[]> {272	requireRepo(repo);273	return (await bucket.list(`${repo}/releases/`))274		.map((key) => key.split("/"))275		.filter((parts) => parts.length === 4 && parts[3] === "release.json")276		.map((parts) => parts[2] as string)277		.filter(isVersion);278}279280export async function readRelease(281	bucket: Bucket,282	repo: string,283	version: string,284): Promise<ReleaseRecord> {285	requireRelease(repo, version);286	const key = `${repo}/releases/${version}/release.json`;287	const bytes = await bucket.get(key);288	if (bytes === null) throw new BucketError(`${key} is missing`);289	return checkRelease(repo, version, JSON.parse(decoder.decode(bytes)));290}291292/** A parsed `<repo>/releases/<version>/release.json`, if the sync would accept it (§11.2). */293export function checkRelease(repo: string, version: string, value: unknown): ReleaseRecord {294	requireRelease(repo, version);295	const record = parseReleaseRecord(value);296	if (record.repo !== repo || record.version !== version) {297		throw new BucketError(298			`${repo}/releases/${version}/release.json holds ${record.repo} ${record.version}`,299		);300	}301	return record;302}303304function requireRelease(repo: string, version: string): void {305	requireRepo(repo);306	if (!isVersion(version)) throw new BucketError(`not a release version: "${version}"`);307}308309function parseReleaseRecord(value: unknown): ReleaseRecord {310	const r = value as Record<string, unknown>;311	const valid =312		typeof value === "object" &&313		value !== null &&314		r.format === 1 &&315		typeof r.repo === "string" &&316		typeof r.version === "string" &&317		typeof r.save === "string" &&318		SAVE_ID.test(r.save) &&319		isCount(r.published_at) &&320		typeof r.machine === "string" &&321		typeof r.notes === "string" &&322		Array.isArray(r.files) &&323		r.files.every(isReleaseFile) &&324		// One file per platform per version (§11.2).325		new Set(r.files.map((file) => file.platform)).size === r.files.length;326	if (!valid) throw new BucketError("release record does not match §11.2");327	return value as ReleaseRecord;328}329330function isReleaseFile(value: unknown): value is ReleaseFile {331	const f = value as Record<string, unknown>;332	return (333		typeof value === "object" &&334		value !== null &&335		typeof f.platform === "string" &&336		isPlatform(f.platform) &&337		typeof f.name === "string" &&338		FILE_NAME.test(f.name) &&339		f.name !== "." &&340		f.name !== ".." &&341		isCount(f.size) &&342		typeof f.blake3 === "string" &&343		HEX64.test(f.blake3) &&344		typeof f.sha256 === "string" &&345		HEX64.test(f.sha256)346	);347}348349function parseSaveRecord(value: unknown): SaveRecord {350	const r = value as Record<string, unknown>;351	const valid =352		typeof value === "object" &&353		value !== null &&354		["message", "machine", "agent", "session"].every((key) => typeof r[key] === "string") &&355		typeof r.id === "string" &&356		SAVE_ID.test(r.id) &&357		["parent", "restores", "replayed_from"].every((key) => isOptionalSaveId(r[key])) &&358		isCount(r.created_at) &&359		isCount(r.size_bytes) &&360		typeof r.is_checkpoint === "boolean" &&361		Array.isArray(r.files) &&362		r.files.every(isSaveFile) &&363		new Set(r.files.map((file) => file.path)).size === r.files.length;364	if (!valid) throw new BucketError("save record does not match the Koh 3 schema");365	return value as SaveRecord;366}367368function parseEventRecord(value: unknown): EventRecord {369	const r = value as Record<string, unknown>;370	const valid =371		typeof value === "object" &&372		value !== null &&373		typeof r.id === "string" &&374		SAVE_ID.test(r.id) &&375		isOptionalSaveId(r.save_id) &&376		typeof r.path === "string" &&377		// A flag or clear is about one save and no path; a strip names a path, and one save or378		// (with no ID) all. Sync ignores a strip whose path is illegal, as Koh does (§5.5).379		(r.kind === "strip" ||380			((r.kind === "flag" || r.kind === "clear") && r.save_id !== "" && r.path === "")) &&381		typeof r.reason === "string" &&382		typeof r.machine === "string" &&383		isCount(r.created_at);384	if (!valid) throw new BucketError("event record does not match the Koh 3 schema");385	return value as EventRecord;386}387388function isOptionalSaveId(value: unknown): boolean {389	return value === "" || (typeof value === "string" && SAVE_ID.test(value));390}391392function isCount(value: unknown): boolean {393	return Number.isSafeInteger(value) && (value as number) >= 0;394}395396/** §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. */397export function isSafePath(path: string): boolean {398	return (399		path.isWellFormed() &&400		!path.includes("\\") &&401		!CONTROL_CHAR.test(path) &&402		path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..")403	);404}405406/** A name printable without its controls reaching the page, as Koh's `escape_path` prints it. */407export function escapePath(path: string): string {408	return path409		.replace(/[\\\p{Cc}\udc80-\udcff]/gu, (char) => {410			const code = char.charCodeAt(0);411			if (char === "\\") return "\\\\";412			// A byte `decodeRecord` found outside UTF-8.413			if (code >= 0xdc80) return `\\x${(code - 0xdc00).toString(16)}`;414			const hex = code.toString(16).padStart(2, "0");415			return code >= 0x80 ? `\\u00${hex}` : `\\x${hex}`;416		})417		.toWellFormed();418}419420function isSaveFile(value: unknown): value is SaveFile {421	const f = value as Record<string, unknown>;422	return (423		typeof value === "object" &&424		value !== null &&425		typeof f.path === "string" &&426		typeof f.hash === "string" &&427		HEX64.test(f.hash) &&428		typeof f.executable === "boolean"429	);430}