Merge branch 't3/implement-auth-deploy'
Integrate auth, config, watcher and terminal wiring in buildApp: auth guards every API route by default, notebook watcher events feed the /api/events hub, the terminal runs in the configured workspace, and SHELLBOOK_DATA_DIR is the single data directory variable. The systemd unit uses KillMode=process so tmux sessions survive service restarts.
This commit is contained in:
+37
-9
@@ -3,28 +3,56 @@ import websocket from "@fastify/websocket";
|
||||
import { loadConfig, type ServerConfig } from "./config";
|
||||
import { workspacePlugin } from "./workspace";
|
||||
import { runsPlugin, EventsHub } from "./runs";
|
||||
import { terminalPlugin, type TerminalOptions } from "./terminal";
|
||||
import { createNotebookWatcher } from "./watch";
|
||||
import { registerAuth, type AuthOptions } from "./auth";
|
||||
import { registerStatic } from "./static";
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: boolean;
|
||||
config?: Partial<ServerConfig>;
|
||||
events?: EventsHub;
|
||||
/**
|
||||
* Login protection for all /api routes. Enabled by default with `config.dataDir`.
|
||||
* `false` exists only for tests that exercise other plugins in isolation.
|
||||
*/
|
||||
auth?: Partial<AuthOptions> | false;
|
||||
trustProxy?: string[];
|
||||
/** Built web app (apps/web/dist); served only when it contains index.html. */
|
||||
staticDir?: string;
|
||||
/** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */
|
||||
watchNotebooks?: boolean;
|
||||
terminal?: Omit<TerminalOptions, "workspaceDir">;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the Fastify app. Feature areas live in their own folders and are
|
||||
* registered here as Fastify plugins, one line each:
|
||||
* M2 src/workspace/ (notebooks, hosts.yaml), src/ssh/, src/runs/ (queue, audit, artifacts, /api/events)
|
||||
* M4 src/terminal/ (node-pty + tmux, /api/terminal), src/watch/ (file.changed events)
|
||||
* M5 src/auth/ (login, persistent session secret)
|
||||
* Builds the Fastify app. Feature areas live in their own folders:
|
||||
* src/auth/ login, persistent session secret (registered first: its hook guards every /api route)
|
||||
* src/workspace/ notebooks, hosts.yaml; src/ssh/, src/runs/ queue, audit, artifacts, /api/events
|
||||
* src/terminal/ node-pty + tmux, /api/terminal; src/watch/ file.changed events into the events hub
|
||||
* src/static/ built web app with SPA fallback
|
||||
*/
|
||||
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
|
||||
const app = Fastify({ logger: options.logger ?? false });
|
||||
const config = loadConfig(options.config);
|
||||
const hub = options.events ?? new EventsHub();
|
||||
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
|
||||
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
||||
await app.register(websocket);
|
||||
await app.register(workspacePlugin, { config: loadConfig(options.config) });
|
||||
await app.register(runsPlugin, { config: loadConfig(options.config), hub: options.events ?? new EventsHub() });
|
||||
await app.register((await import("./terminal/index")).terminalPlugin);
|
||||
await app.register(workspacePlugin, { config });
|
||||
await app.register(runsPlugin, { config, hub });
|
||||
await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir });
|
||||
|
||||
if (options.watchNotebooks) {
|
||||
const watcher = createNotebookWatcher(config.workspaceDir, {
|
||||
onError: error => app.log.error({ err: error }, "notebook watcher error"),
|
||||
});
|
||||
watcher.on(event => hub.publish(event));
|
||||
app.addHook("onClose", async () => { await watcher.close(); });
|
||||
await watcher.ready;
|
||||
}
|
||||
|
||||
app.get("/api/health", async () => ({ ok: true }));
|
||||
if (options.staticDir) await registerStatic(app, options.staticDir);
|
||||
|
||||
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.");
|
||||
@@ -9,7 +9,7 @@ export interface ServerConfig {
|
||||
export function loadConfig(overrides: Partial<ServerConfig> = {}): ServerConfig {
|
||||
return {
|
||||
workspaceDir: path.resolve(overrides.workspaceDir ?? process.env.SHELLBOOK_WORKSPACE ?? "workspace"),
|
||||
dataDir: path.resolve(overrides.dataDir ?? process.env.SHELLBOOK_DATA ?? "data"),
|
||||
dataDir: path.resolve(overrides.dataDir ?? process.env.SHELLBOOK_DATA_DIR ?? "data"),
|
||||
sshKeyPath: path.resolve(overrides.sshKeyPath ?? process.env.SHELLBOOK_SSH_KEY ?? "data/id_ed25519"),
|
||||
};
|
||||
}
|
||||
|
||||
+17
-1
@@ -1,7 +1,23 @@
|
||||
import { buildApp } from "./app";
|
||||
import { loadConfig } from "./config";
|
||||
|
||||
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 config = loadConfig();
|
||||
const app = await buildApp({
|
||||
logger: true,
|
||||
config,
|
||||
trustProxy: proxies,
|
||||
staticDir: process.env.SHELLBOOK_STATIC_DIR,
|
||||
watchNotebooks: true,
|
||||
auth: {
|
||||
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