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 { platform, 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 koh(57 cwd: string,58 home: string,59 args: string[],60 env: Record<string, string> = {},61): Promise<Ran> {62 const proc = Bun.spawn(["koh", ...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 koh(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 koh(repoDir, ownerHome, ["init"], keys)).code).toBe(0);99 expect(100 (await koh(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 koh(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 koh(repoDir, ownerHome, ["save", "second save"])).code).toBe(0);107 108 109 expect((await koh(keptDir, ownerHome, ["init"], keys)).code).toBe(0);110 await writeFile(join(keptDir, "secret.txt"), "kept in the bucket\n");111 expect((await koh(keptDir, ownerHome, ["save", "a private repo"])).code).toBe(0);112113 114 const dataDir = await mkdtemp(join(tmpdir(), "kepr-steal-kepr-"));115 const kepr = openKeprDb(dataDir);116 const bucket = {117 kind: "s3" as const,118 endpoint,119 name: BUCKET,120 region: "fr-par",121 accessKeyId: ACCESS,122 secretAccessKey: SECRET,123 };124 125 const sync = () =>126 syncAll({127 bucket: openBucket(bucket),128 kepr,129 mirrorDir: join(dataDir, "mirror"),130 });131 await sync();132 kepr.query("UPDATE repos SET public = 1 WHERE name = ?").run(REPO);133 let app: Hono;134 const server = Bun.serve({135 port: 0,136 fetch: (request) => app.fetch(request),137 });138 app = createApp(139 {140 domain: `127.0.0.1:${server.port}`,141 dataDir,142 adminPasswordHash: await Bun.password.hash(PASSWORD, "argon2id"),143 bucket,144 },145 kepr,146 );147 const host = `http://127.0.0.1:${server.port}`;148149 150 const thiefHome = join(root, "thief-home");151 const thiefDir = join(root, "thief");152 await mkdir(thiefHome, { recursive: true });153 await mkdir(thiefDir, { recursive: true });154 const stolen = await koh(thiefDir, thiefHome, ["steal", `${host}/${REPO}`]);155 expect(stolen.code, stolen.err + stolen.out).toBe(0);156 const copy = join(thiefDir, REPO);157 expect(await readFile(join(copy, "README.md"), "utf8")).toContain("edited");158 expect((await koh(copy, thiefHome, ["doctor"])).code).toBe(0);159 160 expect(await line(copy, thiefHome)).toEqual(await line(repoDir, ownerHome));161 162 expect((await koh(copy, thiefHome, ["remote"])).out).toContain(`${host}/${REPO}`);163 164 const refused = await koh(copy, thiefHome, ["offer"]);165 expect(refused.code).toBe(1);166 expect(refused.err + refused.out).toContain("which is read-only");167168 169 await writeFile(join(repoDir, "README.md"), "# shipped\n\nA third save.\n");170 expect((await koh(repoDir, ownerHome, ["save", "third save"])).code).toBe(0);171 await sync();172 expect((await koh(copy, thiefHome, ["steal", "--yes"])).code).toBe(0);173 expect(await readFile(join(copy, "README.md"), "utf8")).toContain("A third save");174175 176 177 178 179 await stripPath(repoDir, ownerHome, "src.v");180 181 expect(await readFile(join(repoDir, ".kohignore"), "utf8")).toContain("/src.v\n");182 expect((await koh(repoDir, ownerHome, ["save", "ignore the stripped src.v"])).code).toBe(0);183 await sync();184 expect((await koh(copy, thiefHome, ["steal", "--yes"])).code).toBe(0);185 expect((await koh(copy, thiefHome, ["doctor"])).code).toBe(0);186 expect(await Bun.file(join(copy, "src.v")).exists()).toBe(true);187 188 const status = (await koh(copy, thiefHome, ["status"])).out;189 expect(status).not.toContain("+ src.v");190 expect(status).toContain("no changes");191 const fresh = join(root, "thief-again");192 await mkdir(fresh, { recursive: true });193 expect((await koh(fresh, thiefHome, ["steal", `${host}/${REPO}`])).code).toBe(0);194 expect(await Bun.file(join(fresh, REPO, "src.v")).exists()).toBe(false);195 196 const third = join(root, "thief-three");197 await mkdir(third, { recursive: true });198 expect((await koh(third, thiefHome, ["steal", `${host}/${REPO}`])).code).toBe(0);199 200 const fourth = join(root, "thief-four");201 await mkdir(fourth, { recursive: true });202 expect((await koh(fourth, thiefHome, ["steal", `${host}/${REPO}`])).code).toBe(0);203204 205 206 207 const origin = `https://127.0.0.1:${server.port}`;208 const browser = new Browser(app);209 const signInPage = await browser.get("/sign-in");210 const form = /name="form" value="([^"]+)"/.exec(await signInPage.text())?.[1] ?? "";211 const signed = await browser.request("/sign-in", {212 method: "POST",213 headers: { origin },214 body: new URLSearchParams({ form, password: PASSWORD }),215 });216 expect(signed.status).toBe(303);217 const machine = "thief-machine";218 expect((await browser.get(`/connect?machine=${machine}`)).status).toBe(200);219 const shown = await browser.post("/connect", { machine }, origin);220 const code = /class="mono code">([^<]+)</.exec(await shown.text())?.[1]?.trim() ?? "";221 expect(code).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}$/);222 const signedIn = await koh(thiefDir, thiefHome, ["remote", host, "--code", code]);223 expect(signedIn.code, signedIn.err + signedIn.out).toBe(0);224225 226 227 await writeFile(join(copy, "local.txt"), "work in progress\n");228 const local = await koh(copy, thiefHome, ["save", "local only"]);229 expect(local.code, local.err + local.out).toBe(0);230 expect(local.out + local.err).not.toContain("offered");231 expect((await koh(copy, thiefHome, ["remote"])).out).toContain(`${host}/${REPO}`);232233 234 235 const upgraded = await koh(copy, thiefHome, ["offer"]);236 expect(upgraded.code, upgraded.err + upgraded.out).toBe(0);237 expect(upgraded.out + upgraded.err).toContain("now syncs with your bucket");238 239 240 expect((await koh(repoDir, ownerHome, ["revert", "--yes"])).code).toBe(0);241 expect((await koh(repoDir, ownerHome, ["steal", "--yes"])).code).toBe(0);242 expect(await readFile(join(repoDir, "local.txt"), "utf8")).toContain("work in progress");243 expect(JSON.parse((await koh(repoDir, ownerHome, ["view", "--json"])).out).saves).toEqual(244 JSON.parse((await koh(copy, thiefHome, ["view", "--json"])).out).saves,245 );246 await writeFile(join(copy, "README.md"), "# shipped\n\nThe thief's edit.\n");247 expect((await koh(copy, thiefHome, ["save", "from the thief"])).code).toBe(0);248 expect((await koh(repoDir, ownerHome, ["steal", "--yes"])).code).toBe(0);249 expect(await readFile(join(repoDir, "README.md"), "utf8")).toContain("The thief's edit");250251 252 253 254 const other = join(fresh, REPO);255 await writeFile(join(repoDir, "README.md"), "# shipped\n\nThe owner's edit.\n");256 expect((await koh(repoDir, ownerHome, ["save", "owner edits the readme"])).code).toBe(0);257 await writeFile(join(other, "README.md"), "# shipped\n\nThe other copy's edit.\n");258 expect((await koh(other, thiefHome, ["save", "other copy edits"])).code).toBe(0);259 const clashed = await koh(other, thiefHome, ["offer", "--yes"]);260 expect(clashed.code).toBe(1);261 expect(clashed.err).toContain(262 'README.md changed on both machines — run "koh steal" to choose, then offer',263 );264 expect(await readFile(join(other, "README.md"), "utf8")).toContain("other copy's edit");265 expect((await koh(other, thiefHome, ["remote"])).out).toContain(`${host}/${REPO}`);266 267 const chosen = await koh(other, thiefHome, ["steal", "--theirs", "--yes"]);268 expect(chosen.code, chosen.err + chosen.out).toBe(0);269 expect(chosen.out + chosen.err).toContain("now syncs with your bucket");270 expect(chosen.out + chosen.err).toContain("your README.md is in");271 expect(await readFile(join(other, "README.md"), "utf8")).toContain("The owner's edit");272273 274 const second = join(root, "thief-two");275 await mkdir(second, { recursive: true });276 const kept = await koh(second, thiefHome, ["steal", `${host}/${PRIVATE_REPO}`]);277 expect(kept.code, kept.err + kept.out).toBe(0);278 expect(await readFile(join(second, PRIVATE_REPO, "secret.txt"), "utf8")).toContain("kept");279 280 expect((await koh(second, thiefHome, ["remote"])).out).toContain(`s3 ${endpoint}`);281282 283 expect((await koh(repoDir, ownerHome, ["steal", "--yes"])).code).toBe(0);284 await writeFile(join(repoDir, "risky.txt"), "risky\n");285 286 await writeFile(join(repoDir, "VERSION"), "1.0.0\n");287 await writeFile(288 join(repoDir, "koh.build"),289 [290 `command = mkdir -p out && printf built > out/app-1.0.0-${platform()}`,291 "output = out/app-{version}-{platform}",292 `platforms = ${platform()}`,293 "",294 ].join("\n"),295 );296 const risky = JSON.parse(297 (await koh(repoDir, ownerHome, ["save", "risky", "--json"])).out,298 ).id;299 const flag = await koh(repoDir, ownerHome, ["flag", risky, "--reason", "broke the build"]);300 expect(flag.code, flag.err + flag.out).toBe(0);301 expect((await koh(repoDir, ownerHome, ["offer"])).code).toBe(0);302 const flaggedOffer = await koh(join(third, REPO), thiefHome, ["offer", "--json", "--yes"]);303 expect(flaggedOffer.code, flaggedOffer.err + flaggedOffer.out).toBe(0);304 expect(JSON.parse(flaggedOffer.out).flagged).toEqual([risky]);305 const flaggedBuilds = await koh(join(fourth, REPO), thiefHome, [306 "offer",307 "--builds",308 "--json",309 "--yes",310 ]);311 expect(flaggedBuilds.code, flaggedBuilds.err + flaggedBuilds.out).toBe(0);312 expect(JSON.parse(flaggedBuilds.out).flagged).toEqual([risky]);313 } finally {314 bucketServer.stop();315 }316 },317 RUN,318 );319});