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
+29
View File
@@ -0,0 +1,29 @@
import { randomBytes, scrypt as derive, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { join } from "node:path";
const scrypt = promisify(derive);
export async function hashPassword(password: string): Promise<string> {
if (!password || Buffer.byteLength(password) > 4096) throw new Error("Password must contain 1–4096 bytes");
const salt = randomBytes(32).toString("hex");
const hash = await scrypt(password, salt, 64) as Buffer;
return `scrypt:${salt}:${hash.toString("hex")}`;
}
export async function verifyPassword(password: string, encoded: string): Promise<boolean> {
if (!password || Buffer.byteLength(password) > 4096 || !/^scrypt:[a-f0-9]{64}:[a-f0-9]{128}$/.test(encoded)) return false;
const [, salt, hash] = encoded.split(":");
const actual = await scrypt(password, salt!, 64) as Buffer;
return timingSafeEqual(actual, Buffer.from(hash!, "hex"));
}
export async function readPasswordHash(dataDir: string): Promise<string | undefined> {
try { return (JSON.parse(await readFile(join(dataDir, "auth.json"), "utf8")) as { passwordHash: string }).passwordHash; }
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
}
export async function setPassword(dataDir: string, password: string): Promise<void> {
const passwordHash = await hashPassword(password);
await mkdir(dataDir, { recursive: true, mode: 0o700 });
const temp = join(dataDir, `auth.${randomBytes(8).toString("hex")}.tmp`);
await writeFile(temp, JSON.stringify({ passwordHash }) + "\n", { mode: 0o600, flag: "wx" });
await rename(temp, join(dataDir, "auth.json"));
}
+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 }));
}
+24
View File
@@ -0,0 +1,24 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
import { join } from "node:path";
export function loadSessionSecret(dataDir: string): Buffer {
mkdirSync(dataDir, { recursive: true, mode: 0o700 });
const path = join(dataDir, "session-secret");
try { writeFileSync(path, randomBytes(32), { flag: "wx", mode: 0o600 }); }
catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
const secret = readFileSync(path);
if (secret.length !== 32) throw new Error("Invalid session-secret (expected 32 bytes)");
chmodSync(path, 0o600);
return secret;
}
export function signSession(secret: Buffer, expiresAt: number): string {
const payload = String(expiresAt);
return `${payload}.${createHmac("sha256", secret).update(payload).digest("base64url")}`;
}
export function verifySession(secret: Buffer, cookie: string, now = Date.now()): boolean {
if (!/^\d{1,16}\.[A-Za-z0-9_-]{43}$/.test(cookie)) return false;
const [payload, mac] = cookie.split(".");
const expected = signSession(secret, Number(payload)).split(".")[1]!;
return Number(payload) > now && timingSafeEqual(Buffer.from(mac!), Buffer.from(expected));
}