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:
@@ -1,8 +1,14 @@
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import websocket from "@fastify/websocket";
|
||||
import { resolve } from "node:path";
|
||||
import { registerAuth, type AuthOptions } from "./auth";
|
||||
import { registerStatic } from "./static";
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: boolean;
|
||||
auth?: AuthOptions;
|
||||
trustProxy?: string[];
|
||||
staticDir?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -13,10 +19,12 @@ export interface AppOptions {
|
||||
* M5 src/auth/ (login, persistent session secret)
|
||||
*/
|
||||
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);
|
||||
|
||||
app.get("/api/health", async () => ({ ok: true }));
|
||||
await registerStatic(app, options.staticDir ?? resolve("apps/web/dist"));
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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 }));
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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
@@ -3,5 +3,18 @@ import { buildApp } from "./app";
|
||||
const host = process.env.SHELLBOOK_HOST ?? "127.0.0.1";
|
||||
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 });
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user