Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

6.8 KB
Raw Blame
/**
 * Sessions as rows in auth_sessions (auth/service.ts): the cookie carries a random token and
 * the row stores its sha256. Each property the row model is chosen for is pinned here; an
 * admin's password reset deleting a user's rows is covered with the reset route in
 * admin-users.test.ts.
 *
 * - Given a v0.2.0 database whose auth_sessions lacks `via`, a boot adds it and login works.
 * - A session survives a restart, because it is a row on disk.
 * - Logout deletes the row, and it stays deleted across a restart.
 * - Expired rows are swept on the next login.
 * - A long session slides in place: the expiry is topped up and the cookie value never changes.
 * - A short cli token expires at its hour instead of renewing into a long one.
 */
import path from "node:path";
import { describe, expect, it } from "vitest";
import { SESSION_COOKIE } from "../src/auth/middleware.js";
import { apiClient, cookieFrom, createTestApp, loginAdmin, makeTempRoot } from "./helpers.js";

const DAY_MS = 24 * 60 * 60 * 1000;
/** The session TTL test apps are built with (helpers.ts) — fixtures derive from it, not from literals. */
const TEST_SESSION_TTL_MS = 30 * DAY_MS;

describe("auth sessions", () => {
  /**
   * A v0.2.0 web.db has auth_sessions WITHOUT the `via` column, and CREATE TABLE IF NOT EXISTS
   * never adds one — so without the ensureColumn migration every login, first-login mint and
   * `penguin auth token` on an upgraded database fails "no column named via".
   */
  it("upgrades a v0.2.0 database that has auth_sessions without `via`", async () => {
    const root = await makeTempRoot();
    const p = path.join(root, "web.db");
    const sqlite = process.getBuiltinModule("node:sqlite");
    const legacy = new sqlite.DatabaseSync(p);
    legacy.exec(
      "CREATE TABLE auth_sessions (token_hash TEXT PRIMARY KEY, user_id TEXT, created_at TEXT, expires_at TEXT)",
    );
    legacy.close();

    const t = await createTestApp({ config: { root, dbPath: p } });
    try {
      const cols = (
        t.deps.db.prepare("PRAGMA table_info(auth_sessions)").all() as { name: string }[]
      ).map((c) => c.name);
      expect(cols).toContain("via");
      // And the whole login path works on it.
      const { cookie } = await loginAdmin(t.app);
      expect((await apiClient(t.app, cookie).get("/api/me")).status).toBe(200);
    } finally {
      await t.cleanup();
    }
  });

  it("survives a restart, because the session is a row on disk", async () => {
    const root = await makeTempRoot();
    const config = { root, dbPath: `${root}/web.db` };
    const t = await createTestApp({ config });
    let cookie: string;
    try {
      cookie = (await loginAdmin(t.app)).cookie;
      expect((await apiClient(t.app, cookie).get("/api/me")).status).toBe(200);
    } finally {
      await t.cleanup();
    }
    // A new process on the same database: the row is still there, so the cookie still works —
    // a restart does not sign everyone out.
    const reborn = await createTestApp({ config });
    try {
      expect((await apiClient(reborn.app, cookie).get("/api/me")).status).toBe(200);
    } finally {
      await reborn.cleanup();
    }
  });

  it("logout deletes the row, and it stays deleted across a restart", async () => {
    const root = await makeTempRoot();
    const config = { root, dbPath: `${root}/web.db` };
    const t = await createTestApp({ config });
    let cookie: string;
    try {
      cookie = (await loginAdmin(t.app)).cookie;
      await apiClient(t.app, cookie).post("/api/auth/logout");
      expect((await apiClient(t.app, cookie).get("/api/me")).status).toBe(401);
    } finally {
      await t.cleanup();
    }
    const reborn = await createTestApp({ config });
    try {
      expect((await apiClient(reborn.app, cookie).get("/api/me")).status).toBe(401);
    } finally {
      await reborn.cleanup();
    }
  });

  it("expired rows are swept on login", async () => {
    let nowMs = Date.now();
    const t = await createTestApp({ now: () => new Date(nowMs) });
    try {
      await loginAdmin(t.app);
      const rows = () =>
        Number(
          (t.deps.db.prepare("SELECT COUNT(*) AS n FROM auth_sessions").get() as { n: unknown }).n,
        );
      expect(rows()).toBe(1);
      // Past the TTL, the row is dead weight; the next login sweeps it (and adds its own).
      nowMs += TEST_SESSION_TTL_MS + DAY_MS;
      await loginAdmin(t.app);
      expect(rows()).toBe(1);
    } finally {
      await t.cleanup();
    }
  });

  it("slides a long session in place, so the cookie value never changes", async () => {
    let nowMs = Date.now();
    const t = await createTestApp({ now: () => new Date(nowMs) });
    try {
      const cookie = (await loginAdmin(t.app)).cookie;
      const token = cookie.split("=").slice(1).join("=");
      // Two days in, past the renewal threshold (29 days): the request tops up the expiry and
      // refreshes the cookie, but the token VALUE is unchanged — same session, longer life.
      nowMs += 2 * DAY_MS;
      const res = await apiClient(t.app, cookie).get("/api/me");
      expect(res.status).toBe(200);
      const refreshed = cookieFrom(res);
      expect(refreshed).toBe(`${SESSION_COOKIE}=${token}`);
      // The DB expiry moved forward to now+TTL.
      const row = t.deps.db.prepare("SELECT expires_at FROM auth_sessions LIMIT 1").get() as {
        expires_at: string;
      };
      expect(Date.parse(row.expires_at)).toBeGreaterThan(nowMs + TEST_SESSION_TTL_MS - DAY_MS);
    } finally {
      await t.cleanup();
    }
  });

  it("a short cli token expires at its hour rather than renewing", async () => {
    // A cli token spans an hour, well under the renewal window, so being used must not top it
    // up to the full term. Insert one directly (as `penguin auth token` does) and use it.
    let nowMs = Date.now();
    const t = await createTestApp({ now: () => new Date(nowMs) });
    try {
      const { createHash, randomBytes } = await import("node:crypto");
      const token = randomBytes(32).toString("base64url");
      const hash = createHash("sha256").update(token).digest("hex");
      t.deps.db
        .prepare(
          "INSERT INTO auth_sessions (token_hash, user_id, created_at, expires_at, via) VALUES (?,?,?,?,?)",
        )
        .run(
          hash,
          "admin",
          new Date(nowMs).toISOString(),
          new Date(nowMs + 60 * 60_000).toISOString(),
          "cli",
        );
      const res = await apiClient(t.app, `${SESSION_COOKIE}=${token}`).get("/api/me");
      expect(res.status).toBe(200);
      // No renewal cookie, and the expiry did not move to the full term.
      expect(res.headers.get("set-cookie")).toBeNull();
      const row = t.deps.db
        .prepare("SELECT expires_at FROM auth_sessions WHERE token_hash = ?")
        .get(hash) as { expires_at: string };
      expect(Date.parse(row.expires_at)).toBe(nowMs + 60 * 60_000);
    } finally {
      await t.cleanup();
    }
  });
});