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 };789export 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 22 manifest?: string;23 files: SaveFile[];24};252627export 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};363738export type ReleaseFile = {39 platform: string;40 name: string;41 size: number;42 blake3: string;43 sha256: string;44};454647export 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};575859export 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;686970export type ArrivingSave = SaveRecord & { quarantined: string[] };717273export type VerifiedObject = { compressed: Uint8Array; size: number };7475export class BucketError extends Error {}767778export class OversizedObject extends BucketError {}7980const MAX_OBJECT = 512 * 1024 * 1024;81828384export 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}$/;8990const FILE_NAME = /^[^/\\"\p{Cc}]{1,255}$/u;91const decoder = new TextDecoder();929394const 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;9697const 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>;101102103104105106107export 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}121122123function 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}130131132export 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}141142143export 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}171172173export 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}183184185186187188189function 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}213214215export function objectSize(bucket: Bucket, repo: string, hash: string): Promise<number> {216 return bucket.size(objectKey(repo, hash));217}218219220221222223export 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 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}263264265export 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}272273274export 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}283284285export 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}305306307export 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 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 379 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 395 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}412413414export 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}422423424export 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 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}