import { createHmac } from "node:crypto"; import { ensureSetupToken, matchesSetupToken, removeSetupToken, setupTokenPath, validNewPassword } from "./setup"; import type { FastifyInstance } from "fastify"; import { readPasswordHash, verifyPassword, setPassword } from "./credentials"; import { loadSessionSecret, signSession, verifySession, rotateSessionSecret } from "./session"; export interface AuthOptions { dataDir: string; sessionMaxAgeSeconds?: number; forwardAuth?: { header: string; trustedProxyIps: string[] }; /** Failed attempts permitted per IP per window. */ maxAttempts?: number; rateWindowMs?: number; } const normalizeIp = (ip: string) => ip.replace(/^::ffff:/, ""); export async function registerAuth(app: FastifyInstance, options: AuthOptions): Promise { let secret = loadSessionSecret(options.dataDir); if (!await readPasswordHash(options.dataDir)) { await ensureSetupToken(options.dataDir); app.log.warn(`Set up ShellBook in the browser; read the one-time token at ${setupTokenPath(options.dataDir)}`); } else await removeSetupToken(options.dataDir); // Binding to the persisted hash also revokes sessions after CLI password changes. const sessionKey = async () => createHmac("sha256", secret).update(await readPasswordHash(options.dataDir) ?? "unconfigured").digest(); let mutation: Promise = Promise.resolve(); const exclusive = (action: () => Promise): Promise => { const next = mutation.then(action); mutation = next.catch(() => {}); return next; }; const maxAge = options.sessionMaxAgeSeconds ?? 30 * 86400; if (!Number.isSafeInteger(maxAge) || maxAge <= 0) throw new Error("Invalid session lifetime"); const failures = new Map(); const cookie = (value: string, secure: boolean, age: number) => `shellbook_session=${value}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${age}${secure ? "; Secure" : ""}`; app.addHook("onRequest", async (request, reply) => { const path = request.url.split("?")[0]!; if (!(path === "/api" || path.startsWith("/api/"))) return; // Also protect cookie-bearing WebSocket upgrades against cross-site requests. const origin = request.headers.origin; if (origin) { try { if (new URL(origin).host !== request.headers.host) return reply.code(403).send({ error: "Origin rejected" }); } catch { return reply.code(403).send({ error: "Origin rejected" }); } } if (path === "/api/health" || path === "/api/auth/login" || path === "/api/auth/setup") return; const forward = options.forwardAuth; const peer = normalizeIp(request.raw.socket?.remoteAddress ?? ""); if (forward && forward.trustedProxyIps.some(ip => normalizeIp(ip) === peer)) { const user = request.headers[forward.header.toLowerCase()]; if (typeof user === "string" && user.trim()) return; } const token = request.headers.cookie?.split(";").map(part => part.trim()).find(part => part.startsWith("shellbook_session="))?.slice("shellbook_session=".length); if (!token || !verifySession(await sessionKey(), token)) return reply.code(401).send({ error: "Authentication required" }); }); function reserveAttempt(ip: string, reply: import("fastify").FastifyReply) { const now = Date.now(); for (const [key, value] of failures) if (value.until <= now) failures.delete(key); const entry = failures.get(ip); if ((entry?.count ?? 0) >= (options.maxAttempts ?? 5) || (!entry && failures.size >= 10000)) { return reply.header("Retry-After", String(Math.max(1, Math.ceil(((entry?.until ?? now + 60000) - now) / 1000)))).code(429).send({ error: "Try again later" }); } // Reserve before scrypt awaits, so parallel attempts cannot bypass the limit. failures.set(ip, { count: (entry?.count ?? 0) + 1, until: entry?.until ?? now + (options.rateWindowMs ?? 60000) }); return undefined; } const freshCookie = async (secure: boolean) => cookie(signSession(await sessionKey(), Date.now() + maxAge * 1000), secure, maxAge); app.get("/api/auth/setup", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ required: !await readPasswordHash(options.dataDir) })); app.post("/api/auth/setup", { bodyLimit: 16384 }, async (request, reply) => exclusive(async () => { if (await readPasswordHash(options.dataDir)) return reply.code(409).send({ error: "Already configured" }); const limited = reserveAttempt(request.ip, reply); if (limited) return limited; const body = request.body as { token?: unknown; newPassword?: unknown; confirmPassword?: unknown } | null; if (!await matchesSetupToken(options.dataDir, body?.token)) return reply.code(401).send({ error: "Invalid setup token" }); if (!validNewPassword(body?.newPassword) || body.newPassword !== body.confirmPassword) return reply.code(400).send({ error: "Passwords must match and contain at least 12 characters (maximum 4096 bytes)" }); await setPassword(options.dataDir, body.newPassword); await removeSetupToken(options.dataDir); failures.delete(request.ip); return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send(); })); app.post("/api/settings/password", { bodyLimit: 16384 }, async (request, reply) => exclusive(async () => { const limited = reserveAttempt(request.ip, reply); if (limited) return limited; const body = request.body as { currentPassword?: unknown; newPassword?: unknown; confirmPassword?: unknown } | null; const hash = await readPasswordHash(options.dataDir); if (typeof body?.currentPassword !== "string" || !hash || !await verifyPassword(body.currentPassword, hash)) return reply.code(401).send({ error: "Invalid current password" }); if (!validNewPassword(body.newPassword) || body.newPassword !== body.confirmPassword) return reply.code(400).send({ error: "Passwords must match and contain at least 12 characters (maximum 4096 bytes)" }); await setPassword(options.dataDir, body.newPassword); app.websocketServer?.clients.forEach(socket => socket.close(1008, "Sessions revoked")); failures.delete(request.ip); return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send(); })); app.post("/api/settings/sessions/revoke", async (request, reply) => exclusive(async () => { secret = rotateSessionSecret(options.dataDir); app.websocketServer?.clients.forEach(socket => socket.close(1008, "Sessions revoked")); return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send(); })); app.get("/api/settings/session", async () => ({ lifetimeSeconds: maxAge })); app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => exclusive(async () => { const limited = reserveAttempt(request.ip, reply); if (limited) return limited; const now = Date.now(); const password = (request.body as { password?: unknown } | null)?.password; const hash = await readPasswordHash(options.dataDir); if (typeof password !== "string" || !hash || !await verifyPassword(password, hash)) return reply.code(401).send({ error: "Invalid credentials" }); failures.delete(request.ip); return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(await sessionKey(), now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send(); })); app.post("/api/auth/logout", async (request, reply) => reply.header("Set-Cookie", cookie("", request.protocol === "https", 0)).code(204).send()); app.get("/api/auth/me", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ authenticated: true })); }