// Shared auth helpers for the Nitro server (the deployed Bun server). Single-user,
// shared-password gate: the user logs in with PUNKTFUNK_UI_PASSWORD, which sets a SEALED
// (h3 useSession — AES-GCM) cookie; every request is gated by server/middleware/auth.ts.
//
// The management token never reaches the browser: server/routes/api/[...].ts injects it
// server-side when proxying to the loopback management API.
import {
	createHash,
	timingSafeEqual as nodeTimingSafeEqual,
} from "node:crypto";
import type { SessionConfig } from "h3";

export const SESSION_NAME = "pf_session";

/** The login password. Empty string ⇒ auth is MISCONFIGURED (the gate fails closed). */
export function uiPassword(): string {
	return process.env.PUNKTFUNK_UI_PASSWORD ?? "";
}

/** The management API the proxy forwards to (loopback by default — never LAN-exposed). It serves
 * HTTPS with the host's self-signed identity cert, so the deployment also sets
 * NODE_TLS_REJECT_UNAUTHORIZED=0 for the (loopback-only) proxy fetch — see .env.example. */
export function mgmtUrl(): string {
	return process.env.PUNKTFUNK_MGMT_URL ?? "https://127.0.0.1:47990";
}

/** Bearer token for the management API, injected server-side. */
export function mgmtToken(): string {
	return process.env.PUNKTFUNK_MGMT_TOKEN ?? "";
}

/** Whether `url`'s host is a loopback address — the only place the proxy relaxes TLS verification
 * for the host's self-signed cert. IPv4 127.0.0.0/8, IPv6 ::1, and the `localhost` name. */
export function isLoopbackUrl(url: string): boolean {
	let host: string;
	try {
		host = new URL(url).hostname;
	} catch {
		return false;
	}
	// URL wraps IPv6 in brackets in .host but strips them in .hostname; normalize anyway.
	const h = host.replace(/^\[|\]$/g, "").toLowerCase();
	if (h === "localhost" || h === "::1") return true;
	return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
}

/**
 * The cookie-sealing key for h3 `useSession` (must be ≥ 32 chars). Precedence:
 *   1. PUNKTFUNK_UI_SECRET — explicit operator override.
 *   2. Derived from the MANAGEMENT TOKEN (a 32-byte / 64-hex CSPRNG value) — the packaged deployment
 *      always has one, so the seal key is high-entropy without any extra config.
 *   3. Only as a last resort (dev/local with no token) derive from the password.
 *
 * Why not (2)→password by default: the password is low-entropy (a human picks it), so a key DERIVED
 * from it turns any captured session cookie into an OFFLINE dictionary oracle — an attacker unseals
 * candidate cookies locally, no server round-trips, so the login throttle can't help. The mgmt token
 * is unguessable, so a cookie sealed under it leaks nothing about the password. (Deriving from the
 * token instead of the password also means changing the password no longer silently invalidates
 * sessions; rotating the mgmt token does — the correct, security-relevant trigger.)
 */
export function sessionConfig(): SessionConfig {
	const explicit = process.env.PUNKTFUNK_UI_SECRET;
	const token = mgmtToken();
	let secret: string;
	if (explicit && explicit.length >= 32) {
		secret = explicit;
	} else if (token) {
		// High-entropy source: the CSPRNG mgmt token. Hash it (never use the raw admin token as the
		// seal key) with a distinct label so the two uses can't be conflated.
		secret = createHash("sha256")
			.update(`punktfunk-session-v1:token:${token}`)
			.digest("hex");
	} else {
		// Last resort (no token configured — dev/local only). No worse than before; a real deployment
		// always has a token and never reaches here.
		secret = createHash("sha256")
			.update(`punktfunk-session-v1:${uiPassword()}`)
			.digest("hex");
	}
	return {
		name: SESSION_NAME,
		// h3's `useSession` calls this seal key `password` (it's the iron/AES-GCM key, not the login
		// password — see the derivation above).
		password: secret,
		// Bounds a stolen/replayed cookie's lifetime (sets the cookie Max-Age AND the iron
		// seal TTL). 7 days for a single-user console.
		maxAge: 60 * 60 * 24 * 7,
		cookie: {
			httpOnly: true,
			sameSite: "lax",
			path: "/",
			// h3 defaults Secure to true, which browsers DROP over plain http:// (so login
			// silently fails on a LAN HTTP server). Only mark Secure when actually behind TLS
			// (set PUNKTFUNK_UI_SECURE=1 / =true then).
			secure: /^(1|true)$/i.test(process.env.PUNKTFUNK_UI_SECURE ?? ""),
		},
	};
}

/** Constant-time string comparison (avoids leaking the password via timing). */
export function timingSafeEqual(a: string, b: string): boolean {
	const ab = Buffer.from(a);
	const bb = Buffer.from(b);
	if (ab.length !== bb.length) return false;
	return nodeTimingSafeEqual(ab, bb);
}

/** Paths reachable WITHOUT a session: the login page, the auth endpoints, and the build's
 * static assets (the login page needs its own CSS/JS, all of which live under /assets/).
 * Everything else — crucially ALL of /api — is gated.
 *
 * Note: do NOT allowlist by file extension. The client assets are all under /assets/, and a
 * generic `*.json` allowlist would expose `/api/v1/openapi.json` (and any future
 * `.json`/`.png` management route) through the proxy unauthenticated. */
export function isPublicPath(pathname: string): boolean {
	if (pathname === "/api" || pathname.startsWith("/api/")) return false; // always gated
	if (pathname === "/login") return true;
	if (pathname.startsWith("/_auth/")) return true;
	if (pathname.startsWith("/assets/")) return true;
	if (pathname === "/favicon.ico" || pathname === "/robots.txt") return true;
	return false;
}

/** Validate a post-login redirect target: a same-origin path only. Resolves `next` against a
 * sentinel origin and keeps it only if it stays same-origin — rejecting absolute (`https://evil.com`),
 * protocol-relative (`//evil.com`) AND backslash/tab variants (`/\evil.com`, which the WHATWG URL
 * parser folds to `//evil.com`) that a plain `startsWith("//")` guard lets through. */
export function safeNextPath(next: string | undefined): string {
	if (!next) return "/";
	try {
		const base = "http://pf.invalid";
		const u = new URL(next, base);
		return u.origin === base ? u.pathname + u.search + u.hash : "/";
	} catch {
		return "/";
	}
}

export interface SessionData {
	authenticated?: boolean;
}
