1import { beforeAll, describe, expect, test } from "bun:test";2import { join } from "node:path";3import { BucketWriteError, openBucket } from "../src/bucket/reader.ts";4import { listRepos } from "../src/bucket/repo.ts";5import { Browser, type Instance, instance } from "./browser.ts";6import { makeRepos } from "./fixture.ts";78const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]);9const MP4 = new Uint8Array([0, 0, 0, 0x18, ...new TextEncoder().encode("ftypisom"), 1, 2, 3, 4]);1011describe("editing a repo's description and details while signed in", () => {12 let inst: Instance;13 let browser: Browser;14 let bucketDir: string;15 const page = async (path: string) => (await inst.app.request(path)).text();16 const save = (field: string, value: string) =>17 browser.post("/admin/repos/app/text", { field, value });18 const upload = (bytes: Uint8Array, name: string) => {19 const data = new FormData();20 data.append("file", new File([bytes], name));21 return browser.post("/admin/repos/app/media", data);22 };2324 beforeAll(async () => {25 const repos = await makeRepos(["app", "shy"]);26 bucketDir = repos.bucketDir;27 inst = await instance(bucketDir);28 inst.kepr.run("UPDATE repos SET public = 1 WHERE name = 'app'");29 browser = new Browser(inst.app);30 });3132 test("signing in leaves a script-readable mark that says only that, beside the session", async () => {33 const response = await browser.signIn();34 const cookies = response.headers.getSetCookie();35 expect(cookies.find((line) => line.startsWith("kepr_editor=1"))).not.toMatch(/HttpOnly/i);36 expect(cookies.find((line) => line.startsWith("kepr_session="))).toMatch(/HttpOnly/i);37 38 expect(await (await browser.request("/app")).text()).toBe(await page("/app"));39 });4041 test("starts from the README's words", async () => {42 const response = await browser.request("/admin/repos/app/text");43 const texts = (await response.json()) as Record<"form" | "description" | "details", string>;44 expect(texts.description).toBe("The app project.");45 expect(texts.details).toContain("# app");46 47 expect(texts.form).toBe(browser.form);48 });4950 test("the operator's description replaces the README's on the page, in cards and previews", async () => {51 expect((await save("description", "My **own** words.")).status).toBe(204);52 const repo = await page("/app");53 expect(repo).toContain('<div class="repo-desc"><p>My <strong>own</strong> words.</p></div>');54 expect(repo).toContain('<meta name="description" content="My own words.">');55 expect(await page("/browse")).toContain('<p class="repo-card-desc">My own words.</p>');56 });5758 test("details size and place pictures and videos from their options, and keep uploads' URLs", async () => {59 const details = [60 '',61 '',62 "",63 '',64 ].join("\n\n");65 expect((await save("details", details)).status).toBe(204);66 const repo = await page("/app");67 expect(repo).toContain(68 '<img src="/static/assets/media/app/a.png" alt="shot" class="media media-w33 media-right">',69 );70 expect(repo).toContain(71 '<video class="media media-w50 media-left" src="/static/assets/media/app/b.mp4" autoplay muted loop playsinline aria-label="demo"></video>',72 );73 expect(repo).toContain(74 '<video class="media media-w100 media-center" src="/static/assets/media/app/c.webm" controls preload="metadata" aria-label="talk"></video>',75 );76 77 expect(repo).toContain('<img src="/app/raw/pic.png" alt="plain" title="a real title">');78 expect(repo).not.toContain("# app");79 });8081 test("the preview renders as the page will", async () => {82 const response = await browser.post("/admin/repos/app/preview", {83 field: "details",84 value: "**hi** <script>x</script>",85 });86 expect(await response.text()).toBe(87 "<p><strong>hi</strong> <script>x</script></p>\n",88 );89 });9091 test("clearing a text brings the README's back", async () => {92 await save("description", "");93 await save("details", "");94 const repo = await page("/app");95 expect(repo).toContain("<p>The app project.</p>");96 expect(repo).toContain("<h1>app</h1>");97 });9899 test("refuses an unknown field, an overlong text and an unknown repo", async () => {100 expect((await save("title", "x")).status).toBe(400);101 expect((await save("description", "x".repeat(2001))).status).toBe(400);102 expect((await browser.post("/admin/repos/nope/text", { field: "details" })).status).toBe(404);103 });104105 test("uploads pictures and videos by what their bytes are, served as privately as the repo", async () => {106 const png = await upload(PNG, "shot.txt");107 expect(png.status).toBe(200);108 const { url } = (await png.json()) as { url: string };109 expect(url).toMatch(/^\/static\/assets\/media\/app\/[0-9a-f]{64}\.png$/);110 111 const key = `.kepr/media/app/${url.split("/").pop()}`;112 expect(await Bun.file(join(bucketDir, key)).exists()).toBe(true);113 expect(await listRepos(openBucket({ kind: "folder", path: bucketDir }))).toEqual([114 "app",115 "shy",116 ]);117 const served = await inst.app.request(url);118 expect([served.status, served.headers.get("content-type")]).toEqual([200, "image/png"]);119 const video = ((await (await upload(MP4, "demo.mp4")).json()) as { url: string }).url;120 expect(video).toEndWith(".mp4");121 122 const server = Bun.serve({ port: 0, fetch: (request) => inst.app.fetch(request) });123 const range = await fetch(new URL(video, server.url), { headers: { range: "bytes=0-3" } });124 expect([range.status, (await range.arrayBuffer()).byteLength]).toEqual([206, 4]);125 server.stop();126 expect((await upload(new TextEncoder().encode("<svg onload=x>"), "a.svg")).status).toBe(400);127 inst.kepr.run("UPDATE repos SET public = 0 WHERE name = 'app'");128 expect((await inst.app.request(url)).status).toBe(404);129 inst.kepr.run("UPDATE repos SET public = 1 WHERE name = 'app'");130 });131132 test("signed out, none of it answers", async () => {133 const stranger = new Browser(inst.app);134 expect((await stranger.request("/admin/repos/app/text")).status).toBe(401);135 expect((await stranger.post("/admin/repos/app/media", new FormData())).status).toBe(401);136 });137});138139test("Kepr writes only its own folder and builds, and to S3 only with the write key", async () => {140 const { bucketDir } = await makeRepos(["app"]);141 const folder = openBucket({ kind: "folder", path: bucketDir });142 const refused = ["app/head", ".kepr/../app/head", ".kepr//x", "x/.kepr/y", "app/releases/.."];143 for (const key of [...refused, "app/releases/1.0.0/app", "app/releases/1.0.0/x/release.json"]) {144 await expect(folder.put(key, new Uint8Array([1]), "image/png")).rejects.toBeInstanceOf(145 BucketWriteError,146 );147 }148 for (const key of [...refused, "app/saves/x", "app/releases/1.0.0/"]) {149 await expect(folder.remove(key)).rejects.toBeInstanceOf(BucketWriteError);150 }151 await folder.put("app/releases/latest", new TextEncoder().encode("1.0.0"), "text/plain");152 expect(await Bun.file(`${bucketDir}/app/releases/latest`).text()).toBe("1.0.0");153 await folder.put("app/releases/1.0.0/release.json", new Uint8Array([1]), "application/json");154 await folder.put(".kepr/x", new Uint8Array([1]), "text/plain");155 await folder.remove(".kepr/x");156 expect(await Bun.file(`${bucketDir}/.kepr/x`).exists()).toBe(false);157 const readOnly = openBucket({158 kind: "s3",159 endpoint: "http://127.0.0.1:9",160 name: "b",161 region: "r",162 accessKeyId: "k",163 secretAccessKey: "s",164 });165 await expect(166 readOnly.put(".kepr/media/app/x.png", new Uint8Array([1]), "image/png"),167 ).rejects.toThrow("[bucket.write]");168 await expect(readOnly.remove(".kepr/media/app/x.png")).rejects.toThrow("[bucket.write]");169});