feat(server): add persistent authentication and production build (#6)

Protect HTTP and WebSocket API routes with scrypt password login and signed persistent sessions. Restrict forwarded identity and HTTPS detection to configured proxies, and serve optional web assets with SPA fallback.

Add @fastify/static for Fastify-compatible static file handling and esbuild to bundle TypeScript core source while retaining native dependencies externally.
This commit is contained in:
Florian Schmidt
2026-11-16 00:07:18 +01:00
parent d06f4336ae
commit af331177ac
10 changed files with 817 additions and 3 deletions
+58
View File
@@ -0,0 +1,58 @@
import type { FastifyInstance } from "fastify";
import { readPasswordHash, verifyPassword } from "./credentials";
import { loadSessionSecret, signSession, verifySession } 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<void> {
const secret = loadSessionSecret(options.dataDir);
const maxAge = options.sessionMaxAgeSeconds ?? 30 * 86400;
if (!Number.isSafeInteger(maxAge) || maxAge <= 0) throw new Error("Invalid session lifetime");
const failures = new Map<string, { count: number; until: number }>();
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") 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(secret, token)) return reply.code(401).send({ error: "Authentication required" });
});
app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => {
const now = Date.now();
for (const [key, value] of failures) if (value.until <= now) failures.delete(key);
const ip = request.ip;
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) });
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(ip);
return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(secret, 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 }));
}