1234567891011import { describe, expect, test } from "bun:test";12import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";13import { tmpdir } from "node:os";14import { join } from "node:path";15import type { Hono } from "hono";16import { openBucket } from "../src/bucket/reader.ts";17import { syncAll } from "../src/bucket/sync.ts";18import { createApp } from "../src/server/app.ts";19import { openKeprDb } from "../src/server/db.ts";20import { Browser, PASSWORD } from "./browser.ts";21import { stripPath } from "./fixture.ts";2223const REPO = "shipped";24const PRIVATE_REPO = "kept";25const BUCKET = "kohbucket";26const ACCESS = "fake-access";27const SECRET = "fake-secret";2829const RUN = 60_000;30313233343536async function startBucket(): Promise<{ endpoint: string; stop: () => void }> {37 const proc = Bun.spawn(["bun", "run", join(import.meta.dir, "fake-s3.ts")], {38 stdout: "pipe",39 stderr: "inherit",40 });41 const reader = proc.stdout.getReader();42 const first = await reader.read();43 const endpoint =44 new TextDecoder()45 .decode(first.value ?? new Uint8Array())46 .trim()47 .split("\n")[0] ?? "";48 reader.releaseLock();49 expect(endpoint).toStartWith("http://127.0.0.1:");50 return { endpoint, stop: () => proc.kill() };51}5253type Ran = { code: number; out: string; err: string };545556async function koh3(57 cwd: string,58 home: string,59 args: string[],60 env: Record<string, string> = {},61): Promise<Ran> {62 const proc = Bun.spawn(["koh3", ...args], {63 cwd,64 env: { PATH: process.env.PATH, HOME: home, NO_COLOR: "1", ...env },65 stdout: "pipe",66 stderr: "pipe",67 });68 const [out, err, code] = await Promise.all([69 new Response(proc.stdout).text(),70 new Response(proc.stderr).text(),71 proc.exited,72 ]);73 return { code, out, err };74}757677async function line(repo: string, home: string): Promise<unknown> {78 return JSON.parse((await koh3(repo, home, ["view", "--json"])).out).saves;79}8081describe.serial("stealing a public repo from Kepr over HTTP", () => {82 test(83 "a stolen copy comes over the wire, stays read-only, and follows its source",84 async () => {85 const root = await mkdtemp(join(tmpdir(), "kepr-steal-"));86 const bucketServer = await startBucket();87 const endpoint = bucketServer.endpoint;88 const keys = { KOH_ACCESS_KEY: ACCESS, KOH_SECRET_KEY: SECRET };89 try {90 91 const ownerHome = join(root, "owner-home");92 const ownerDir = join(root, "owner");93 const repoDir = join(ownerDir, REPO);94 const keptDir = join(ownerDir, PRIVATE_REPO);95 await mkdir(ownerHome, { recursive: true });96 await mkdir(repoDir, { recursive: true });97 await mkdir(keptDir, { recursive: true });98 expect((await koh3(repoDir, ownerHome, ["init"], keys)).code).toBe(0);99 expect(100 (await koh3(repoDir, ownerHome, ["remote", "s3", endpoint, BUCKET, "fr-par"], keys)).code,101 ).toBe(0);102 await writeFile(join(repoDir, "README.md"), "# shipped\n\nA repo to steal.\n");103 await writeFile(join(repoDir, "src.v"), "fn main() {}\n");104 expect((await koh3(repoDir, ownerHome, ["save", "first save"])).code).toBe(0);105 await writeFile(join(repoDir, "README.md"), "# shipped\n\nA repo to steal, edited.\n");106 expect((await koh3(repoDir, ownerHome, ["save", "second save"])).code).toBe(0);107 108 expect((await koh3(keptDir, ownerHome, ["init"], keys)).code).toBe(0);109 expect(110 (await koh3(keptDir, ownerHome, ["remote", "s3", endpoint, BUCKET, "fr-par"], keys)).code,111 ).toBe(0);112 await writeFile(join(keptDir, "secret.txt"), "kept in the bucket\n");113 expect((await koh3(keptDir, ownerHome, ["save", "a private repo"])).code).toBe(0);114115 116 const dataDir = await mkdtemp(join(tmpdir(), "kepr-steal-kepr-"));117 const kepr = openKeprDb(dataDir);118 const bucket = {119 kind: "s3" as const,120 endpoint,121 name: BUCKET,122 region: "fr-par",123 accessKeyId: ACCESS,124 secretAccessKey: SECRET,125 };126 127 const sync = () =>128 syncAll({129 bucket: openBucket(bucket),130 kepr,131 mirrorDir: join(dataDir, "mirror"),132 tarballDir: join(dataDir, "tarballs"),133 });134 await sync();135 kepr.query("UPDATE repos SET public = 1 WHERE name = ?").run(REPO);136 let app: Hono;137 const server = Bun.serve({138 port: 0,139 fetch: (request) => app.fetch(request),140 });141 app = createApp(142 {143 domain: `127.0.0.1:${server.port}`,144 dataDir,145 adminPasswordHash: await Bun.password.hash(PASSWORD, "argon2id"),146 bucket: { ...bucket, write: { accessKeyId: ACCESS, secretAccessKey: SECRET } },147 },148 kepr,149 );150 const host = `http://127.0.0.1:${server.port}`;151152 153 const thiefHome = join(root, "thief-home");154 const thiefDir = join(root, "thief");155 await mkdir(thiefHome, { recursive: true });156 await mkdir(thiefDir, { recursive: true });157 const stolen = await koh3(thiefDir, thiefHome, ["steal", `${host}/${REPO}`]);158 expect(stolen.code, stolen.err + stolen.out).toBe(0);159 const copy = join(thiefDir, REPO);160 expect(await readFile(join(copy, "README.md"), "utf8")).toContain("edited");161 expect((await koh3(copy, thiefHome, ["doctor"])).code).toBe(0);162 163 expect(await line(copy, thiefHome)).toEqual(await line(repoDir, ownerHome));164 165 expect((await koh3(copy, thiefHome, ["remote"])).out).toContain(`${host}/${REPO}`);166 167 const refused = await koh3(copy, thiefHome, ["offer"]);168 expect(refused.code).toBe(1);169 expect(refused.err + refused.out).toContain("which is read-only");170171 172 await writeFile(join(repoDir, "README.md"), "# shipped\n\nA third save.\n");173 expect((await koh3(repoDir, ownerHome, ["save", "third save"])).code).toBe(0);174 await sync();175 expect((await koh3(copy, thiefHome, ["steal"])).code).toBe(0);176 expect(await readFile(join(copy, "README.md"), "utf8")).toContain("A third save");177178 179 180 181 182 await stripPath(repoDir, ownerHome, "src.v");183 184 expect(await readFile(join(repoDir, ".kohignore"), "utf8")).toContain("/src.v\n");185 expect((await koh3(repoDir, ownerHome, ["save", "ignore the stripped src.v"])).code).toBe(186 0,187 );188 await sync();189 expect((await koh3(copy, thiefHome, ["steal"])).code).toBe(0);190 expect((await koh3(copy, thiefHome, ["doctor"])).code).toBe(0);191 expect(await Bun.file(join(copy, "src.v")).exists()).toBe(true);192 expect((await koh3(copy, thiefHome, ["status"])).out).not.toContain("src.v");193 const fresh = join(root, "thief-again");194 await mkdir(fresh, { recursive: true });195 expect((await koh3(fresh, thiefHome, ["steal", `${host}/${REPO}`])).code).toBe(0);196 expect(await Bun.file(join(fresh, REPO, "src.v")).exists()).toBe(false);197 198 const third = join(root, "thief-three");199 await mkdir(third, { recursive: true });200 expect((await koh3(third, thiefHome, ["steal", `${host}/${REPO}`])).code).toBe(0);201202 203 204 205 const origin = `https://127.0.0.1:${server.port}`;206 const browser = new Browser(app);207 const signInPage = await browser.get("/sign-in");208 const form = /name="form" value="([^"]+)"/.exec(await signInPage.text())?.[1] ?? "";209 const signed = await browser.request("/sign-in", {210 method: "POST",211 headers: { origin },212 body: new URLSearchParams({ form, password: PASSWORD }),213 });214 expect(signed.status).toBe(303);215 const machine = "thief-machine";216 expect((await browser.get(`/connect?machine=${machine}`)).status).toBe(200);217 const shown = await browser.post("/connect", { machine }, origin);218 const code = /class="mono code">([^<]+)</.exec(await shown.text())?.[1]?.trim() ?? "";219 expect(code).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}$/);220 const signedIn = await koh3(thiefDir, thiefHome, ["remote", host, "--code", code]);221 expect(signedIn.code, signedIn.err + signedIn.out).toBe(0);222223 224 225 await writeFile(join(copy, "local.txt"), "work in progress\n");226 const local = await koh3(copy, thiefHome, ["save", "local only"]);227 expect(local.code, local.err + local.out).toBe(0);228 expect(local.out + local.err).not.toContain("offered");229 expect((await koh3(copy, thiefHome, ["remote"])).out).toContain(`${host}/${REPO}`);230231 232 233 const upgraded = await koh3(copy, thiefHome, ["offer"]);234 expect(upgraded.code, upgraded.err + upgraded.out).toBe(0);235 expect(upgraded.out + upgraded.err).toContain("now syncs with your bucket");236 237 238 expect((await koh3(repoDir, ownerHome, ["revert", "--yes"])).code).toBe(0);239 expect((await koh3(repoDir, ownerHome, ["steal"])).code).toBe(0);240 expect(await readFile(join(repoDir, "local.txt"), "utf8")).toContain("work in progress");241 expect(JSON.parse((await koh3(repoDir, ownerHome, ["view", "--json"])).out).saves).toEqual(242 JSON.parse((await koh3(copy, thiefHome, ["view", "--json"])).out).saves,243 );244 await writeFile(join(copy, "README.md"), "# shipped\n\nThe thief's edit.\n");245 expect((await koh3(copy, thiefHome, ["save", "from the thief"])).code).toBe(0);246 expect((await koh3(repoDir, ownerHome, ["steal"])).code).toBe(0);247 expect(await readFile(join(repoDir, "README.md"), "utf8")).toContain("The thief's edit");248249 250 251 252 const other = join(fresh, REPO);253 await writeFile(join(repoDir, "README.md"), "# shipped\n\nThe owner's edit.\n");254 expect((await koh3(repoDir, ownerHome, ["save", "owner edits the readme"])).code).toBe(0);255 await writeFile(join(other, "README.md"), "# shipped\n\nThe other copy's edit.\n");256 expect((await koh3(other, thiefHome, ["save", "other copy edits"])).code).toBe(0);257 const clashed = await koh3(other, thiefHome, ["offer"]);258 expect(clashed.code).toBe(1);259 expect(clashed.err).toContain(260 'README.md changed on both machines — run "koh steal" to choose, then offer',261 );262 expect(await readFile(join(other, "README.md"), "utf8")).toContain("other copy's edit");263 expect((await koh3(other, thiefHome, ["remote"])).out).toContain(`${host}/${REPO}`);264 265 const chosen = await koh3(other, thiefHome, ["steal", "--theirs"]);266 expect(chosen.code, chosen.err + chosen.out).toBe(0);267 expect(chosen.out + chosen.err).toContain("now syncs with your bucket");268 expect(chosen.out + chosen.err).toContain("your README.md is in");269 expect(await readFile(join(other, "README.md"), "utf8")).toContain("The owner's edit");270271 272 const second = join(root, "thief-two");273 await mkdir(second, { recursive: true });274 const kept = await koh3(second, thiefHome, ["steal", `${host}/${PRIVATE_REPO}`]);275 expect(kept.code, kept.err + kept.out).toBe(0);276 expect(await readFile(join(second, PRIVATE_REPO, "secret.txt"), "utf8")).toContain("kept");277 278 expect((await koh3(second, thiefHome, ["remote"])).out).toContain(`s3 ${endpoint}`);279280 281 expect((await koh3(repoDir, ownerHome, ["steal"])).code).toBe(0);282 await writeFile(join(repoDir, "risky.txt"), "risky\n");283 const risky = JSON.parse(284 (await koh3(repoDir, ownerHome, ["save", "risky", "--json"])).out,285 ).id;286 const flag = await koh3(repoDir, ownerHome, ["flag", risky, "--reason", "broke the build"]);287 expect(flag.code, flag.err + flag.out).toBe(0);288 expect((await koh3(repoDir, ownerHome, ["offer"])).code).toBe(0);289 const flaggedOffer = await koh3(join(third, REPO), thiefHome, ["offer", "--json"]);290 expect(flaggedOffer.code, flaggedOffer.err + flaggedOffer.out).toBe(0);291 expect(JSON.parse(flaggedOffer.out).flagged).toEqual([risky]);292 } finally {293 bucketServer.stop();294 }295 },296 RUN,297 );298});