peppa/apps/web/lib/auth.ts
Асель 14916079bc PEP-5/43/47/48: usage and limits, story budgets, factory metrics, audit journal
- PEP-5: statusLine hook (cost, context, 5h/7d limit windows), transcript tokens,
  sessions.usage, usage strip over every page, runner usage, bot /status, MCP get_usage
- PEP-43: project/story budgets in settings, watchdog pause (Escape, question to the PM:
  extend x2 / remove limit / stop), start/resume guard, budget on the story card
- PEP-47: project metrics tab (cycle time, first pass, review returns, questions, runner
  hours, PM wait, limits, spend by week/agent/epic), MCP get_metrics
- PEP-48: event authors (actor columns, AsyncLocalStorage context), question_answered,
  /journal for superadmins, project journal tab, authors in the story feed
- Migration 0007_usage_audit; OpenSpec changes archived

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:52:13 +05:00

72 lines
2.9 KiB
TypeScript

import { enterActor, getUser, isUserAllowed, sign, verify, type User } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { cache } from "react";
import { db } from "./db";
export const SESSION_COOKIE = "peppa_session";
export const STATE_COOKIE = "peppa_oauth_state";
export const NEXT_COOKIE = "peppa_next";
/** eGov QR flow handle (PEP-65): httpOnly, only for /auth/egov, lives as long as the QR. */
export const EGOV_COOKIE = "peppa_egov";
/** Only same-site relative paths are allowed as a post-login destination. */
export const safeNext = (n: string | null | undefined) => (n && n.startsWith("/") && !n.startsWith("//") ? n : "/");
const SESSION_DAYS = 30;
interface SessionPayload {
uid: number;
exp: number;
}
/** Memoized per request: the layout, the page and the side panel all ask for the user. */
export const currentUser = cache(async (): Promise<User | null> => {
const p = verify<SessionPayload>((await cookies()).get(SESSION_COOKIE)?.value);
if (!p || p.exp < Date.now()) return null;
const user = await getUser(db, p.uid);
// Removed from the allowlist → the session stops working right away.
return user && (await isUserAllowed(db, user)) ? user : null;
});
/** For pages and server actions: the logged-in user, or a redirect to /login. */
export async function requireUser(): Promise<User> {
const u = await currentUser();
if (!u) redirect("/login");
return u;
}
/**
* PEP-48: marks the rest of this server action as done by `user` through the web. Synchronous
* on purpose — call it in the action body: `const user = asWebActor(await requireUser())`.
*/
export function asWebActor(user: User): User {
enterActor({ kind: "user", userId: user.id, channel: "web" });
return user;
}
export function sessionCookie(uid: number) {
const exp = Date.now() + SESSION_DAYS * 86400_000;
return {
name: SESSION_COOKIE,
value: sign({ uid, exp } satisfies SessionPayload),
options: { httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/", maxAge: SESSION_DAYS * 86400 },
};
}
export const egovCookieOptions = (maxAgeSec: number) => ({ httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/auth/egov", maxAge: maxAgeSec });
const isHttps = () => loadEnv().PEPPA_WEB_URL.startsWith("https://");
/**
* Public origin of this request. Behind Cloudflare → Traefik the proto header says http,
* so the configured PEPPA_WEB_URL wins when the host matches it.
*/
export async function publicOrigin(): Promise<string> {
const h = await headers();
const host = h.get("x-forwarded-host") ?? h.get("host") ?? "localhost:3100";
const configured = new URL(loadEnv().PEPPA_WEB_URL);
if (host === configured.host) return configured.origin;
return `${host.startsWith("localhost") || host.startsWith("127.") ? "http" : "https"}://${host}`;
}