import { execFileSync, spawnSync } from "node:child_process"; import assert from "node:assert/strict"; import { randomBytes } from "node:crypto"; import { emptyNutrients } from "../shared/domain.js"; const image = process.argv[2] || "calio:local"; const unraid = process.argv.includes("--unraid"); const suffix = randomBytes(4).toString("hex"); const name = "calio-smoke-" + suffix; const volume = name + "-data"; const password = randomBytes(24).toString("hex"); const docker = (args, input) => execFileSync("docker", args, { encoding: "utf8", input, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], }).trim(); async function start() { docker([ "run", "-d", "--name", name, ...(unraid ? ["--user", "99:100"] : []), ...(unraid ? ["--mount", `type=volume,source=${volume},target=/data,volume-nocopy`] : ["-v", volume + ":/data"]), "--read-only", "--tmpfs", "/tmp", "--cap-drop", "ALL", "--security-opt", "no-new-privileges:true", "-e", "APP_ORIGIN=http://localhost:3000", "-e", "COOKIE_SECURE=false", "-e", "CALIO_USERNAME=smoke", "-e", "CALIO_PASSWORD=" + password, image, ]); let lastError; for (let i = 0; i < 50; i++) { try { if ((await request("/api/health")).status === 200) return; } catch (error) { lastError = error; if ( docker(["inspect", "--format", "{{.State.Running}}", name]) === "false" ) break; } await new Promise((resolve) => setTimeout(resolve, 200)); } const logs = spawnSync("docker", ["logs", name], { encoding: "utf8" }); throw new Error( "Container failed to start: " + logs.stdout + logs.stderr + "\n" + (lastError?.message || "") + "\n" + docker(["inspect", "--format", "{{json .State}}", name]), ); } // In-container probes work on socket-mounted Forgejo runners without published ports. const request = async (path, body, cookie) => { const probe = `let input=''; for await (const chunk of process.stdin) input+=chunk; const {path,body,cookie}=JSON.parse(input); const response=await fetch('http://127.0.0.1:3000'+path,{ method:body===undefined?'GET':'POST', headers:{'Content-Type':'application/json',Origin:'http://localhost:3000','X-Calio-Request':'1',Cookie:cookie||''}, body:body===undefined?undefined:JSON.stringify(body) }); console.log(JSON.stringify({status:response.status,cookie:response.headers.get('set-cookie'),body:await response.text()}));`; const result = JSON.parse( docker( ["exec", "-i", name, "node", "--input-type=module", "-e", probe], JSON.stringify({ path, body, cookie }), ), ); return { status: result.status, headers: new Headers(result.cookie ? { "set-cookie": result.cookie } : {}), text: async () => result.body, json: async () => JSON.parse(result.body), }; }; try { if (unraid) { docker(["volume", "create", volume]); // Only initialize the unique, disposable test volume, as on Unraid appdata. docker([ "run", "--rm", "--user", "0:0", "-v", volume + ":/data", "--entrypoint", "sh", image, "-c", "chown 99:100 /data", ]); } await start(); assert.equal((await request("/api/records")).status, 401); const login = await request("/api/login", { username: "smoke", password }); assert.equal(login.status, 200); const cookie = login.headers.get("set-cookie").split(";")[0]; const record = { id: "persistence-test", type: "food", updatedAt: new Date().toISOString(), deleted: false, data: { name: "Test food", serving: "1 serving", nutrients: emptyNutrients(), }, }; assert.equal( (await request("/api/sync", { records: [record] }, cookie)).status, 200, ); for (const path of [ "/", "/sw.js", "/manifest.webmanifest", "/icons/apple-touch-icon.png", ]) assert.equal((await request(path)).status, 200, path); const html = await (await request("/")).text(); const asset = html.match(/src="(\/assets\/[^\"]+)"/)[1]; assert.equal((await request(asset)).status, 200); assert.equal(docker(["exec", name, "id", "-u"]), unraid ? "99" : "1000"); if (unraid) assert.equal(docker(["exec", name, "id", "-g"]), "100"); docker(["rm", "-f", name]); await start(); // Session and journal both survive a full container replacement, as during an update. const response = await request("/api/records", undefined, cookie); assert.equal(response.status, 200); assert.deepEqual((await response.json()).records, [record]); console.log( `PASS (${unraid ? "Unraid 99:100" : "default 1000"}): non-root container, production assets, authentication, read-only root, persistent volume and sessions after container recreation.`, ); } finally { try { docker(["rm", "-f", name]); } catch {} try { docker(["volume", "rm", volume]); } catch {} }