Files
loki/scripts/test/lib/session-cookie.mjs
CatoandClaude 0096d86a4c feat(ship): done means seen — ship reports, and Loki records how Build next is used (#1150)
"Build next" (#1141) was reported to the operator as a merge notice: merged
at 21:14, "should go live on its own", "I haven't confirmed that, or tried
the screen in a browser myself", open /loki and tap a chip. Read on a phone.
No link, no picture, no statement of what was checked — every rule this
repo already states ("confirm the commit is LIVE, not just merged"; the
fleet brief's "done means merged, deployed and checked live") skipped,
because checking took tooling nobody had wired together.

Ship report (`pnpm run ship:report -- /route --focus '<selector>'`):
- confirms the running site's build commit contains the shipped one
  (/api/health `commit`, with `--wait` to sit out the deploy), never a guess
  from a timestamp
- screenshots the real deployed page at 390 and 1440, crops the built
  section, counts console errors and 5xx during load
- writes REPORT.md: live URL first, screenshots, what was and was NOT
  checked; exits non-zero while the build is not live or the section is
  missing
- session auth shared with the responsive audit in
  scripts/test/lib/session-cookie.mjs (extracted, not duplicated)

The contract — docs/development/ship-report.md — keeps the message it
replaces, and the fleet brief now tells every dispatched agent to report
the live URL first, a screenshot, and what was verified.

After it ships, Loki watches whether it is used: operator_usage_events
records each show, tap and rotate of Build next (surfaces and actions SSOT
in src/config/usage-surfaces.ts; /api/usage refuses anything else; target
is an id, never prose). A pure summariser turns the rows into one line per
surface — shown, tapped, kinds offered and never taken — and a `usage`
retrieval source hands it to Loki: "how am I using Build next?" leads with
it, and every "what should I build?" reads it before recommending, with a
prompt line to say when a surface is shown and never used and propose the
one change.

Tests: scripts/test/usage-summary.ts (registry refuses unlisted pairs,
never-shown surface reported, window honoured, planner leads with usage
when asked about use); retrieval-plan, telemetry-freshness, fleet-brief and
account-deletion gates extended or passing as-is.


Claude-Session: https://claude.ai/code/session_016T1Vm7uYyhpgUxbD3xXro9

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-11 15:21:48 -07:00

86 lines
2.9 KiB
JavaScript

/**
* One session for every headless check that drives the AUTHENTICATED app:
* the responsive audit and the ship report. The cookie name follows the
* scheme (Auth.js prefixes it with __Secure- on https), and the token comes
* from the environment or is minted from an explicitly supplied Postgres URL.
*
* Resolution order:
* LOKI_SESSION_TOKEN — set it and nothing else is needed
* AUDIT_DATABASE_URL — mints a JWT itself (scripts/db-tunnel.sh prints
* the URL for a firewalled Postgres over SSH)
* Deliberately NOT reusing print-session-token.ts: that resolves a DIRECT box
* connection from .env.hetzner.local, which is exactly what is unreachable
* from a sandboxed or CI runner.
*/
export function sessionCookieName(base) {
return base.startsWith("https://") ? "__Secure-authjs.session-token" : "authjs.session-token";
}
/** A session token for `base`, or null when nothing can supply one. */
export async function mintSessionToken(base) {
const fromEnv = process.env.LOKI_SESSION_TOKEN?.trim();
if (fromEnv) return fromEnv;
const dbUrl = process.env.AUDIT_DATABASE_URL?.trim();
const secret = process.env.AUTH_SECRET?.trim();
if (!dbUrl || !secret) return null;
const postgres = (await import("postgres")).default;
const sql = postgres(dbUrl, { max: 1, ssl: false });
try {
const rows = await sql`
SELECT id, email, name, username, onboarded_at
FROM users
WHERE is_default = true OR email IS NOT NULL
ORDER BY is_default DESC, created_at ASC
LIMIT 1
`;
const u = rows[0];
if (!u?.id) return null;
const { encode } = await import("@auth/core/jwt");
return await encode({
token: {
id: u.id,
email: u.email,
name: u.name,
username: u.username,
onboardedAt: u.onboarded_at,
onboardingComplete: Boolean(u.username && u.onboarded_at),
sub: u.id,
},
secret,
salt: sessionCookieName(base),
});
} finally {
await sql.end({ timeout: 5 }).catch(() => undefined);
}
}
/**
* The cookies a browser context needs: the session (only when there is one —
* a cookie with an undefined value is not "no cookie", it is a malformed one
* Playwright rejects) and, when LOKI_PRIVATE_ZONE_COOKIE is set, the
* private-zone unlock (scripts/test/print-private-zone-cookie.ts).
*/
export function sessionCookies(base, token) {
const domain = new URL(base).hostname;
const secure = base.startsWith("https://");
const cookies = token
? [{ name: sessionCookieName(base), value: token, domain, path: "/", httpOnly: true, secure }]
: [];
const pz = process.env.LOKI_PRIVATE_ZONE_COOKIE?.trim();
const pzEq = pz ? pz.indexOf("=") : -1;
if (pzEq > 0) {
cookies.push({
name: pz.slice(0, pzEq),
value: pz.slice(pzEq + 1),
domain,
path: "/",
httpOnly: true,
secure,
});
}
return cookies;
}