repo.ts

14.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 and the inflated bytes they were verified from. */71export type VerifiedObject = { compressed: Uint8Array; bytes: Uint8Array };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;9798// ponytail: one full listing per call; switch to a delimiter listing if the bucket grows large.99export async function listRepos(bucket: Bucket): Promise<string[]> {100	const keys = await bucket.list("");101	return keys102		.filter((key) => key.endsWith("/head") && key.split("/").length === 2)103		.map((key) => key.slice(0, -"/head".length))104		.filter(isRepoName);105}106107function isRepoName(name: string): boolean {108	return REPO_NAME.test(name) && name !== "." && name !== "..";109}110111// Checked here rather than in route handlers, so no caller can build a key from unchecked input.112function requireRepo(repo: string): void {113	if (!isRepoName(repo)) throw new BucketError(`not a repo name: "${repo}"`);114}115116function requireSaveId(id: string): void {117	if (!SAVE_ID.test(id)) throw new BucketError(`not a save ID: "${id}"`);118}119120/** Applies §9.2's format rule: a missing key is version 1; anything but `koh-remote 1` is refused. */121export async function checkFormat(bucket: Bucket, repo: string): Promise<void> {122	requireRepo(repo);123	const bytes = await bucket.get(`${repo}/format`);124	if (bytes === null) return;125	const format = decoder.decode(bytes).trim();126	if (format !== "koh-remote 1") {127		throw new BucketError(`${repo} uses remote format "${format}"; update Kepr to read it`);128	}129}130131export async function readHead(bucket: Bucket, repo: string): Promise<string | null> {132	requireRepo(repo);133	const bytes = await bucket.get(`${repo}/head`);134	if (bytes === null) return null;135	const head = decoder.decode(bytes).trim();136	if (!SAVE_ID.test(head)) throw new BucketError(`${repo}/head is not a save ID: "${head}"`);137	return head;138}139140export async function readSave(bucket: Bucket, repo: string, id: string): Promise<ArrivingSave> {141	requireRepo(repo);142	requireSaveId(id);143	const bytes = await bucket.get(`${repo}/saves/${id}`);144	if (bytes === null) throw new BucketError(`${repo}/saves/${id} is missing`);145	const record = parseSaveRecord(JSON.parse(decodeRecord(bytes)));146	if (record.id !== id) throw new BucketError(`${repo}/saves/${id} holds save ${record.id}`);147	return {148		...record,149		files: record.files.filter((file) => isSafePath(file.path)),150		quarantined: record.files151			.filter((file) => !isSafePath(file.path))152			.map((file) => escapePath(file.path)),153	};154}155156/**157 * A record's text, read as Koh reads it (\u00A75.5): an unpaired surrogate escape stands for its three158 * bytes, and each byte outside a valid UTF-8 sequence becomes the lone surrogate U+DC00 + byte, so159 * the path holding it fails `isWellFormed` while a genuine U+FFFD stays legal.160 */161function decodeRecord(bytes: Uint8Array): string {162	const text = Buffer.from(bytes)163		.toString("latin1")164		.replace(JSON_ESCAPE, (sequence) => {165			if (sequence.length !== 6 || sequence[1] !== "u") return sequence;166			const unit = Number.parseInt(sequence.slice(2), 16);167			return String.fromCharCode(168				0xe0 | (unit >> 12),169				0x80 | ((unit >> 6) & 0x3f),170				0x80 | (unit & 0x3f),171			);172		});173	return text.replace(UTF8_RUN, (run, valid: string | undefined) =>174		valid === undefined175			? String.fromCharCode(0xdc00 + run.charCodeAt(0))176			: decoder.decode(Buffer.from(valid, "latin1")),177	);178}179180/** Fetches an object, inflates it and checks its Blake3 against its key, as steal does (§9.4). */181export async function readObject(182	bucket: Bucket,183	repo: string,184	hash: string,185): Promise<VerifiedObject> {186	requireRepo(repo);187	if (!HEX64.test(hash)) throw new BucketError(`not an object hash: "${hash}"`);188	const compressed = await bucket.get(`${repo}/objects/${hash}`);189	if (compressed === null) throw new BucketError(`${repo}/objects/${hash} is missing`);190	let bytes: Uint8Array;191	try {192		bytes = new Uint8Array(inflateSync(compressed, { maxOutputLength: MAX_OBJECT }));193	} catch (cause) {194		if (cause instanceof RangeError) {195			throw new OversizedObject(`${repo}/objects/${hash} inflates past 512 MiB`);196		}197		throw cause;198	}199	if (bytesToHex(blake3(bytes)) !== hash) {200		throw new BucketError(`${repo}/objects/${hash} does not match its hash`);201	}202	return { compressed, bytes };203}204205export async function listEventIds(bucket: Bucket, repo: string): Promise<string[]> {206	requireRepo(repo);207	const prefix = `${repo}/events/`;208	// A folder remote's half-written temp files can show up in a listing; only IDs are events.209	return (await bucket.list(prefix))210		.map((key) => key.slice(prefix.length))211		.filter((id) => SAVE_ID.test(id));212}213214export async function readEvent(bucket: Bucket, repo: string, id: string): Promise<EventRecord> {215	requireRepo(repo);216	requireSaveId(id);217	const bytes = await bucket.get(`${repo}/events/${id}`);218	if (bytes === null) throw new BucketError(`${repo}/events/${id} is missing`);219	const record = parseEventRecord(JSON.parse(decodeRecord(bytes)));220	if (record.id !== id) throw new BucketError(`${repo}/events/${id} holds event ${record.id}`);221	return record;222}223224/** §11.1's version rule, minus `.` and `..`, which would name a folder rather than a version. */225export function isVersion(value: string): boolean {226	return VERSION.test(value) && value !== "." && value !== "..";227}228229export function isPlatform(value: string): boolean {230	return (PLATFORMS as readonly string[]).includes(value);231}232233/** The body of `<repo>/releases/latest`, trimmed, or null when the repo has never released. */234export async function readReleasesLatest(bucket: Bucket, repo: string): Promise<string | null> {235	requireRepo(repo);236	const bytes = await bucket.get(`${repo}/releases/latest`);237	if (bytes === null) return null;238	const version = decoder.decode(bytes).trim();239	if (!isVersion(version))240		throw new BucketError(`${repo}/releases/latest is not a version: "${version}"`);241	return version;242}243244/** Every version with a `release.json`: a version without one doesn't exist (§11.2). */245export async function listReleaseVersions(bucket: Bucket, repo: string): Promise<string[]> {246	requireRepo(repo);247	return (await bucket.list(`${repo}/releases/`))248		.map((key) => key.split("/"))249		.filter((parts) => parts.length === 4 && parts[3] === "release.json")250		.map((parts) => parts[2] as string)251		.filter(isVersion);252}253254export async function readRelease(255	bucket: Bucket,256	repo: string,257	version: string,258): Promise<ReleaseRecord> {259	requireRelease(repo, version);260	const key = `${repo}/releases/${version}/release.json`;261	const bytes = await bucket.get(key);262	if (bytes === null) throw new BucketError(`${key} is missing`);263	return checkRelease(repo, version, JSON.parse(decoder.decode(bytes)));264}265266/** A parsed `<repo>/releases/<version>/release.json`, if the sync would accept it (§11.2). */267export function checkRelease(repo: string, version: string, value: unknown): ReleaseRecord {268	requireRelease(repo, version);269	const record = parseReleaseRecord(value);270	if (record.repo !== repo || record.version !== version) {271		throw new BucketError(272			`${repo}/releases/${version}/release.json holds ${record.repo} ${record.version}`,273		);274	}275	return record;276}277278function requireRelease(repo: string, version: string): void {279	requireRepo(repo);280	if (!isVersion(version)) throw new BucketError(`not a release version: "${version}"`);281}282283function parseReleaseRecord(value: unknown): ReleaseRecord {284	const r = value as Record<string, unknown>;285	const valid =286		typeof value === "object" &&287		value !== null &&288		r.format === 1 &&289		typeof r.repo === "string" &&290		typeof r.version === "string" &&291		typeof r.save === "string" &&292		SAVE_ID.test(r.save) &&293		isCount(r.published_at) &&294		typeof r.machine === "string" &&295		typeof r.notes === "string" &&296		Array.isArray(r.files) &&297		r.files.every(isReleaseFile) &&298		// One file per platform per version (§11.2).299		new Set(r.files.map((file) => file.platform)).size === r.files.length;300	if (!valid) throw new BucketError("release record does not match §11.2");301	return value as ReleaseRecord;302}303304function isReleaseFile(value: unknown): value is ReleaseFile {305	const f = value as Record<string, unknown>;306	return (307		typeof value === "object" &&308		value !== null &&309		typeof f.platform === "string" &&310		isPlatform(f.platform) &&311		typeof f.name === "string" &&312		FILE_NAME.test(f.name) &&313		f.name !== "." &&314		f.name !== ".." &&315		isCount(f.size) &&316		typeof f.blake3 === "string" &&317		HEX64.test(f.blake3) &&318		typeof f.sha256 === "string" &&319		HEX64.test(f.sha256)320	);321}322323function parseSaveRecord(value: unknown): SaveRecord {324	const r = value as Record<string, unknown>;325	const valid =326		typeof value === "object" &&327		value !== null &&328		["message", "machine", "agent", "session"].every((key) => typeof r[key] === "string") &&329		typeof r.id === "string" &&330		SAVE_ID.test(r.id) &&331		["parent", "restores", "replayed_from"].every((key) => isOptionalSaveId(r[key])) &&332		isCount(r.created_at) &&333		isCount(r.size_bytes) &&334		typeof r.is_checkpoint === "boolean" &&335		Array.isArray(r.files) &&336		r.files.every(isSaveFile) &&337		new Set(r.files.map((file) => file.path)).size === r.files.length;338	if (!valid) throw new BucketError("save record does not match the Koh 3 schema");339	return value as SaveRecord;340}341342function parseEventRecord(value: unknown): EventRecord {343	const r = value as Record<string, unknown>;344	const valid =345		typeof value === "object" &&346		value !== null &&347		typeof r.id === "string" &&348		SAVE_ID.test(r.id) &&349		isOptionalSaveId(r.save_id) &&350		typeof r.path === "string" &&351		// A flag or clear is about one save and no path; a strip names a path, and one save or352		// (with no ID) all. Sync ignores a strip whose path is illegal, as Koh does (§5.5).353		(r.kind === "strip" ||354			((r.kind === "flag" || r.kind === "clear") && r.save_id !== "" && r.path === "")) &&355		typeof r.reason === "string" &&356		typeof r.machine === "string" &&357		isCount(r.created_at);358	if (!valid) throw new BucketError("event record does not match the Koh 3 schema");359	return value as EventRecord;360}361362function isOptionalSaveId(value: unknown): boolean {363	return value === "" || (typeof value === "string" && SAVE_ID.test(value));364}365366function isCount(value: unknown): boolean {367	return Number.isSafeInteger(value) && (value as number) >= 0;368}369370/** §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. */371export function isSafePath(path: string): boolean {372	return (373		path.isWellFormed() &&374		!path.includes("\\") &&375		!CONTROL_CHAR.test(path) &&376		path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..")377	);378}379380/** A name printable without its controls reaching the page, as Koh's `escape_path` prints it. */381export function escapePath(path: string): string {382	return path383		.replace(/[\\\p{Cc}\udc80-\udcff]/gu, (char) => {384			const code = char.charCodeAt(0);385			if (char === "\\") return "\\\\";386			// A byte `decodeRecord` found outside UTF-8.387			if (code >= 0xdc80) return `\\x${(code - 0xdc00).toString(16)}`;388			const hex = code.toString(16).padStart(2, "0");389			return code >= 0x80 ? `\\u00${hex}` : `\\x${hex}`;390		})391		.toWellFormed();392}393394function isSaveFile(value: unknown): value is SaveFile {395	const f = value as Record<string, unknown>;396	return (397		typeof value === "object" &&398		value !== null &&399		typeof f.path === "string" &&400		typeof f.hash === "string" &&401		HEX64.test(f.hash) &&402		typeof f.executable === "boolean"403	);404}