peppa/apps/web/lib/auth.ts

83 lines
4.0 KiB
TypeScript

import { enterActor, getUiMode, isSuperadmin, sign, type User } from "@peppa/core";
import { loadEnv } from "@peppa/shared";
import { wording, type Words } from "@peppa/shared/wording";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { cache } from "react";
import { db } from "./db";
import { getLocale } from "./i18n";
import { SESSION_COOKIE, SESSION_DAYS, userFromSessionToken, type SessionPayload } from "./session-user";
export { SESSION_COOKIE };
/** 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 : "/");
/** Memoized per request: the layout, the page and the side panel all ask for the user. */
export const currentUser = cache(async (): Promise<User | null> => userFromSessionToken((await cookies()).get(SESSION_COOKIE)?.value));
/** 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 });
/** Google OAuth state (PEP-90): binds the callback to the browser that started the flow. */
export const GOOGLE_COOKIE = "peppa_google";
export const googleCookieOptions = (maxAgeSec: number) => ({ httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/auth/google", maxAge: maxAgeSec });
/** PEP-252: Access Hub sign-in state — the service's answer must come back to the browser that started it. */
export const connOAuthCookieOptions = (maxAgeSec: number) => ({ httpOnly: true, sameSite: "lax" as const, secure: isHttps(), path: "/connections/oauth", 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}`;
}
/** PEP-119: «Продакт» or «Инженер» for the current user (memoized per request). */
export const uiMode = cache(async (): Promise<"product" | "engineer"> => {
const u = await currentUser();
return u ? getUiMode(db, u.id) : "product";
});
/** PEP-123: «задача» / «стори», «агент» / «раннер» — the words of the current user's view. */
export const words = cache(async (): Promise<Words> => wording(await uiMode(), await getLocale()));
/** PEP-121: subscription names carry the login of whoever connected them — a superadmin's eyes only. */
export const subscriptionNamesVisible = cache(async (): Promise<boolean> => {
const u = await currentUser();
return u ? isSuperadmin(db, u) : false;
});