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
+5 -1
View File
@@ -5,16 +5,20 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "tsx watch src/main.ts", "dev": "tsx watch src/main.ts",
"build": "tsc -p tsconfig.json --noEmit", "build": "esbuild src/main.ts src/cli/set-password.ts --bundle --platform=node --target=node22 --format=esm --packages=external --outdir=dist --outbase=src --external:node-pty --alias:@shellbook/core=../../packages/core/src/index.ts",
"start": "node dist/main.js",
"set-password": "tsx src/cli/set-password.ts",
"typecheck": "tsc -p tsconfig.json --noEmit", "typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest run --passWithNoTests" "test": "vitest run --passWithNoTests"
}, },
"dependencies": { "dependencies": {
"@fastify/static": "^8.0.0",
"@fastify/websocket": "^11.0.1", "@fastify/websocket": "^11.0.1",
"@shellbook/core": "workspace:*", "@shellbook/core": "workspace:*",
"fastify": "^5.1.0" "fastify": "^5.1.0"
}, },
"devDependencies": { "devDependencies": {
"esbuild": "^0.24.2",
"tsx": "^4.19.2" "tsx": "^4.19.2"
} }
} }
+9 -1
View File
@@ -1,8 +1,14 @@
import Fastify, { type FastifyInstance } from "fastify"; import Fastify, { type FastifyInstance } from "fastify";
import websocket from "@fastify/websocket"; import websocket from "@fastify/websocket";
import { resolve } from "node:path";
import { registerAuth, type AuthOptions } from "./auth";
import { registerStatic } from "./static";
export interface AppOptions { export interface AppOptions {
logger?: boolean; logger?: boolean;
auth?: AuthOptions;
trustProxy?: string[];
staticDir?: string;
} }
/** /**
@@ -13,10 +19,12 @@ export interface AppOptions {
* M5 src/auth/ (login, persistent session secret) * M5 src/auth/ (login, persistent session secret)
*/ */
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> { export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
const app = Fastify({ logger: options.logger ?? false }); const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
await registerAuth(app, options.auth ?? { dataDir: resolve(process.env.SHELLBOOK_DATA_DIR ?? "data") });
await app.register(websocket); await app.register(websocket);
app.get("/api/health", async () => ({ ok: true })); app.get("/api/health", async () => ({ ok: true }));
await registerStatic(app, options.staticDir ?? resolve("apps/web/dist"));
return app; return app;
} }
+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));
}
+36
View File
@@ -0,0 +1,36 @@
import { createInterface } from "node:readline/promises";
import { resolve } from "node:path";
import { setPassword } from "../auth/credentials";
// TTY input is hidden; piped input is a single line (never a command-line argument).
async function readPassword(): Promise<string> {
if (!process.stdin.isTTY) {
const reader = createInterface({ input: process.stdin });
try { for await (const line of reader) return line; return ""; }
finally { reader.close(); }
}
process.stderr.write("New ShellBook password: ");
process.stdin.setRawMode(true);
process.stdin.resume();
process.stdin.setEncoding("utf8");
return new Promise((resolvePassword, reject) => {
let password = "";
const onData = (chunk: string) => {
for (const char of chunk) {
if (char === "\r" || char === "\n" || char === "\u0003") {
process.stdin.off("data", onData);
process.stdin.setRawMode(false);
process.stdin.pause();
process.stderr.write("\n");
if (char === "\u0003") reject(new Error("Cancelled")); else resolvePassword(password);
return;
}
if (char === "\u007f" || char === "\b") password = password.slice(0, -1);
else password += char;
}
};
process.stdin.on("data", onData);
});
}
await setPassword(resolve(process.env.SHELLBOOK_DATA_DIR ?? "data"), await readPassword());
console.log("Password saved. Existing sessions remain valid until expiry.");
+14 -1
View File
@@ -3,5 +3,18 @@ import { buildApp } from "./app";
const host = process.env.SHELLBOOK_HOST ?? "127.0.0.1"; const host = process.env.SHELLBOOK_HOST ?? "127.0.0.1";
const port = Number(process.env.SHELLBOOK_PORT ?? 8080); const port = Number(process.env.SHELLBOOK_PORT ?? 8080);
const app = await buildApp({ logger: true }); const proxies = process.env.SHELLBOOK_TRUSTED_PROXIES?.split(",").map(ip => ip.trim()).filter(Boolean) ?? [];
const app = await buildApp({
logger: true,
trustProxy: proxies,
staticDir: process.env.SHELLBOOK_STATIC_DIR,
auth: {
dataDir: process.env.SHELLBOOK_DATA_DIR ?? "data",
sessionMaxAgeSeconds: Number(process.env.SHELLBOOK_SESSION_SECONDS ?? 2592000),
forwardAuth: process.env.SHELLBOOK_FORWARD_AUTH_HEADER ? {
header: process.env.SHELLBOOK_FORWARD_AUTH_HEADER,
trustedProxyIps: proxies,
} : undefined,
},
});
await app.listen({ host, port }); await app.listen({ host, port });
+15
View File
@@ -0,0 +1,15 @@
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import type { FastifyInstance } from "fastify";
import fastifyStatic from "@fastify/static";
export async function registerStatic(app: FastifyInstance, directory: string): Promise<void> {
const root = resolve(directory);
if (!existsSync(resolve(root, "index.html"))) return;
await app.register(fastifyStatic, { root, wildcard: false });
app.setNotFoundHandler((request, reply) => {
const path = request.url.split("?")[0]!;
if (path === "/api" || path.startsWith("/api/") || !["GET", "HEAD"].includes(request.method)) return reply.code(404).send({ error: "Not found" });
return reply.type("text/html").sendFile("index.html");
});
}
+133
View File
@@ -0,0 +1,133 @@
import { afterEach, describe, expect, it } from "vitest";
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { FastifyInstance } from "fastify";
import { buildApp, type AppOptions } from "../src/app";
import { hashPassword, setPassword, verifyPassword } from "../src/auth/credentials";
import { loadSessionSecret, signSession, verifySession } from "../src/auth/session";
const dirs: string[] = [];
const apps: FastifyInstance[] = [];
async function directory() { const dir = await mkdtemp(join(tmpdir(), "shellbook-auth-")); dirs.push(dir); return dir; }
async function setup(options: AppOptions = {}) {
const dataDir = options.auth?.dataDir ?? await directory();
await setPassword(dataDir, "test password");
const app = await buildApp({ ...options, auth: { dataDir, ...options.auth } });
apps.push(app);
app.get("/api/private", async () => ({ ok: true }));
app.get("/api/ws", { websocket: true }, socket => { socket.send("authenticated"); });
return { app, dataDir };
}
async function login(app: FastifyInstance, headers = {}) {
return app.inject({ method: "POST", url: "/api/auth/login", payload: { password: "test password" }, headers });
}
afterEach(async () => {
for (const app of apps.splice(0)) await app.close();
for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true });
});
describe("passwords and sessions", () => {
it("salts scrypt hashes and compares passwords safely", async () => {
const hash = await hashPassword("secret");
expect(await hashPassword("secret")).not.toBe(hash);
expect(await verifyPassword("secret", hash)).toBe(true);
expect(await verifyPassword("wrong", hash)).toBe(false);
expect(await verifyPassword("secret", "malformed")).toBe(false);
expect(await verifyPassword("x".repeat(4097), hash)).toBe(false);
await expect(hashPassword("")).rejects.toThrow();
});
it("rejects tampering, wrong keys, invalid input and expired cookies", () => {
const key = Buffer.alloc(32, 1);
const token = signSession(key, 2000);
expect(verifySession(key, token, 1000)).toBe(true);
expect(verifySession(key, token, 2000)).toBe(false);
expect(verifySession(key, token.replace("2000", "3000"), 1000)).toBe(false);
expect(verifySession(Buffer.alloc(32, 2), token, 1000)).toBe(false);
for (const bad of ["", "x.y", "99999999999999999.a", token + "x"]) expect(verifySession(key, bad, 1000)).toBe(false);
});
it("persists a private signing secret and rejects corrupt state", async () => {
const dir = await directory();
expect(loadSessionSecret(dir)).toEqual(loadSessionSecret(dir));
if (process.platform !== "win32") expect((await stat(join(dir, "session-secret"))).mode & 0o777).toBe(0o600);
await writeFile(join(dir, "session-secret"), "bad");
expect(() => loadSessionSecret(dir)).toThrow("Invalid session-secret");
});
});
describe("authentication boundary", () => {
it("protects all API paths, including websocket handshakes, and permits health/login", async () => {
const { app } = await setup();
for (const url of ["/api", "/api/private", "/api/auth/me", "/api/auth/logout", "/api/unknown", "/api/health/", "/api/ws"]) {
const response = await app.inject({ method: url.endsWith("logout") ? "POST" : "GET", url, headers: { connection: "Upgrade", upgrade: "websocket" } });
expect(response.statusCode, url).toBe(401);
}
expect((await app.inject("/api/health?check=1")).statusCode).toBe(200);
await expect(app.injectWS("/api/ws")).rejects.toThrow("401");
expect((await app.inject({ method: "POST", url: "/api/auth/login", payload: { password: "wrong" } })).statusCode).toBe(401);
const response = await login(app);
expect(response.statusCode).toBe(204);
expect(response.headers["set-cookie"]).toContain("HttpOnly; SameSite=Strict; Max-Age=2592000");
const cookie = String(response.headers["set-cookie"]).split(";")[0]!;
expect((await app.inject({ url: "/api/auth/me", headers: { cookie } })).json()).toEqual({ authenticated: true });
const ws = await app.injectWS("/api/ws", { headers: { cookie } });
ws.close();
const logout = await app.inject({ method: "POST", url: "/api/auth/logout", headers: { cookie } });
expect(logout.statusCode).toBe(204);
expect(logout.headers["set-cookie"]).toContain("Max-Age=0");
});
it("survives app restart using the same data directory", async () => {
const { app, dataDir } = await setup();
const cookie = String((await login(app)).headers["set-cookie"]).split(";")[0]!;
await app.close();
apps.splice(apps.indexOf(app), 1);
const second = await buildApp({ auth: { dataDir } }); apps.push(second);
expect((await second.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode).toBe(200);
expect(await readFile(join(dataDir, "auth.json"), "utf8")).not.toContain("test password");
});
it("fails closed without configured password and rejects cross-origin requests", async () => {
const app = await buildApp({ auth: { dataDir: await directory() } }); apps.push(app);
expect((await login(app)).statusCode).toBe(401);
expect((await login(app, { origin: "https://evil.test", host: "shellbook.test" })).statusCode).toBe(403);
});
it("only trusts HTTPS forwarding from configured proxies", async () => {
const { app } = await setup();
expect((await login(app, { "x-forwarded-proto": "https" })).headers["set-cookie"]).not.toContain("Secure");
const { app: trusted } = await setup({ trustProxy: ["127.0.0.1"] });
expect((await login(trusted, { "x-forwarded-proto": "https" })).headers["set-cookie"]).toContain("Secure");
const { app: other } = await setup({ trustProxy: ["192.0.2.1"] });
expect((await login(other, { "x-forwarded-proto": "https" })).headers["set-cookie"]).not.toContain("Secure");
});
it("limits parallel failures per IP and permits retry after the window", async () => {
const { app } = await setup({ auth: { dataDir: await directory(), maxAttempts: 2, rateWindowMs: 100 } });
const attempt = () => app.inject({ method: "POST", url: "/api/auth/login", payload: { password: "wrong" } });
const results = await Promise.all([attempt(), attempt(), attempt()]);
expect(results.map(r => r.statusCode).sort()).toEqual([401, 401, 429]);
await new Promise(resolve => setTimeout(resolve, 120));
expect((await login(app)).statusCode).toBe(204);
});
it("accepts identity headers only from configured direct peers, never X-Forwarded-For", async () => {
const dir = await directory();
const { app } = await setup({ auth: { dataDir: dir, forwardAuth: { header: "Remote-User", trustedProxyIps: ["127.0.0.1"] } } });
expect((await app.inject({ url: "/api/auth/me", headers: { "remote-user": "admin" } })).statusCode).toBe(200);
expect((await app.inject({ url: "/api/auth/me", headers: { "remote-user": " " } })).statusCode).toBe(401);
const { app: untrusted } = await setup({ auth: { dataDir: await directory(), forwardAuth: { header: "Remote-User", trustedProxyIps: ["192.0.2.1"] } } });
expect((await untrusted.inject({ url: "/api/auth/me", headers: { "remote-user": "admin", "x-forwarded-for": "192.0.2.1" } })).statusCode).toBe(401);
const { app: disabled } = await setup();
expect((await disabled.inject({ url: "/api/auth/me", headers: { "remote-user": "admin" } })).statusCode).toBe(401);
});
it("rejects expired sessions and honors configured lifetime", async () => {
const { app, dataDir } = await setup({ auth: { dataDir: await directory(), sessionMaxAgeSeconds: 60 } });
expect((await login(app)).headers["set-cookie"]).toContain("Max-Age=60");
const cookie = `shellbook_session=${signSession(loadSessionSecret(dataDir), Date.now() - 1)}`;
expect((await app.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode).toBe(401);
});
it("serves static assets and SPA routes without swallowing API misses", async () => {
const root = await directory();
await writeFile(join(root, "index.html"), "<h1>ShellBook</h1>");
await writeFile(join(root, "asset.js"), "/* asset */");
const { app } = await setup({ staticDir: root });
expect((await app.inject("/notebooks/example")).body).toBe("<h1>ShellBook</h1>");
expect((await app.inject("/asset.js")).body).toBe("/* asset */");
const cookie = String((await login(app)).headers["set-cookie"]).split(";")[0]!;
expect((await app.inject({ url: "/api/missing", headers: { cookie } })).statusCode).toBe(404);
});
});
+494
View File
File diff suppressed because it is too large Load Diff