first commit
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m4s

This commit is contained in:
Elijah 2026-10-20 19:04:12 -07:00
commit 6fc0a01c56
51 changed files with 11319 additions and 0 deletions

29
scripts/build-sw.js Normal file
View file

@ -0,0 +1,29 @@
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
import { createHash } from "node:crypto";
const assets = readdirSync("dist/assets").map((name) => "/assets/" + name);
const shell = [
"/",
"/index.html",
"/icon.svg",
"/manifest.webmanifest",
"/icons/apple-touch-icon.png",
"/icons/icon-192.png",
"/icons/icon-512.png",
"/icons/maskable-512.png",
...assets,
];
const digest = createHash("sha256");
for (const path of shell)
digest.update(readFileSync(path === "/" ? "dist/index.html" : "dist" + path));
const hash = digest.digest("hex").slice(0, 12);
writeFileSync(
"dist/sw.js",
`const CACHE='calio-${hash}';const SHELL=${JSON.stringify(shell)};
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(SHELL))));
self.addEventListener('message',event=>{if(event.data==='ACTIVATE')self.skipWaiting()});
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(key=>key.startsWith('calio-')&&key!==CACHE).map(key=>caches.delete(key)))).then(()=>self.clients.claim())));
self.addEventListener('fetch',event=>{const url=new URL(event.request.url);if(event.request.method!=='GET'||url.origin!==self.location.origin||url.pathname.startsWith('/api/'))return;
if(event.request.mode==='navigate'){event.respondWith(caches.open(CACHE).then(cache=>cache.match('/index.html')).then(cached=>cached||fetch(event.request)));return;}
if(SHELL.includes(url.pathname))event.respondWith(caches.open(CACHE).then(cache=>cache.match(event.request)).then(cached=>cached||fetch(event.request)));
});`,
);

157
scripts/container-smoke.js Normal file
View file

@ -0,0 +1,157 @@
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 {}
}

View file

@ -0,0 +1,22 @@
Add-Type -AssemblyName System.Drawing
$iconRoot = Join-Path $PSScriptRoot '../public/icons'
New-Item -ItemType Directory -Force -Path $iconRoot | Out-Null
foreach ($iconSpec in @(@('icon-192.png',192), @('icon-512.png',512), @('maskable-512.png',512), @('apple-touch-icon.png',180))) {
$iconSize = [int]$iconSpec[1]
$bitmap = New-Object System.Drawing.Bitmap($iconSize,$iconSize)
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
$graphics.ScaleTransform($iconSize / 192.0, $iconSize / 192.0)
$graphics.Clear([System.Drawing.ColorTranslator]::FromHtml('#8391ed'))
$cream = New-Object System.Drawing.SolidBrush([System.Drawing.ColorTranslator]::FromHtml('#f5f5ef'))
$ringPen = New-Object System.Drawing.Pen($cream,8)
$graphics.DrawEllipse($ringPen,48,54,96,96)
foreach ($point in @(@(72,112),@(95,122),@(118,112),@(96,99))) { $graphics.FillEllipse($cream,($point[0]-8),($point[1]-8),16,16) }
$leaf = New-Object System.Drawing.Drawing2D.GraphicsPath
$leaf.AddBezier(96,50,94,27,119,26,120,27)
$leaf.AddBezier(120,27,120,44,105,51,96,50)
$green = New-Object System.Drawing.SolidBrush([System.Drawing.ColorTranslator]::FromHtml('#cad1ff'))
$graphics.FillPath($green,$leaf)
$bitmap.Save((Join-Path $iconRoot $iconSpec[0]),[System.Drawing.Imaging.ImageFormat]::Png)
$graphics.Dispose(); $bitmap.Dispose(); $cream.Dispose(); $ringPen.Dispose(); $leaf.Dispose(); $green.Dispose()
}

10
scripts/password.js Normal file
View file

@ -0,0 +1,10 @@
import { hashPassword } from "../server/auth.js";
// Read from stdin so passwords never need to appear in shell arguments.
let input = "";
for await (const chunk of process.stdin) input += chunk;
const password = input.trimEnd();
if (password.length < 12)
throw new Error(
"Use at least 12 characters. Pipe the password through stdin.",
);
console.log(hashPassword(password));

108
scripts/publish-image.js Normal file
View file

@ -0,0 +1,108 @@
import { spawnSync, execFileSync } from "node:child_process";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
export function publicationPlan(env) {
if (!["push", "workflow_dispatch"].includes(env.CI_EVENT)) return null;
const repository = (env.REPOSITORY || "").toLowerCase();
if (!/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/.test(repository))
throw new Error("Invalid REPOSITORY");
const sha = env.COMMIT_SHA || "";
if (!/^[a-f0-9]{40}$/.test(sha))
throw new Error("COMMIT_SHA must be a full Git commit ID");
const image = "git.elijahkuntz.com/" + repository;
const tags = [sha];
const ref = env.TARGET_REF || "";
const latest = ref === "refs/heads/" + (env.MAIN_BRANCH || "main");
const version = ref.startsWith("refs/tags/")
? ref.slice("refs/tags/".length)
: "";
if (/^v[\w][\w.-]{0,126}$/.test(version)) tags.push(version.toLowerCase());
return { registry: "git.elijahkuntz.com", image, tags, latest, sha };
}
export function publishImage(env = process.env, dryRun = false) {
const plan = publicationPlan(env);
if (!plan) {
console.log("This event verifies the image without publishing.");
return;
}
if (dryRun) {
console.log(
JSON.stringify(
{ ...plan, latestRequiresCurrentBranchHead: plan.latest },
null,
2,
),
);
return;
}
if (!env.FORGEJO_PAT)
throw new Error(
"Add FORGEJO_PAT with write:package permission under Calio Settings → Actions → Secrets, then rerun this workflow.",
);
if (!env.REGISTRY_USERNAME)
throw new Error("REGISTRY_USERNAME must identify the token owner");
const configDir = mkdtempSync(join(tmpdir(), "calio-registry-"));
const childEnv = { ...process.env, ...env, DOCKER_CONFIG: configDir };
const sourceImage = env.SOURCE_IMAGE || "calio:ci";
const docker = (args, input) => {
const result = spawnSync("docker", args, {
env: childEnv,
input,
stdio: [input === undefined ? "ignore" : "pipe", "inherit", "inherit"],
});
if (result.error) throw result.error;
if (result.status !== 0) throw new Error(`docker ${args[0]} failed`);
};
try {
docker(
[
"login",
plan.registry,
"--username",
env.REGISTRY_USERNAME,
"--password-stdin",
],
env.FORGEJO_PAT,
);
for (const tag of plan.tags) {
const target = `${plan.image}:${tag}`;
docker(["tag", sourceImage, target]);
docker(["push", target]);
}
if (plan.latest) {
const head = execFileSync(
"git",
["ls-remote", "origin", `refs/heads/${env.MAIN_BRANCH || "main"}`],
{ encoding: "utf8" },
)
.trim()
.split(/\s+/)[0];
if (head !== plan.sha) {
console.log(
"Main has a newer commit; published the commit tag and left latest unchanged.",
);
return;
}
docker(["tag", sourceImage, `${plan.image}:latest`]);
docker(["push", `${plan.image}:latest`]);
}
} finally {
rmSync(configDir, { recursive: true, force: true });
}
}
if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
try {
publishImage(process.env, process.argv.includes("--dry-run"));
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}