feat(settings): add browser setup and administration (#10)

This commit is contained in:
Florian Schmidt
2026-11-16 10:15:04 +01:00
parent 4fe7e4e376
commit 02a22bef40
20 changed files with 939 additions and 24 deletions
+58 -10
View File
@@ -1,6 +1,8 @@
import { createHmac } from "node:crypto";
import { ensureSetupToken, matchesSetupToken, removeSetupToken, setupTokenPath, validNewPassword } from "./setup";
import type { FastifyInstance } from "fastify";
import { readPasswordHash, verifyPassword } from "./credentials";
import { loadSessionSecret, signSession, verifySession } from "./session";
import { readPasswordHash, verifyPassword, setPassword } from "./credentials";
import { loadSessionSecret, signSession, verifySession, rotateSessionSecret } from "./session";
export interface AuthOptions {
dataDir: string;
@@ -12,7 +14,17 @@ export interface AuthOptions {
}
const normalizeIp = (ip: string) => ip.replace(/^::ffff:/, "");
export async function registerAuth(app: FastifyInstance, options: AuthOptions): Promise<void> {
const secret = loadSessionSecret(options.dataDir);
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<unknown> = Promise.resolve();
const exclusive = <T,>(action: () => Promise<T>): Promise<T> => {
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<string, { count: number; until: number }>();
@@ -27,7 +39,7 @@ export async function registerAuth(app: FastifyInstance, options: AuthOptions):
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;
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)) {
@@ -35,24 +47,60 @@ export async function registerAuth(app: FastifyInstance, options: AuthOptions):
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" });
if (!token || !verifySession(await sessionKey(), token)) return reply.code(401).send({ error: "Authentication required" });
});
app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => {
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 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) });
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(ip);
return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(secret, now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send();
});
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 }));
}