import { afterAll, beforeAll, describe, expect, setSystemTime, test } from "bun:test";
import type { Hono } from "hono";
import { createApp } from "../src/server/app.ts";
import { Browser, type Instance, instance, PASSWORD } from "./browser.ts";
import { makeRepos, writeRelease } from "./fixture.ts";
// Every admin route with sample parameters, from the app's own route table.
function adminRoutes(app: Hono): { method: string; path: string }[] {
return app.routes
.filter((route) => route.path.startsWith("/admin") && route.method !== "ALL")
.map((route) => ({
method: route.method,
path: route.path
.replace(":repo", "app")
.replace(/:n\{[^}]+\}/, "1")
.replace(/:version(\{[^}]+\})?/, "1.0.0"),
}));
}
describe("admin sign-in, sessions and the guard", () => {
let inst: Instance;
let clock = Date.parse("2026-09-26T12:00:00Z");
const tick = (seconds: number) => {
clock += seconds * 1000;
setSystemTime(new Date(clock));
};
beforeAll(async () => {
setSystemTime(new Date(clock));
const repos = await makeRepos(["app"]);
await writeRelease(repos.bucketDir, "app", {
version: "1.0.0",
save: repos.saves.app as string,
files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],
});
inst = await instance(repos.bucketDir);
});
afterAll(() => setSystemTime());
test("the sign-in page sets a strict double-submit cookie and is never cached", async () => {
const response = await new Browser(inst.app).request("/sign-in");
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(response.headers.get("referrer-policy")).toBe("same-origin");
const cookie = response.headers.getSetCookie()[0] ?? "";
expect(cookie).toMatch(
/^kepr_sign_in=[0-9a-f]{64}; Path=\/; HttpOnly; Secure; SameSite=Strict$/,
);
});
test("the right password sets a 30-day strict session and opens the console", async () => {
const browser = new Browser(inst.app);
await browser.get("/sign-in");
const response = await browser.post("/sign-in", { password: PASSWORD });
expect(response.status).toBe(303);
expect(response.headers.get("location")).toBe("/admin");
const cookie = response.headers.getSetCookie().find((c) => c.startsWith("kepr_session="));
expect(cookie).toMatch(
/^kepr_session=[0-9a-f]{64}; Max-Age=2592000; Path=\/; HttpOnly; Secure; SameSite=Strict$/,
);
// Only the token's hash is stored.
const token = browser.cookies.get("kepr_session") ?? "";
const stored = inst.kepr
.query<{ token_hash: string }, []>("SELECT token_hash FROM sessions")
.all();
expect(stored.some((row) => row.token_hash === token)).toBe(false);
const admin = await browser.get("/admin");
expect(admin.status).toBe(200);
expect(admin.headers.get("cache-control")).toBe("no-store");
const text = await admin.text();
// As the sync recorded it: the console never waits on the bucket.
expect(text).toMatch(/Bucket read by the sync (just now|\d+ \w+ ago): 1 repo\./);
expect(text).toContain("format ok");
// A repo gone from the bucket keeps its row, but the last listing didn't find it.
inst.kepr.query("INSERT INTO repos (name) VALUES ('gone')").run();
expect(await (await browser.get("/admin")).text()).toMatch(/: 1 repo\./);
inst.kepr.query("DELETE FROM repos WHERE name = 'gone'").run();
inst.kepr.query("INSERT INTO settings (key, value) VALUES ('bucket_error', 'timed out')").run();
expect(await (await browser.get("/admin")).text()).toContain(
"Bucket unreachable at the last sync: timed out",
);
inst.kepr.query("DELETE FROM settings WHERE key = 'bucket_error'").run();
expect(text).toMatch(/Running kepr 3\.\d+\.\d+: [\d,]+ lines of TypeScript/);
expect(text).toContain('href="/admin?section=backups"');
const backupPage = await (await browser.get("/admin?section=backups")).text();
expect(backupPage).toContain("
backups
");
expect(backupPage).toContain("Sessions and bucket credentials are not included");
expect(backupPage).not.toContain("Bucket read by the sync");
});
test("a wrong password, a foreign origin or a missing sign-in cookie is refused", async () => {
const browser = new Browser(inst.app, "198.51.100.1");
expect((await browser.signIn("wrong")).status).toBe(401);
expect(browser.cookies.has("kepr_session")).toBe(false);
await browser.get("/sign-in");
expect(
(await browser.post("/sign-in", { password: PASSWORD }, "https://evil.example")).status,
).toBe(403);
expect((await browser.post("/sign-in", { password: PASSWORD }, "")).status).toBe(403);
browser.cookies.delete("kepr_sign_in");
expect((await browser.post("/sign-in", { password: PASSWORD })).status).toBe(403);
});
test("plain http is the site's origin only when the domain is localhost", async () => {
const plain = new Browser(inst.app, "198.51.100.4");
await plain.get("/sign-in");
const http = "http://kepr.example";
expect((await plain.post("/sign-in", { password: PASSWORD }, http)).status).toBe(403);
const local = createApp({ ...inst.config, domain: "localhost:3000" }, inst.kepr);
const browser = new Browser(local, "198.51.100.4");
const origin = "http://localhost:3000";
await browser.get("/sign-in");
expect((await browser.post("/sign-in", { password: PASSWORD }, origin)).status).toBe(303);
await browser.get("/admin");
expect((await browser.post("/admin/sync", {}, origin)).status).toBe(303);
expect((await browser.post("/admin/sync", {}, "http://localhost:4000")).status).toBe(403);
});
test("five failures lock one address out for 15 minutes, even with the right password", async () => {
const browser = new Browser(inst.app, "198.51.100.2");
for (let i = 0; i < 5; i++) expect((await browser.signIn("nope")).status).toBe(401);
const locked = await browser.signIn();
expect(locked.status).toBe(429);
expect(locked.headers.get("retry-after")).toBe("900");
expect((await new Browser(inst.app, "198.51.100.3").signIn()).status).toBe(303);
tick(901);
expect((await browser.signIn()).status).toBe(303);
});
test("failures are limited per address, with no global cap", async () => {
for (let i = 0; i < 30; i++) {
expect((await new Browser(inst.app, `192.0.2.${i}`).signIn("nope")).status).toBe(401);
}
expect((await new Browser(inst.app, "192.0.2.200").signIn()).status).toBe(303);
});
test("every admin route: signed out is 401; a post needs the origin and the form token", async () => {
const routes = adminRoutes(inst.app);
expect(routes.length).toBeGreaterThan(1);
const stranger = new Browser(inst.app);
for (const { method, path } of routes) {
const response =
method === "GET" ? await stranger.get(path) : await stranger.post(path, { form: "x" });
expect(`${method} ${path} ${response.status}`).toBe(`${method} ${path} 401`);
}
const browser = new Browser(inst.app);
await browser.signIn();
for (const { path } of routes.filter((route) => route.method === "POST")) {
const foreign = await browser.post(path, {}, "https://evil.example");
expect(`${path} ${foreign.status}`).toBe(`${path} 403`);
const bare = await browser.post(path, {}, "");
expect(`${path} ${bare.status}`).toBe(`${path} 403`);
const tokenless = await browser.post(path, { form: "" });
expect(`${path} ${tokenless.status}`).toBe(`${path} 403`);
const other = new Browser(inst.app);
await other.signIn();
const foreignToken = await browser.post(path, { form: other.form });
expect(`${path} ${foreignToken.status}`).toBe(`${path} 403`);
}
});
test("a session expires after 30 days", async () => {
const browser = new Browser(inst.app);
await browser.signIn();
tick(30 * 86400 - 10);
expect((await browser.get("/admin")).status).toBe(200);
tick(11);
expect((await browser.get("/admin")).status).toBe(401);
});
test("signing out revokes the session on the server, not just the cookie", async () => {
const browser = new Browser(inst.app);
await browser.signIn();
const token = browser.cookies.get("kepr_session") ?? "";
const out = await browser.post("/admin/sign-out", {});
expect(out.status).toBe(303);
expect(browser.cookies.has("kepr_session")).toBe(false);
browser.cookies.set("kepr_session", token);
expect((await browser.get("/admin")).status).toBe(401);
});
});