1import { Database } from "bun:sqlite";2import { expect, test } from "bun:test";3import { existsSync } from "node:fs";4import { mkdir, readFile, writeFile } from "node:fs/promises";5import { dirname, join } from "node:path";6import { openBucket } from "../src/bucket/reader.ts";7import { syncAll } from "../src/bucket/sync.ts";8import { flattenTree } from "../src/mirror/manifest.ts";9import { filesAt } from "../src/mirror/queries.ts";10import { openMirror, quarantinedPaths } from "../src/mirror/store.ts";11import { openKeprDb } from "../src/server/db.ts";12import { KOH_BIN, makeKohBucket } from "./fixture.ts";131415const UNSAFE = [16 "../joint-escape.txt",17 "/tmp/koh-joint-absolute.txt",18 "a/../../joint-nested.txt",19 "back\\slash.txt",20 "ctl\u0001name.txt",21 "Icon\r",22 "c1-\u0085",23 24 "lone-\ud800",25 26 "raw-X-byte",27];2829const ILLEGAL_STRIPS = ["src//", "", "src\ud800"];3031test("Koh and Kepr drop the same unsafe paths and keep the same file list for every save (A3)", async () => {32 const fx = await makeKohBucket("joint-paths");33 const head = fx.saveIds[0] as string;34 const key = join(fx.bucketDir, fx.repo, "saves", head);35 const record = JSON.parse(await readFile(key, "utf8"));36 const hash = record.files[0].hash;37 for (const path of UNSAFE) record.files.push({ path, hash, executable: false });38 const bytes = Buffer.from(JSON.stringify(record));39 bytes[bytes.indexOf("raw-X-byte") + 4] = 0xff;40 await writeFile(key, bytes);41 for (const [i, path] of ILLEGAL_STRIPS.entries()) {42 const id = `${i}`.repeat(12);43 const strip = { id, kind: "strip", save_id: "", path, reason: "", created_at: 1, machine: "x" };44 await writeFile(join(fx.bucketDir, fx.repo, "events", id), JSON.stringify(strip));45 }4647 const root = dirname(dirname(fx.repoDir));48 const home = join(root, "second-home");49 const work = join(root, "second-work");50 await mkdir(home);51 await mkdir(work);52 const runKoh = (cwd: string, args: string[]) =>53 Bun.spawnSync([KOH_BIN, ...args], {54 cwd,55 env: { PATH: process.env.PATH, HOME: home, NO_COLOR: "1" },56 });57 expect(runKoh(work, ["remote", "folder", fx.bucketDir]).exitCode).toBe(0);58 const stolen = runKoh(work, ["steal", fx.repo, "--json"]);59 expect(stolen.exitCode, stolen.stderr.toString()).toBe(0);60 const dropped: string[] = JSON.parse(stolen.stdout.toString()).unsafe_paths;6162 const dataDir = join(root, "kepr-data");63 const kepr = openKeprDb(dataDir);64 await syncAll({65 bucket: openBucket({ kind: "folder", path: fx.bucketDir }),66 kepr,67 mirrorDir: join(dataDir, "mirror"),68 });69 expect(kepr.query("SELECT last_sync_error FROM repos").get()).toEqual({ last_sync_error: null });7071 72 73 const sorted = (rows: { save_id: string; path: string }[]) =>74 rows.sort((a, b) =>75 a.save_id === b.save_id ? (a.path < b.path ? -1 : 1) : a.save_id < b.save_id ? -1 : 1,76 );77 const kohFiles = (db: Database) => {78 if (db.query("SELECT 1 FROM sqlite_schema WHERE name = 'save_files'").get()) {79 return sorted(80 db81 .query<{ save_id: string; path: string }, []>("SELECT save_id, path FROM save_files")82 .all(),83 );84 }85 const bodies = new Map(86 db87 .query<{ hash: string; body: string }, []>("SELECT hash, body FROM manifests")88 .all()89 .map((row) => [row.hash, row.body] as const),90 );91 return sorted(92 db93 .query<{ id: string; manifest: string }, []>("SELECT id, manifest FROM saves")94 .all()95 .flatMap((save) =>96 flattenTree((hash) => bodies.get(hash) as string, save.manifest).map((file) => ({97 save_id: save.id,98 path: file.path,99 })),100 ),101 );102 };103 const mirrorFiles = (db: Database) =>104 sorted(105 db106 .query<{ id: string }, []>("SELECT id FROM saves")107 .all()108 .flatMap((save) =>109 filesAt(db, save.id).map((file) => ({ save_id: save.id, path: file.path })),110 ),111 );112 const koh = new Database(join(work, fx.repo, ".koh"));113 const mirror = openMirror(join(dataDir, "mirror"), fx.repo);114 expect(kohFiles(koh)).toEqual(mirrorFiles(mirror));115 expect(kohFiles(koh)).toContainEqual({ save_id: head, path: "src/main.ts" });116 117 expect(dropped.length).toBe(UNSAFE.length);118 expect([...dropped].sort()).toEqual(quarantinedPaths(mirror));119 for (const path of UNSAFE) {120 expect(kohFiles(koh)).not.toContainEqual({ save_id: head, path });121 }122 koh.close();123124 for (const outside of [125 join(work, "joint-escape.txt"),126 join(root, "joint-nested.txt"),127 "/tmp/koh-joint-absolute.txt",128 ]) {129 expect(existsSync(outside), outside).toBe(false);130 }131});