repo.ts

14.0 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;7980const SAVE_ID = /^[0-9a-f]{12}$/;81const REPO_NAME = /^[A-Za-z0-9._-]+$/;82const CONTROL_CHAR = /\p{Cc}/u;83const HEX64 = /^[0-9a-f]{64}$/;84const VERSION = /^[A-Za-z0-9.-]{1,32}$/;85// A file name that is safe as one key segment and inside a quoted Content-Disposition filename.86const FILE_NAME = /^[^/\\"\p{Cc}]{1,255}$/u;87const decoder = new TextDecoder();88// A run of whole UTF-8 sequences (RFC 3629), or one byte outside them, over a record read one89// character per byte.90const UTF8_RUN =91	/((?:[^\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;92// A surrogate pair escape, a lone surrogate escape, or any other escape (`\\` included), whole.93const JSON_ESCAPE =94	/\\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;9596// ponytail: one full listing per call; switch to a delimiter listing if the bucket grows large.97export async function listRepos(bucket: Bucket): Promise<string[]> {98	const keys = await bucket.list("");99	return keys100		.filter((key) => key.endsWith("/head") && key.split("/").length === 2)101		.map((key) => key.slice(0, -"/head".length))102		.filter(isRepoName);103}104105function isRepoName(name: string): boolean {106	return REPO_NAME.test(name) && name !== "." && name !== "..";107}108109// Checked here rather than in route handlers, so no caller can build a key from unchecked input.110function requireRepo(repo: string): void {111	if (!isRepoName(repo)) throw new BucketError(`not a repo name: "${repo}"`);112}113114function requireSaveId(id: string): void {115	if (!SAVE_ID.test(id)) throw new BucketError(`not a save ID: "${id}"`);116}117118/** Applies §9.2's format rule: a missing key is version 1; anything but `koh-remote 1` is refused. */119export async function checkFormat(bucket: Bucket, repo: string): Promise<void> {120	requireRepo(repo);121	const bytes = await bucket.get(`${repo}/format`);122	if (bytes === null) return;123	const format = decoder.decode(bytes).trim();124	if (format !== "koh-remote 1") {125		throw new BucketError(`${repo} uses remote format "${format}"; update Kepr to read it`);126	}127}128129export async function readHead(bucket: Bucket, repo: string): Promise<string | null> {130	requireRepo(repo);131	const bytes = await bucket.get(`${repo}/head`);132	if (bytes === null) return null;133	const head = decoder.decode(bytes).trim();134	if (!SAVE_ID.test(head)) throw new BucketError(`${repo}/head is not a save ID: "${head}"`);135	return head;136}137138export async function readSave(bucket: Bucket, repo: string, id: string): Promise<ArrivingSave> {139	requireRepo(repo);140	requireSaveId(id);141	const bytes = await bucket.get(`${repo}/saves/${id}`);142	if (bytes === null) throw new BucketError(`${repo}/saves/${id} is missing`);143	const record = parseSaveRecord(JSON.parse(decodeRecord(bytes)));144	if (record.id !== id) throw new BucketError(`${repo}/saves/${id} holds save ${record.id}`);145	return {146		...record,147		files: record.files.filter((file) => isSafePath(file.path)),148		quarantined: record.files149			.filter((file) => !isSafePath(file.path))150			.map((file) => escapePath(file.path)),151	};152}153154/**155 * A record's text, read as Koh reads it (\u00A75.5): an unpaired surrogate escape stands for its three156 * bytes, and each byte outside a valid UTF-8 sequence becomes the lone surrogate U+DC00 + byte, so157 * the path holding it fails `isWellFormed` while a genuine U+FFFD stays legal.158 */159function decodeRecord(bytes: Uint8Array): string {160	const text = Buffer.from(bytes)161		.toString("latin1")162		.replace(JSON_ESCAPE, (sequence) => {163			if (sequence.length !== 6 || sequence[1] !== "u") return sequence;164			const unit = Number.parseInt(sequence.slice(2), 16);165			return String.fromCharCode(166				0xe0 | (unit >> 12),167				0x80 | ((unit >> 6) & 0x3f),168				0x80 | (unit & 0x3f),169			);170		});171	return text.replace(UTF8_RUN, (run, valid: string | undefined) =>172		valid === undefined173			? String.fromCharCode(0xdc00 + run.charCodeAt(0))174			: decoder.decode(Buffer.from(valid, "latin1")),175	);176}177178/** Fetches an object, inflates it and checks its Blake3 against its key, as steal does (§9.4). */179export async function readObject(180	bucket: Bucket,181	repo: string,182	hash: string,183): Promise<VerifiedObject> {184	requireRepo(repo);185	if (!HEX64.test(hash)) throw new BucketError(`not an object hash: "${hash}"`);186	const compressed = await bucket.get(`${repo}/objects/${hash}`);187	if (compressed === null) throw new BucketError(`${repo}/objects/${hash} is missing`);188	let bytes: Uint8Array;189	try {190		bytes = new Uint8Array(inflateSync(compressed, { maxOutputLength: MAX_OBJECT }));191	} catch (cause) {192		if (cause instanceof RangeError) {193			throw new OversizedObject(`${repo}/objects/${hash} inflates past 512 MiB`);194		}195		throw cause;196	}197	if (bytesToHex(blake3(bytes)) !== hash) {198		throw new BucketError(`${repo}/objects/${hash} does not match its hash`);199	}200	return { compressed, bytes };201}202203export async function listEventIds(bucket: Bucket, repo: string): Promise<string[]> {204	requireRepo(repo);205	const prefix = `${repo}/events/`;206	// A folder remote's half-written temp files can show up in a listing; only IDs are events.207	return (await bucket.list(prefix))208		.map((key) => key.slice(prefix.length))209		.filter((id) => SAVE_ID.test(id));210}211212export async function readEvent(bucket: Bucket, repo: string, id: string): Promise<EventRecord> {213	requireRepo(repo);214	requireSaveId(id);215	const bytes = await bucket.get(`${repo}/events/${id}`);216	if (bytes === null) throw new BucketError(`${repo}/events/${id} is missing`);217	const record = parseEventRecord(JSON.parse(decodeRecord(bytes)));218	if (record.id !== id) throw new BucketError(`${repo}/events/${id} holds event ${record.id}`);219	return record;220}221222/** §11.1's version rule, minus `.` and `..`, which would name a folder rather than a version. */223export function isVersion(value: string): boolean {224	return VERSION.test(value) && value !== "." && value !== "..";225}226227export function isPlatform(value: string): boolean {228	return (PLATFORMS as readonly string[]).includes(value);229}230231/** The body of `<repo>/releases/latest`, trimmed, or null when the repo has never released. */232export async function readReleasesLatest(bucket: Bucket, repo: string): Promise<string | null> {233	requireRepo(repo);234	const bytes = await bucket.get(`${repo}/releases/latest`);235	if (bytes === null) return null;236	const version = decoder.decode(bytes).trim();237	if (!isVersion(version))238		throw new BucketError(`${repo}/releases/latest is not a version: "${version}"`);239	return version;240}241242/** Every version with a `release.json`: a version without one doesn't exist (§11.2). */243export async function listReleaseVersions(bucket: Bucket, repo: string): Promise<string[]> {244	requireRepo(repo);245	return (await bucket.list(`${repo}/releases/`))246		.map((key) => key.split("/"))247		.filter((parts) => parts.length === 4 && parts[3] === "release.json")248		.map((parts) => parts[2] as string)249		.filter(isVersion);250}251252export async function readRelease(253	bucket: Bucket,254	repo: string,255	version: string,256): Promise<ReleaseRecord> {257	requireRelease(repo, version);258	const key = `${repo}/releases/${version}/release.json`;259	const bytes = await bucket.get(key);260	if (bytes === null) throw new BucketError(`${key} is missing`);261	return checkRelease(repo, version, JSON.parse(decoder.decode(bytes)));262}263264/** A parsed `<repo>/releases/<version>/release.json`, if the sync would accept it (§11.2). */265export function checkRelease(repo: string, version: string, value: unknown): ReleaseRecord {266	requireRelease(repo, version);267	const record = parseReleaseRecord(value);268	if (record.repo !== repo || record.version !== version) {269		throw new BucketError(270			`${repo}/releases/${version}/release.json holds ${record.repo} ${record.version}`,271		);272	}273	return record;274}275276function requireRelease(repo: string, version: string): void {277	requireRepo(repo);278	if (!isVersion(version)) throw new BucketError(`not a release version: "${version}"`);279}280281function parseReleaseRecord(value: unknown): ReleaseRecord {282	const r = value as Record<string, unknown>;283	const valid =284		typeof value === "object" &&285		value !== null &&286		r.format === 1 &&287		typeof r.repo === "string" &&288		typeof r.version === "string" &&289		typeof r.save === "string" &&290		SAVE_ID.test(r.save) &&291		isCount(r.published_at) &&292		typeof r.machine === "string" &&293		typeof r.notes === "string" &&294		Array.isArray(r.files) &&295		r.files.every(isReleaseFile) &&296		// One file per platform per version (§11.2).297		new Set(r.files.map((file) => file.platform)).size === r.files.length;298	if (!valid) throw new BucketError("release record does not match §11.2");299	return value as ReleaseRecord;300}301302function isReleaseFile(value: unknown): value is ReleaseFile {303	const f = value as Record<string, unknown>;304	return (305		typeof value === "object" &&306		value !== null &&307		typeof f.platform === "string" &&308		isPlatform(f.platform) &&309		typeof f.name === "string" &&310		FILE_NAME.test(f.name) &&311		f.name !== "." &&312		f.name !== ".." &&313		isCount(f.size) &&314		typeof f.blake3 === "string" &&315		HEX64.test(f.blake3) &&316		typeof f.sha256 === "string" &&317		HEX64.test(f.sha256)318	);319}320321function parseSaveRecord(value: unknown): SaveRecord {322	const r = value as Record<string, unknown>;323	const valid =324		typeof value === "object" &&325		value !== null &&326		["message", "machine", "agent", "session"].every((key) => typeof r[key] === "string") &&327		typeof r.id === "string" &&328		SAVE_ID.test(r.id) &&329		["parent", "restores", "replayed_from"].every((key) => isOptionalSaveId(r[key])) &&330		isCount(r.created_at) &&331		isCount(r.size_bytes) &&332		typeof r.is_checkpoint === "boolean" &&333		Array.isArray(r.files) &&334		r.files.every(isSaveFile) &&335		new Set(r.files.map((file) => file.path)).size === r.files.length;336	if (!valid) throw new BucketError("save record does not match the Koh 3 schema");337	return value as SaveRecord;338}339340function parseEventRecord(value: unknown): EventRecord {341	const r = value as Record<string, unknown>;342	const valid =343		typeof value === "object" &&344		value !== null &&345		typeof r.id === "string" &&346		SAVE_ID.test(r.id) &&347		isOptionalSaveId(r.save_id) &&348		typeof r.path === "string" &&349		// A flag or clear is about one save and no path; a strip names a path, and one save or350		// (with no ID) all. Sync ignores a strip whose path is illegal, as Koh does (§5.5).351		(r.kind === "strip" ||352			((r.kind === "flag" || r.kind === "clear") && r.save_id !== "" && r.path === "")) &&353		typeof r.reason === "string" &&354		typeof r.machine === "string" &&355		isCount(r.created_at);356	if (!valid) throw new BucketError("event record does not match the Koh 3 schema");357	return value as EventRecord;358}359360function isOptionalSaveId(value: unknown): boolean {361	return value === "" || (typeof value === "string" && SAVE_ID.test(value));362}363364function isCount(value: unknown): boolean {365	return Number.isSafeInteger(value) && (value as number) >= 0;366}367368/** §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. */369export function isSafePath(path: string): boolean {370	return (371		path.isWellFormed() &&372		!path.includes("\\") &&373		!CONTROL_CHAR.test(path) &&374		path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..")375	);376}377378/** A name printable without its controls reaching the page, as Koh's `escape_path` prints it. */379export function escapePath(path: string): string {380	return path381		.replace(/[\\\p{Cc}\udc80-\udcff]/gu, (char) => {382			const code = char.charCodeAt(0);383			if (char === "\\") return "\\\\";384			// A byte `decodeRecord` found outside UTF-8.385			if (code >= 0xdc80) return `\\x${(code - 0xdc00).toString(16)}`;386			const hex = code.toString(16).padStart(2, "0");387			return code >= 0x80 ? `\\u00${hex}` : `\\x${hex}`;388		})389		.toWellFormed();390}391392function isSaveFile(value: unknown): value is SaveFile {393	const f = value as Record<string, unknown>;394	return (395		typeof value === "object" &&396		value !== null &&397		typeof f.path === "string" &&398		typeof f.hash === "string" &&399		HEX64.test(f.hash) &&400		typeof f.executable === "boolean"401	);402}