diff --git a/.agents/mind/architecture.md b/.agents/mind/architecture.md index 5e64da4..c015117 100644 --- a/.agents/mind/architecture.md +++ b/.agents/mind/architecture.md @@ -8,4 +8,6 @@ - [2026-11-16] **Secrets on SSH:** exported via `export NAME=` lines on stdin before the script (sshd AcceptEnv unreliable); redacted from streamed output, captures and audit. - [2026-11-16] **Deploy:** Node 22 from the official nodejs.org tarball verified against SHASUMS256; node-pty 1.1.0 has no Linux prebuilds, so the installer adds build-essential + python3. +- [2026-11-16] **Settings (#10):** browser setup consumes private setup-token; cookies are bound to the password hash, and sign-out-all atomically rotates the persisted secret. Browser auth mutations serialize and close active WebSockets. + ## Archive diff --git a/.agents/mind/index.md b/.agents/mind/index.md index 358f0fd..5a30581 100644 --- a/.agents/mind/index.md +++ b/.agents/mind/index.md @@ -14,7 +14,7 @@ - Notebooks stay plain, readable Markdown. ## Table of Contents -- `architecture.md` — 7 entries — why custom app, stack, AI integration, workspace split +- `architecture.md` — 8 entries — why custom app, stack, AI integration, workspace split - `attempts.md` — 2 entries — marimo + marimo-pair trial and why it was dropped - `open.md` — 2 entries — open design questions - `gotchas.md` — 5 entries — integration foot-guns (CRLF scripts, host-key event order, tmux vs systemd, env names) diff --git a/apps/server/README.md b/apps/server/README.md index 81ff6c2..18894d7 100644 --- a/apps/server/README.md +++ b/apps/server/README.md @@ -94,3 +94,29 @@ uploads, and capture/runtime rendering without bash. The full shipped `ssh-key.m flow generates real keys and skips cleanly when bash or ssh-keygen is unavailable; it runs in CI/Linux, and also on Windows when a working bash with ssh-keygen is installed. No real target host is modified by these tests. + +## Setup and settings (#10) + +On first startup, `dataDir/setup-token` is created privately (0600). The startup +message names its path, never the token. Read it locally and finish setup in the +browser. GET `/api/auth/setup` returns `{required}`; POST accepts +`{token,newPassword,confirmPassword}`, consumes the token, and returns 204 with a +session cookie (409 once configured). Setup/login share a per-IP limiter and the +origin check. Keep the data directory private and owned by the service user. + +Authenticated routes: POST `/api/settings/password` accepts +`{currentPassword,newPassword,confirmPassword}`; POST `/api/settings/sessions/revoke` +rotates the signing key atomically. Both return 204 with a replacement cookie and +close existing WebSockets. Passwords need 12 characters and at most 4096 bytes. +Hash-bound session signatures invalidate cookies after CLI password changes too. +Previously issued cookies from before this feature require a fresh login once. +GET `/api/settings/session` returns `{lifetimeSeconds}`; GET `/api/settings/system` +returns package version, workspace/data paths, and Node version. GET +`/api/settings/claude` runs `claude --version` with no shell, a 3-second timeout +and 4096-byte output limit. `loginAppearsPresent` checks existence only of the +service user's `~/.claude/.credentials.json`; it cannot prove login validity +(and does not inspect macOS Keychain credentials). All status responses are no-store. + +Auth mutations are serialized within the single service process. Run one server +per data directory. Already-running host jobs are not cancelled by revocation. +Forward-auth access must be revoked at the upstream provider. diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index ed3ac60..c9a81b3 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -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 ip.replace(/^::ffff:/, ""); export async function registerAuth(app: FastifyInstance, options: AuthOptions): Promise { - 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 = Promise.resolve(); + const exclusive = (action: () => Promise): Promise => { + 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(); @@ -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 })); } diff --git a/apps/server/src/auth/session.ts b/apps/server/src/auth/session.ts index 8f657c6..5f63190 100644 --- a/apps/server/src/auth/session.ts +++ b/apps/server/src/auth/session.ts @@ -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; +} diff --git a/apps/server/src/auth/setup.ts b/apps/server/src/auth/setup.ts new file mode 100644 index 0000000..eb82de3 --- /dev/null +++ b/apps/server/src/auth/setup.ts @@ -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 { + 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 { + 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 { + 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 + ); +} diff --git a/apps/server/src/settings/index.ts b/apps/server/src/settings/index.ts new file mode 100644 index 0000000..4826ab0 --- /dev/null +++ b/apps/server/src/settings/index.ts @@ -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 { + 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 { + 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); + }); +} diff --git a/apps/server/test/settings.test.ts b/apps/server/test/settings.test.ts new file mode 100644 index 0000000..3cd5fd1 --- /dev/null +++ b/apps/server/test/settings.test.ts @@ -0,0 +1,310 @@ +import { afterEach, expect, it } from "vitest"; +import { + mkdtemp, + readFile, + rm, + stat, + writeFile, + mkdir, + copyFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { FastifyInstance } from "fastify"; +import { buildApp } from "../src/app"; +import { setPassword } from "../src/auth/credentials"; +import { claudeStatus } from "../src/settings"; +const dirs: string[] = [], + apps: FastifyInstance[] = []; +async function dir() { + const path = await mkdtemp(join(tmpdir(), "settings-")); + dirs.push(path); + return path; +} +async function setup(maxAttempts = 5) { + const dataDir = await dir(); + const app = await buildApp({ config: { dataDir }, auth: { maxAttempts } }); + apps.push(app); + return { app, dataDir }; +} +const password = "a long test password"; +const cookieOf = (r: { headers: Record }) => + String(r.headers["set-cookie"]).split(";")[0]!; +afterEach(async () => { + for (const app of apps.splice(0)) await app.close(); + for (const path of dirs.splice(0)) + await rm(path, { recursive: true, force: true }); +}); +it("creates a persistent private token and consumes it once, including parallel setup", async () => { + const { app, dataDir } = await setup(); + const token = (await readFile(join(dataDir, "setup-token"), "utf8")).trim(); + expect(token).toMatch(/^[a-f0-9]{64}$/); + if (process.platform !== "win32") + expect((await stat(join(dataDir, "setup-token"))).mode & 0o777).toBe(0o600); + expect((await app.inject("/api/auth/setup")).json()).toEqual({ + required: true, + }); + expect( + ( + await app.inject({ + method: "POST", + url: "/api/auth/setup", + payload: { + token: "wrong", + newPassword: password, + confirmPassword: password, + }, + }) + ).statusCode, + ).toBe(401); + const payload = { token, newPassword: password, confirmPassword: password }; + const results = await Promise.all( + [1, 2].map(() => + app.inject({ method: "POST", url: "/api/auth/setup", payload }), + ), + ); + expect(results.map((r) => r.statusCode).sort()).toEqual([204, 409]); + await expect(stat(join(dataDir, "setup-token"))).rejects.toMatchObject({ + code: "ENOENT", + }); + expect((await app.inject("/api/auth/setup")).json()).toEqual({ + required: false, + }); + const cookie = cookieOf(results.find((r) => r.statusCode === 204)!); + expect( + (await app.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode, + ).toBe(200); + if (process.platform !== "win32") + expect((await stat(join(dataDir, "auth.json"))).mode & 0o777).toBe(0o600); +}); +it("retains the setup token across restart and removes stale tokens with configured password", async () => { + const { app, dataDir } = await setup(); + const token = await readFile(join(dataDir, "setup-token"), "utf8"); + await app.close(); + apps.splice(apps.indexOf(app), 1); + const second = await buildApp({ config: { dataDir } }); + apps.push(second); + expect(await readFile(join(dataDir, "setup-token"), "utf8")).toBe(token); + await setPassword(dataDir, password); + const third = await buildApp({ config: { dataDir } }); + apps.push(third); + await expect(stat(join(dataDir, "setup-token"))).rejects.toMatchObject({ + code: "ENOENT", + }); +}); +it("shares setup/login limits and rejects weak or mismatched passwords", async () => { + const { app, dataDir } = await setup(3); + const token = (await readFile(join(dataDir, "setup-token"), "utf8")).trim(); + for (const [newPassword, confirmPassword] of [ + ["short", "short"], + [password, "different"], + ]) { + expect( + ( + await app.inject({ + method: "POST", + url: "/api/auth/setup", + payload: { token, newPassword, confirmPassword }, + }) + ).statusCode, + ).toBe(400); + } + expect( + ( + await app.inject({ + method: "POST", + url: "/api/auth/login", + payload: { password }, + }) + ).statusCode, + ).toBe(401); + const response = await app.inject({ + method: "POST", + url: "/api/auth/setup", + payload: { token, newPassword: password, confirmPassword: password }, + }); + expect(response.statusCode).toBe(429); + expect(response.headers["retry-after"]).toBeDefined(); +}); +it("keeps every settings route private and setup under the origin check", async () => { + const { app } = await setup(); + for (const [method, url] of [ + ["GET", "/api/settings/system"], + ["GET", "/api/settings/claude"], + ["GET", "/api/settings/session"], + ["POST", "/api/settings/password"], + ["POST", "/api/settings/sessions/revoke"], + ["GET", "/api/auth/setup/"], + ["GET", "/api/auth/setup/extra"], + ] as const) { + expect((await app.inject({ method, url })).statusCode, url).toBe(401); + } + expect( + ( + await app.inject({ + method: "POST", + url: "/api/auth/setup", + headers: { origin: "https://evil.test" }, + payload: {}, + }) + ).statusCode, + ).toBe(403); +}); +it("checks current password, revokes cookies on password change and rotation, survives restart", async () => { + const { app, dataDir } = await setup(); + await setPassword(dataDir, password); + const login = async () => + cookieOf( + await app.inject({ + method: "POST", + url: "/api/auth/login", + payload: { password }, + }), + ); + const cookie = await login(); + const payload = { + currentPassword: "wrong", + newPassword: "new long password", + confirmPassword: "new long password", + }; + const change = () => + app.inject({ + method: "POST", + url: "/api/settings/password", + headers: { cookie }, + payload, + }); + expect((await change()).statusCode).toBe(401); + payload.currentPassword = password; + payload.confirmPassword = "mismatch"; + expect((await change()).statusCode).toBe(400); + payload.confirmPassword = payload.newPassword; + const changed = await change(); + expect(changed.statusCode).toBe(204); + const fresh = cookieOf(changed); + expect( + (await app.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode, + ).toBe(401); + expect( + ( + await app.inject({ + url: "/api/settings/session", + headers: { cookie: fresh }, + }) + ).json(), + ).toEqual({ lifetimeSeconds: 2592000 }); + const oldSecret = await readFile(join(dataDir, "session-secret")); + const revoked = await app.inject({ + method: "POST", + url: "/api/settings/sessions/revoke", + headers: { cookie: fresh }, + }); + expect(revoked.statusCode).toBe(204); + expect(await readFile(join(dataDir, "session-secret"))).not.toEqual( + oldSecret, + ); + expect( + (await app.inject({ url: "/api/auth/me", headers: { cookie: fresh } })) + .statusCode, + ).toBe(401); + const renewed = cookieOf(revoked); + const second = await buildApp({ config: { dataDir } }); + apps.push(second); + expect( + ( + await second.inject({ + url: "/api/settings/system", + headers: { cookie: renewed }, + }) + ).json(), + ).toMatchObject({ + dataDirPath: dataDir, + nodeVersion: process.version, + version: "0.0.0", + }); + await setPassword(dataDir, "CLI changed password"); + expect( + (await second.inject({ url: "/api/auth/me", headers: { cookie: renewed } })) + .statusCode, + ).toBe(401); +}); +it("reports absent CLI/credentials without reading contents", async () => { + const home = await dir(); + expect(await claudeStatus(home, { PATH: home })).toEqual({ + available: false, + version: null, + loginAppearsPresent: false, + }); + await mkdir(join(home, ".claude")); + await mkdir(join(home, ".claude", ".credentials.json")); + expect((await claudeStatus(home, { PATH: home })).loginAppearsPresent).toBe( + true, + ); +}); +it("runs a fake Claude executable from PATH with argv", async () => { + const home = await dir(); + if (process.platform === "win32") { + await copyFile(process.execPath, join(home, "claude.exe")); + expect( + await claudeStatus(home, { + PATH: home, + SystemRoot: process.env.SystemRoot, + }), + ).toEqual({ + available: true, + version: process.version, + loginAppearsPresent: false, + }); + return; + } + await writeFile( + join(home, "claude"), + '#!/bin/sh\n[ "$1" = --version ] || exit 1\nprintf "fake-claude 1.0\\n"\n', + { mode: 0o700 }, + ); + expect(await claudeStatus(home, { PATH: home })).toEqual({ + available: true, + version: "fake-claude 1.0", + loginAppearsPresent: false, + }); +}); + +it("closes active WebSockets on password changes and sign-out-all", async () => { + const { app, dataDir } = await setup(); + await setPassword(dataDir, password); + app.get("/api/test-socket", { websocket: true }, (socket) => { + socket.send("ready"); + }); + let cookie = cookieOf( + await app.inject({ + method: "POST", + url: "/api/auth/login", + payload: { password }, + }), + ); + for (const url of [ + "/api/settings/password", + "/api/settings/sessions/revoke", + ]) { + const ws = await app.injectWS("/api/test-socket", { headers: { cookie } }); + const closed = new Promise((resolve) => ws.on("close", resolve)); + const response = await app.inject({ + method: "POST", + url, + headers: { cookie }, + payload: url.endsWith("password") + ? { + currentPassword: password, + newPassword: "changed test password", + confirmPassword: "changed test password", + } + : {}, + }); + expect(response.statusCode).toBe(204); + await closed; + await expect( + app.injectWS("/api/test-socket", { headers: { cookie } }), + ).rejects.toThrow("401"); + cookie = cookieOf(response); + } +}); diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index d8fd693..723b214 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,3 +1,7 @@ +import { HeaderNavigation, type NavigationPage } from "./HeaderNavigation"; +import { SettingsPage } from "./SettingsPage"; +import { SetupScreen } from "./SetupScreen"; +import { settingsApi } from "./settingsApi"; import { lazy, Suspense, @@ -46,7 +50,8 @@ function steps(blocks: Block[]): Step[] { ); } export function App({ api }: { api: Api }) { - const [auth, setAuth] = useState<"loading" | "login" | "ready">("loading"); + const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading"); + const [page, setPage] = useState("Notebooks"); const [password, setPassword] = useState(""); const [list, setList] = useState([]); const [hosts, setHosts] = useState([]); @@ -103,8 +108,12 @@ export function App({ api }: { api: Api }) { .me() .then(() => setAuth("ready")) .catch((e) => { - if (e instanceof HttpError && e.status === 401) setAuth("login"); - else setError(String(e)); + if (e instanceof HttpError && e.status === 401) { + setAuth("login"); + void settingsApi.setupStatus() + .then(status => { if (status.required) setAuth("setup"); }) + .catch(() => {}); + } else setError(String(e)); }); }, [api]); useEffect(() => { @@ -281,6 +290,7 @@ export function App({ api }: { api: Api }) { const keyPrompt = Object.values(session.runs).find( (run) => run.status === "hostKey" && requests.current.has(run.runId), ); + if (auth === "setup") return setAuth("ready")} />; if (auth === "login") return (
@@ -347,6 +357,10 @@ export function App({ api }: { api: Api }) {
+ + {page === "Settings" && { setTerminalOpened(true); setTerminal(true); }} />} + {page === "Hosts" &&

Host management will appear here.

} +
{terminalOpened && ( Loading terminal...

}> diff --git a/apps/web/src/HeaderNavigation.tsx b/apps/web/src/HeaderNavigation.tsx new file mode 100644 index 0000000..53353c7 --- /dev/null +++ b/apps/web/src/HeaderNavigation.tsx @@ -0,0 +1,24 @@ +// Feature navigation: add entries here and mount their view in App. Hosts is a placeholder for #7. +export const navigationItems = ["Notebooks", "Hosts", "Settings"] as const; +export type NavigationPage = (typeof navigationItems)[number]; +export function HeaderNavigation({ + page, + onChange, +}: { + page: NavigationPage; + onChange: (page: NavigationPage) => void; +}) { + return ( + + ); +} diff --git a/apps/web/src/PasswordForm.tsx b/apps/web/src/PasswordForm.tsx new file mode 100644 index 0000000..7458031 --- /dev/null +++ b/apps/web/src/PasswordForm.tsx @@ -0,0 +1,98 @@ +import { useState } from "react"; +import type { ChangePasswordRequest, SetupRequest } from "@shellbook/core"; +export function PasswordForm({ + setup = false, + submit, +}: { + setup?: boolean; + submit: (body: ChangePasswordRequest & SetupRequest) => Promise; +}) { + const [token, setToken] = useState(""); + const [currentPassword, setCurrent] = useState(""); + const [newPassword, setNew] = useState(""); + const [confirmPassword, setConfirm] = useState(""); + const [busy, setBusy] = useState(false); + const [message, setMessage] = useState(""); + return ( +
{ + event.preventDefault(); + if (newPassword !== confirmPassword) { + setMessage("Passwords do not match"); + return; + } + setBusy(true); + setMessage(""); + try { + await submit({ + token, + currentPassword, + newPassword, + confirmPassword, + }); + setToken(""); + setCurrent(""); + setNew(""); + setConfirm(""); + setMessage("Password saved. Other sessions have been signed out."); + } catch { + setMessage( + "Unable to save. Check your credentials and try again; too many attempts require waiting a minute.", + ); + } finally { + setBusy(false); + } + }} + > + {setup ? ( + + ) : ( + + )} + + +

Use at least 12 characters (maximum 4096 bytes).

+ + {message &&

{message}

} +
+ ); +} diff --git a/apps/web/src/SettingsPage.tsx b/apps/web/src/SettingsPage.tsx new file mode 100644 index 0000000..3816a75 --- /dev/null +++ b/apps/web/src/SettingsPage.tsx @@ -0,0 +1,110 @@ +import { useEffect, useState } from "react"; +import type { + ClaudeStatusResponse, + SystemInfoResponse, + SessionSettingsResponse, +} from "@shellbook/core"; +import { settingsApi } from "./settingsApi"; +import { PasswordForm } from "./PasswordForm"; +export function SettingsPage({ openTerminal }: { openTerminal: () => void }) { + const [info, setInfo] = useState(); + const [claude, setClaude] = useState(); + const [session, setSession] = useState(); + const [message, setMessage] = useState(""); + const [busy, setBusy] = useState(false); + useEffect(() => { + let active = true; + Promise.all([ + settingsApi.system(), + settingsApi.claude(), + settingsApi.session(), + ]) + .then(([i, c, s]) => { + if (active) { + setInfo(i); + setClaude(c); + setSession(s); + } + }) + .catch(() => { + if (active) + setMessage("Unable to load settings. Sign in again or retry."); + }); + return () => { + active = false; + }; + }, []); + return ( +
+

Settings

+
+

Password and sessions

+ + {session && ( +

+ Session lifetime: {session.lifetimeSeconds} seconds ( + {session.lifetimeSeconds / 86400} days). +

+ )} + +
+
+

Claude CLI

+ {claude ? ( + <> +

+ {claude.available + ? `Available: ${claude.version}` + : "Claude is unavailable on PATH or did not respond."} +

+

+ {claude.loginAppearsPresent + ? "Credentials file exists; login may be available." + : "No credentials file found."} +

+ + ) : ( +

Checking CLI...

+ )} + +

+ Run claude, then /login. Credentials are + checked for existence only. +

+
+
+

About/System

+ {info && ( +
+
ShellBook version
+
{info.version}
+
Workspace
+
{info.workspacePath}
+
Data directory
+
{info.dataDirPath}
+
Node version
+
{info.nodeVersion}
+
+ )} +
+ {message &&

{message}

} +
+ ); +} diff --git a/apps/web/src/SetupScreen.tsx b/apps/web/src/SetupScreen.tsx new file mode 100644 index 0000000..80dd6ed --- /dev/null +++ b/apps/web/src/SetupScreen.tsx @@ -0,0 +1,20 @@ +import { PasswordForm } from "./PasswordForm"; +import { settingsApi } from "./settingsApi"; +export function SetupScreen({ onComplete }: { onComplete: () => void }) { + return ( +
+

Set up ShellBook

+

+ Enter the one-time token from the setup-token file in the server data + directory. +

+ { + await settingsApi.setup(body); + onComplete(); + }} + /> +
+ ); +} diff --git a/apps/web/src/settingsApi.ts b/apps/web/src/settingsApi.ts new file mode 100644 index 0000000..a0caff0 --- /dev/null +++ b/apps/web/src/settingsApi.ts @@ -0,0 +1,31 @@ +import type { + SetupStatusResponse, + SetupRequest, + ChangePasswordRequest, + SessionSettingsResponse, + ClaudeStatusResponse, + SystemInfoResponse, +} from "@shellbook/core"; +import { HttpError } from "./api"; +async function request(path: string, body?: unknown): Promise { + const response = await fetch(`/api${path}`, { + method: body === undefined ? "GET" : "POST", + credentials: "same-origin", + headers: body === undefined ? {} : { "Content-Type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + if (!response.ok) throw new HttpError(response.status); + return response.status === 204 + ? (undefined as T) + : (response.json() as Promise); +} +export const settingsApi = { + setupStatus: () => request("/auth/setup"), + setup: (body: SetupRequest) => request("/auth/setup", body), + password: (body: ChangePasswordRequest) => + request("/settings/password", body), + revoke: () => request("/settings/sessions/revoke", {}), + session: () => request("/settings/session"), + claude: () => request("/settings/claude"), + system: () => request("/settings/system"), +}; diff --git a/apps/web/src/tests/settings.test.tsx b/apps/web/src/tests/settings.test.tsx new file mode 100644 index 0000000..c1ebf73 --- /dev/null +++ b/apps/web/src/tests/settings.test.tsx @@ -0,0 +1,91 @@ +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { PasswordForm } from "../PasswordForm"; +import { SetupScreen } from "../SetupScreen"; +import { SettingsPage } from "../SettingsPage"; +import { HeaderNavigation } from "../HeaderNavigation"; +import { settingsApi } from "../settingsApi"; +afterEach(() => vi.restoreAllMocks()); +function fill(label: string, value: string) { + fireEvent.change(screen.getByLabelText(label), { target: { value } }); +} +it("validates confirmation and clears credentials after setup", async () => { + const submit = vi.fn().mockResolvedValue(undefined); + render(); + fill("Setup token", "token"); + fill("New password", "long password here"); + fill("Confirm password", "wrong password here"); + fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" })); + expect(await screen.findByText("Passwords do not match")).toBeInTheDocument(); + expect(submit).not.toHaveBeenCalled(); + fill("Confirm password", "long password here"); + fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" })); + await waitFor(() => + expect(submit).toHaveBeenCalledWith({ + token: "token", + currentPassword: "", + newPassword: "long password here", + confirmPassword: "long password here", + }), + ); + await waitFor(() => + expect(screen.getByLabelText("New password")).toHaveValue(""), + ); +}); +it("submits setup and enters the app", async () => { + vi.spyOn(settingsApi, "setup").mockResolvedValue(); + const done = vi.fn(); + render(); + fill("Setup token", "token"); + fill("New password", "long password here"); + fill("Confirm password", "long password here"); + fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" })); + await waitFor(() => expect(done).toHaveBeenCalledOnce()); +}); +it("shows password failure and preserves the form for retry", async () => { + render( + , + ); + fill("Current password", "wrong"); + fill("New password", "long password here"); + fill("Confirm password", "long password here"); + fireEvent.click(screen.getByRole("button", { name: "Change password" })); + expect(await screen.findByRole("status")).toHaveTextContent("Unable to save"); +}); +it("renders system/session/Claude information and opens the terminal", async () => { + vi.spyOn(settingsApi, "system").mockResolvedValue({ + version: "1.2", + workspacePath: "/workspace", + dataDirPath: "/data", + nodeVersion: "v22", + }); + vi.spyOn(settingsApi, "session").mockResolvedValue({ + lifetimeSeconds: 86400, + }); + vi.spyOn(settingsApi, "claude").mockResolvedValue({ + available: true, + version: "Claude 1", + loginAppearsPresent: true, + }); + const revoke = vi.spyOn(settingsApi, "revoke").mockResolvedValue(); + const open = vi.fn(); + render(); + expect(await screen.findByText("/workspace")).toBeInTheDocument(); + expect(screen.getByText(/86400 seconds/)).toBeInTheDocument(); + expect(screen.getByText("Available: Claude 1")).toBeInTheDocument(); + fireEvent.click(screen.getByText("Open terminal to log in")); + expect(open).toHaveBeenCalledOnce(); + fireEvent.click(screen.getByText("Sign out all sessions")); + await waitFor(() => expect(revoke).toHaveBeenCalledOnce()); + expect(await screen.findByRole("status")).toHaveTextContent( + "This browser remains signed in", + ); +}); +it("provides the shared feature navigation", () => { + const change = vi.fn(); + render(); + fireEvent.click(screen.getByText("Settings")); + expect(change).toHaveBeenCalledWith("Settings"); + expect(screen.getByText("Hosts")).toBeInTheDocument(); + expect(screen.getByText("Notebooks")).toHaveAttribute("aria-current", "page"); +}); diff --git a/deploy/README.md b/deploy/README.md index bbc4f3f..176e2af 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -15,9 +15,11 @@ LAN/Tailscale addresses. No password is set initially: API access fails closed. `SHELLBOOK_PORT`, `SHELLBOOK_TRUSTED_PROXIES` (comma-separated proxy IPs), and `TS_AUTHKEY` in the host environment. Auth keys are transferred in a mode-0600 temporary file and removed, never stored in the service env. -3. In the CT run the printed password command. It also accepts one password - line on stdin; do not pass passwords as arguments. Source-checkout command: - `SHELLBOOK_DATA_DIR=/var/lib/shellbook pnpm --filter @shellbook/server set-password`. +3. Open ShellBook in your browser. In the CT run `cat /var/lib/shellbook/setup-token` + and enter the token with a new password (at least 12 characters) in the setup screen. + This token is private, survives restart, and is deleted after setup. It is never logged. + Alternative password CLI: `SHELLBOOK_DATA_DIR=/var/lib/shellbook pnpm --filter @shellbook/server set-password` + from the checkout (hidden prompt or one password line on stdin; never arguments). 4. Run `claude` as shellbook and use `/login`. Authorize `/home/shellbook/.ssh/id_ed25519.pub` on managed hosts. The service user has no sudo access. Initialize notebooks manually if templates were absent. @@ -36,8 +38,13 @@ leaves the running service in place. Check `journalctl -u shellbook`. Configuration is `/etc/shellbook/env`; data is `/var/lib/shellbook` (back it up along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie; -password changes do not revoke existing cookies. For emergency revocation stop -the service, delete `session-secret` from the data directory and start it again. +Settings supports changing the password and signing out all sessions; both revoke +older cookies and close active WebSockets, while the current browser receives a fresh +cookie. CLI password changes invalidate cookies on their next request. For emergency +revocation stop the service, delete `session-secret`, and restart it. +Settings also shows paths, versions, and Claude CLI status, and opens the terminal +for `claude` then `/login` as the service user. A credentials file's existence is only +a hint, not proof that a login is valid. Forward auth is off by default. To enable it set `SHELLBOOK_FORWARD_AUTH_HEADER=Remote-User` and trusted proxy IPs. The header is diff --git a/deploy/install.sh b/deploy/install.sh index 25751f9..35ae991 100755 --- a/deploy/install.sh +++ b/deploy/install.sh @@ -122,7 +122,9 @@ systemctl enable shellbook systemctl restart shellbook cat <<'EOF' Next steps: -1. Set the password (hidden prompt): +1. Open ShellBook in the browser and enter the setup token shown by: + cat /var/lib/shellbook/setup-token + Alternative password CLI (hidden prompt): runuser -u shellbook -- env SHELLBOOK_DATA_DIR=/var/lib/shellbook node /opt/shellbook/apps/server/dist/cli/set-password.js 2. Log into Claude as the service user: runuser -l shellbook -c '/home/shellbook/.local/bin/claude' diff --git a/docs/spec.md b/docs/spec.md index 3c0ef21..ed0f965 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -157,9 +157,24 @@ only, then removed. ## 7. Security - The app can run commands on every host → treat access as root-equivalent. -- Built-in login: one password (scrypt hash in config), session cookie signed with a - secret persisted on disk → **logins survive restarts**. Optional: trust a - forward-auth header from Traefik instead. +- Built-in login: one scrypt password hash in `auth.json`; session cookies are HMAC + signed with a persisted mode-0600 secret and bound to the current password hash. + Logins survive restarts; changing the password invalidates other cookies. +- First run creates a random mode-0600 `setup-token` in the data directory. Only its + path is logged. Public GET `/api/auth/setup` reports whether setup is needed; + POST requires the token (constant-time comparison), matching passwords of at + least 12 characters (maximum 4096 bytes), and consumes the token once. Configured + instances reject setup with 409. Setup and login share a per-IP rate limit. +- Settings changes require the current password, or atomically rotate the signing + secret to sign out all sessions. Both issue a fresh cookie to the current browser + and close existing WebSockets; future connections must authenticate again. + Forward-auth identities remain governed by the upstream proxy. +- Every API route is authenticated except exact health, login, and setup paths; + the origin check also covers those exceptions and WebSocket upgrades. + Optional forward-auth headers are accepted only from configured trusted peers. +- Claude status executes only `claude --version` with argv, timeout, and output limit. + Login status checks only the existence of `~/.claude/.credentials.json` under the + service user home; credential contents are never read or returned. - Listens on `127.0.0.1` or LAN; intended behind Traefik + firewall (LAN/Tailscale only). - Terminal panel = shell as the service user: same trust level as the app itself. - No secrets in notebooks, audit log or artifacts metadata. diff --git a/packages/core/src/protocol.ts b/packages/core/src/protocol.ts index c32a806..d424ca7 100644 --- a/packages/core/src/protocol.ts +++ b/packages/core/src/protocol.ts @@ -126,3 +126,12 @@ export type ServerEvent = export type TerminalClientMessage = | { type: "input"; data: string } | { type: "resize"; cols: number; rows: number }; + +// Settings and first-run setup (#10). Only GET/POST /auth/setup is public. +export interface SetupStatusResponse { required: boolean } +export interface NewPasswordRequest { newPassword: string; confirmPassword: string } +export interface SetupRequest extends NewPasswordRequest { token: string } +export interface ChangePasswordRequest extends NewPasswordRequest { currentPassword: string } +export interface SessionSettingsResponse { lifetimeSeconds: number } +export interface ClaudeStatusResponse { available: boolean; version: string | null; loginAppearsPresent: boolean } +export interface SystemInfoResponse { version: string; workspacePath: string; dataDirPath: string; nodeVersion: string }