feat(settings): add browser setup and administration (#10)
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { registerSettings } from "./settings";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import websocket from "@fastify/websocket";
|
||||
import { loadConfig, type ServerConfig } from "./config";
|
||||
@@ -37,6 +38,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
|
||||
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 registerSettings(app, config);
|
||||
await app.register(websocket);
|
||||
await app.register(workspacePlugin, { config });
|
||||
await app.register(runsPlugin, { config, hub });
|
||||
|
||||
@@ -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 }));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
|
||||
import { mkdirSync, readFileSync, writeFileSync, chmodSync, renameSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function loadSessionSecret(dataDir: string): Buffer {
|
||||
@@ -22,3 +22,12 @@ export function verifySession(secret: Buffer, cookie: string, now = Date.now()):
|
||||
const expected = signSession(secret, Number(payload)).split(".")[1]!;
|
||||
return Number(payload) > now && timingSafeEqual(Buffer.from(mac!), Buffer.from(expected));
|
||||
}
|
||||
|
||||
/** Replace before publishing the new key to request handlers. */
|
||||
export function rotateSessionSecret(dataDir: string): Buffer {
|
||||
const secret = randomBytes(32);
|
||||
const temp = join(dataDir, `session-secret.${randomBytes(8).toString("hex")}.tmp`);
|
||||
writeFileSync(temp, secret, { mode: 0o600, flag: "wx" });
|
||||
renameSync(temp, join(dataDir, "session-secret"));
|
||||
return secret;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
|
||||
import { chmod, readFile, writeFile, unlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const setupTokenPath = (dataDir: string) => join(dataDir, "setup-token");
|
||||
export async function ensureSetupToken(dataDir: string): Promise<void> {
|
||||
const path = setupTokenPath(dataDir);
|
||||
try {
|
||||
await writeFile(path, randomBytes(32).toString("hex") + "\n", {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
||||
}
|
||||
await chmod(path, 0o600);
|
||||
}
|
||||
export async function matchesSetupToken(
|
||||
dataDir: string,
|
||||
candidate: unknown,
|
||||
): Promise<boolean> {
|
||||
if (typeof candidate !== "string" || candidate.length > 4096) return false;
|
||||
try {
|
||||
const expected = (await readFile(setupTokenPath(dataDir), "utf8")).trim();
|
||||
const digest = (value: string) =>
|
||||
createHash("sha256").update(value).digest();
|
||||
return timingSafeEqual(digest(candidate), digest(expected));
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export async function removeSetupToken(dataDir: string): Promise<void> {
|
||||
await unlink(setupTokenPath(dataDir)).catch((error) => {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
});
|
||||
}
|
||||
export function validNewPassword(value: unknown): value is string {
|
||||
return (
|
||||
typeof value === "string" &&
|
||||
value.length >= 12 &&
|
||||
Buffer.byteLength(value) <= 4096
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { access } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { ClaudeStatusResponse, SystemInfoResponse } from "@shellbook/core";
|
||||
import type { ServerConfig } from "../config";
|
||||
import { version } from "../../package.json";
|
||||
|
||||
/** No shell, bounded runtime/output, and no credential contents are accessed. */
|
||||
export async function claudeStatus(
|
||||
home = homedir(),
|
||||
env = process.env,
|
||||
): Promise<ClaudeStatusResponse> {
|
||||
const loginAppearsPresent = await access(
|
||||
join(home, ".claude", ".credentials.json"),
|
||||
).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
return new Promise((resolve) => {
|
||||
execFile(
|
||||
"claude",
|
||||
["--version"],
|
||||
{ env, timeout: 3000, maxBuffer: 4096, windowsHide: true },
|
||||
(error, stdout) => {
|
||||
resolve({
|
||||
available: !error,
|
||||
version: error ? null : stdout.trim(),
|
||||
loginAppearsPresent,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
export async function registerSettings(
|
||||
app: FastifyInstance,
|
||||
config: ServerConfig,
|
||||
): Promise<void> {
|
||||
app.get("/api/settings/claude", async (_request, reply) =>
|
||||
reply.header("Cache-Control", "no-store").send(await claudeStatus()),
|
||||
);
|
||||
app.get("/api/settings/system", async (_request, reply) => {
|
||||
const info: SystemInfoResponse = {
|
||||
version,
|
||||
workspacePath: config.workspaceDir,
|
||||
dataDirPath: config.dataDir,
|
||||
nodeVersion: process.version,
|
||||
};
|
||||
return reply.header("Cache-Control", "no-store").send(info);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user