Merge branch 't3/settings-first-run-setup'
This commit is contained in:
@@ -8,4 +8,6 @@
|
|||||||
- [2026-11-16] **Secrets on SSH:** exported via `export NAME=<shellQuote>` lines on stdin before the script (sshd AcceptEnv unreliable); redacted from streamed output, captures and audit.
|
- [2026-11-16] **Secrets on SSH:** exported via `export NAME=<shellQuote>` 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] **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
|
## Archive
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
- Notebooks stay plain, readable Markdown.
|
- Notebooks stay plain, readable Markdown.
|
||||||
|
|
||||||
## Table of Contents
|
## 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
|
- `attempts.md` — 2 entries — marimo + marimo-pair trial and why it was dropped
|
||||||
- `open.md` — 2 entries — open design questions
|
- `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)
|
- `gotchas.md` — 5 entries — integration foot-guns (CRLF scripts, host-key event order, tmux vs systemd, env names)
|
||||||
|
|||||||
@@ -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;
|
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
|
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.
|
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.
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { registerSettings } from "./settings";
|
||||||
import Fastify, { type FastifyInstance } from "fastify";
|
import Fastify, { type FastifyInstance } from "fastify";
|
||||||
import websocket from "@fastify/websocket";
|
import websocket from "@fastify/websocket";
|
||||||
import { loadConfig, type ServerConfig } from "./config";
|
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 hub = options.events ?? new EventsHub();
|
||||||
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
|
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
|
||||||
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
||||||
|
await registerSettings(app, config);
|
||||||
await app.register(websocket);
|
await app.register(websocket);
|
||||||
await app.register(workspacePlugin, { config });
|
await app.register(workspacePlugin, { config });
|
||||||
await app.register(runsPlugin, { config, hub });
|
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 type { FastifyInstance } from "fastify";
|
||||||
import { readPasswordHash, verifyPassword } from "./credentials";
|
import { readPasswordHash, verifyPassword, setPassword } from "./credentials";
|
||||||
import { loadSessionSecret, signSession, verifySession } from "./session";
|
import { loadSessionSecret, signSession, verifySession, rotateSessionSecret } from "./session";
|
||||||
|
|
||||||
export interface AuthOptions {
|
export interface AuthOptions {
|
||||||
dataDir: string;
|
dataDir: string;
|
||||||
@@ -12,7 +14,17 @@ export interface AuthOptions {
|
|||||||
}
|
}
|
||||||
const normalizeIp = (ip: string) => ip.replace(/^::ffff:/, "");
|
const normalizeIp = (ip: string) => ip.replace(/^::ffff:/, "");
|
||||||
export async function registerAuth(app: FastifyInstance, options: AuthOptions): Promise<void> {
|
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;
|
const maxAge = options.sessionMaxAgeSeconds ?? 30 * 86400;
|
||||||
if (!Number.isSafeInteger(maxAge) || maxAge <= 0) throw new Error("Invalid session lifetime");
|
if (!Number.isSafeInteger(maxAge) || maxAge <= 0) throw new Error("Invalid session lifetime");
|
||||||
const failures = new Map<string, { count: number; until: number }>();
|
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" }); }
|
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" }); }
|
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 forward = options.forwardAuth;
|
||||||
const peer = normalizeIp(request.raw.socket?.remoteAddress ?? "");
|
const peer = normalizeIp(request.raw.socket?.remoteAddress ?? "");
|
||||||
if (forward && forward.trustedProxyIps.some(ip => normalizeIp(ip) === peer)) {
|
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;
|
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);
|
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();
|
const now = Date.now();
|
||||||
for (const [key, value] of failures) if (value.until <= now) failures.delete(key);
|
for (const [key, value] of failures) if (value.until <= now) failures.delete(key);
|
||||||
const ip = request.ip;
|
|
||||||
const entry = failures.get(ip);
|
const entry = failures.get(ip);
|
||||||
if ((entry?.count ?? 0) >= (options.maxAttempts ?? 5) || (!entry && failures.size >= 10000)) {
|
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" });
|
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.
|
// 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) });
|
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 password = (request.body as { password?: unknown } | null)?.password;
|
||||||
const hash = await readPasswordHash(options.dataDir);
|
const hash = await readPasswordHash(options.dataDir);
|
||||||
if (typeof password !== "string" || !hash || !await verifyPassword(password, hash)) return reply.code(401).send({ error: "Invalid credentials" });
|
if (typeof password !== "string" || !hash || !await verifyPassword(password, hash)) return reply.code(401).send({ error: "Invalid credentials" });
|
||||||
failures.delete(ip);
|
failures.delete(request.ip);
|
||||||
return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(secret, now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send();
|
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.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 }));
|
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 { 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";
|
import { join } from "node:path";
|
||||||
|
|
||||||
export function loadSessionSecret(dataDir: string): Buffer {
|
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]!;
|
const expected = signSession(secret, Number(payload)).split(".")[1]!;
|
||||||
return Number(payload) > now && timingSafeEqual(Buffer.from(mac!), Buffer.from(expected));
|
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -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, unknown> }) =>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
});
|
||||||
+18
-3
@@ -1,3 +1,7 @@
|
|||||||
|
import { HeaderNavigation, type NavigationPage } from "./HeaderNavigation";
|
||||||
|
import { SettingsPage } from "./SettingsPage";
|
||||||
|
import { SetupScreen } from "./SetupScreen";
|
||||||
|
import { settingsApi } from "./settingsApi";
|
||||||
import {
|
import {
|
||||||
lazy,
|
lazy,
|
||||||
Suspense,
|
Suspense,
|
||||||
@@ -46,7 +50,8 @@ function steps(blocks: Block[]): Step[] {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
export function App({ api }: { api: Api }) {
|
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<NavigationPage>("Notebooks");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [list, setList] = useState<NotebookSummary[]>([]);
|
const [list, setList] = useState<NotebookSummary[]>([]);
|
||||||
const [hosts, setHosts] = useState<HostInfo[]>([]);
|
const [hosts, setHosts] = useState<HostInfo[]>([]);
|
||||||
@@ -103,8 +108,12 @@ export function App({ api }: { api: Api }) {
|
|||||||
.me()
|
.me()
|
||||||
.then(() => setAuth("ready"))
|
.then(() => setAuth("ready"))
|
||||||
.catch((e) => {
|
.catch((e) => {
|
||||||
if (e instanceof HttpError && e.status === 401) setAuth("login");
|
if (e instanceof HttpError && e.status === 401) {
|
||||||
else setError(String(e));
|
setAuth("login");
|
||||||
|
void settingsApi.setupStatus()
|
||||||
|
.then(status => { if (status.required) setAuth("setup"); })
|
||||||
|
.catch(() => {});
|
||||||
|
} else setError(String(e));
|
||||||
});
|
});
|
||||||
}, [api]);
|
}, [api]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -281,6 +290,7 @@ export function App({ api }: { api: Api }) {
|
|||||||
const keyPrompt = Object.values(session.runs).find(
|
const keyPrompt = Object.values(session.runs).find(
|
||||||
(run) => run.status === "hostKey" && requests.current.has(run.runId),
|
(run) => run.status === "hostKey" && requests.current.has(run.runId),
|
||||||
);
|
);
|
||||||
|
if (auth === "setup") return <SetupScreen onComplete={() => setAuth("ready")} />;
|
||||||
if (auth === "login")
|
if (auth === "login")
|
||||||
return (
|
return (
|
||||||
<main className="login">
|
<main className="login">
|
||||||
@@ -347,6 +357,10 @@ export function App({ api }: { api: Api }) {
|
|||||||
</small>
|
</small>
|
||||||
</aside>
|
</aside>
|
||||||
<main>
|
<main>
|
||||||
|
<HeaderNavigation page={page} onChange={setPage} />
|
||||||
|
{page === "Settings" && <SettingsPage openTerminal={() => { setTerminalOpened(true); setTerminal(true); }} />}
|
||||||
|
{page === "Hosts" && <p>Host management will appear here.</p>}
|
||||||
|
<div hidden={page !== "Notebooks"}>
|
||||||
<div className="toolbar">
|
<div className="toolbar">
|
||||||
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
|
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
|
||||||
<button onClick={() => setEdit(!edit)}>
|
<button onClick={() => setEdit(!edit)}>
|
||||||
@@ -468,6 +482,7 @@ export function App({ api }: { api: Api }) {
|
|||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
</div>
|
||||||
</main>
|
</main>
|
||||||
{terminalOpened && (
|
{terminalOpened && (
|
||||||
<Suspense fallback={<p>Loading terminal...</p>}>
|
<Suspense fallback={<p>Loading terminal...</p>}>
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<nav aria-label="Main navigation">
|
||||||
|
{navigationItems.map((item) => (
|
||||||
|
<button
|
||||||
|
key={item}
|
||||||
|
aria-current={page === item ? "page" : undefined}
|
||||||
|
onClick={() => onChange(item)}
|
||||||
|
>
|
||||||
|
{item}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<void>;
|
||||||
|
}) {
|
||||||
|
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 (
|
||||||
|
<form
|
||||||
|
onSubmit={async (event) => {
|
||||||
|
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 ? (
|
||||||
|
<label>
|
||||||
|
Setup token
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
autoComplete="off"
|
||||||
|
value={token}
|
||||||
|
onChange={(e) => setToken(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
) : (
|
||||||
|
<label>
|
||||||
|
Current password
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={currentPassword}
|
||||||
|
onChange={(e) => setCurrent(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<label>
|
||||||
|
New password
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
type="password"
|
||||||
|
minLength={12}
|
||||||
|
autoComplete="new-password"
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(e) => setNew(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Confirm password
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
type="password"
|
||||||
|
minLength={12}
|
||||||
|
autoComplete="new-password"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(e) => setConfirm(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<p>Use at least 12 characters (maximum 4096 bytes).</p>
|
||||||
|
<button disabled={busy}>
|
||||||
|
{setup ? "Set up ShellBook" : "Change password"}
|
||||||
|
</button>
|
||||||
|
{message && <p role="status">{message}</p>}
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<SystemInfoResponse>();
|
||||||
|
const [claude, setClaude] = useState<ClaudeStatusResponse>();
|
||||||
|
const [session, setSession] = useState<SessionSettingsResponse>();
|
||||||
|
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 (
|
||||||
|
<div className="notebook">
|
||||||
|
<h1>Settings</h1>
|
||||||
|
<section>
|
||||||
|
<h2>Password and sessions</h2>
|
||||||
|
<PasswordForm submit={settingsApi.password} />
|
||||||
|
{session && (
|
||||||
|
<p>
|
||||||
|
Session lifetime: {session.lifetimeSeconds} seconds (
|
||||||
|
{session.lifetimeSeconds / 86400} days).
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
disabled={busy}
|
||||||
|
onClick={async () => {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await settingsApi.revoke();
|
||||||
|
setMessage(
|
||||||
|
"Other sessions signed out. This browser remains signed in.",
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
setMessage("Unable to sign out sessions. Try again.");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Sign out all sessions
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>Claude CLI</h2>
|
||||||
|
{claude ? (
|
||||||
|
<>
|
||||||
|
<p>
|
||||||
|
{claude.available
|
||||||
|
? `Available: ${claude.version}`
|
||||||
|
: "Claude is unavailable on PATH or did not respond."}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
{claude.loginAppearsPresent
|
||||||
|
? "Credentials file exists; login may be available."
|
||||||
|
: "No credentials file found."}
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<p>Checking CLI...</p>
|
||||||
|
)}
|
||||||
|
<button onClick={openTerminal}>Open terminal to log in</button>
|
||||||
|
<p>
|
||||||
|
Run <code>claude</code>, then <code>/login</code>. Credentials are
|
||||||
|
checked for existence only.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
<section>
|
||||||
|
<h2>About/System</h2>
|
||||||
|
{info && (
|
||||||
|
<dl>
|
||||||
|
<dt>ShellBook version</dt>
|
||||||
|
<dd>{info.version}</dd>
|
||||||
|
<dt>Workspace</dt>
|
||||||
|
<dd>{info.workspacePath}</dd>
|
||||||
|
<dt>Data directory</dt>
|
||||||
|
<dd>{info.dataDirPath}</dd>
|
||||||
|
<dt>Node version</dt>
|
||||||
|
<dd>{info.nodeVersion}</dd>
|
||||||
|
</dl>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
{message && <p role="status">{message}</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { PasswordForm } from "./PasswordForm";
|
||||||
|
import { settingsApi } from "./settingsApi";
|
||||||
|
export function SetupScreen({ onComplete }: { onComplete: () => void }) {
|
||||||
|
return (
|
||||||
|
<main className="login">
|
||||||
|
<h1>Set up ShellBook</h1>
|
||||||
|
<p>
|
||||||
|
Enter the one-time token from the setup-token file in the server data
|
||||||
|
directory.
|
||||||
|
</p>
|
||||||
|
<PasswordForm
|
||||||
|
setup
|
||||||
|
submit={async (body) => {
|
||||||
|
await settingsApi.setup(body);
|
||||||
|
onComplete();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import type {
|
||||||
|
SetupStatusResponse,
|
||||||
|
SetupRequest,
|
||||||
|
ChangePasswordRequest,
|
||||||
|
SessionSettingsResponse,
|
||||||
|
ClaudeStatusResponse,
|
||||||
|
SystemInfoResponse,
|
||||||
|
} from "@shellbook/core";
|
||||||
|
import { HttpError } from "./api";
|
||||||
|
async function request<T>(path: string, body?: unknown): Promise<T> {
|
||||||
|
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<T>);
|
||||||
|
}
|
||||||
|
export const settingsApi = {
|
||||||
|
setupStatus: () => request<SetupStatusResponse>("/auth/setup"),
|
||||||
|
setup: (body: SetupRequest) => request<void>("/auth/setup", body),
|
||||||
|
password: (body: ChangePasswordRequest) =>
|
||||||
|
request<void>("/settings/password", body),
|
||||||
|
revoke: () => request<void>("/settings/sessions/revoke", {}),
|
||||||
|
session: () => request<SessionSettingsResponse>("/settings/session"),
|
||||||
|
claude: () => request<ClaudeStatusResponse>("/settings/claude"),
|
||||||
|
system: () => request<SystemInfoResponse>("/settings/system"),
|
||||||
|
};
|
||||||
@@ -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(<PasswordForm setup submit={submit} />);
|
||||||
|
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(<SetupScreen onComplete={done} />);
|
||||||
|
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(
|
||||||
|
<PasswordForm submit={vi.fn().mockRejectedValue(new Error("invalid"))} />,
|
||||||
|
);
|
||||||
|
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(<SettingsPage openTerminal={open} />);
|
||||||
|
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(<HeaderNavigation page="Notebooks" onChange={change} />);
|
||||||
|
fireEvent.click(screen.getByText("Settings"));
|
||||||
|
expect(change).toHaveBeenCalledWith("Settings");
|
||||||
|
expect(screen.getByText("Hosts")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Notebooks")).toHaveAttribute("aria-current", "page");
|
||||||
|
});
|
||||||
+12
-5
@@ -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),
|
`SHELLBOOK_PORT`, `SHELLBOOK_TRUSTED_PROXIES` (comma-separated proxy IPs),
|
||||||
and `TS_AUTHKEY` in the host environment. Auth keys are transferred in a
|
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.
|
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
|
3. Open ShellBook in your browser. In the CT run `cat /var/lib/shellbook/setup-token`
|
||||||
line on stdin; do not pass passwords as arguments. Source-checkout command:
|
and enter the token with a new password (at least 12 characters) in the setup screen.
|
||||||
`SHELLBOOK_DATA_DIR=/var/lib/shellbook pnpm --filter @shellbook/server set-password`.
|
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
|
4. Run `claude` as shellbook and use `/login`. Authorize
|
||||||
`/home/shellbook/.ssh/id_ed25519.pub` on managed hosts. The service user has
|
`/home/shellbook/.ssh/id_ed25519.pub` on managed hosts. The service user has
|
||||||
no sudo access. Initialize notebooks manually if templates were absent.
|
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
|
Configuration is `/etc/shellbook/env`; data is `/var/lib/shellbook` (back it up
|
||||||
along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults
|
along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults
|
||||||
to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie;
|
to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie;
|
||||||
password changes do not revoke existing cookies. For emergency revocation stop
|
Settings supports changing the password and signing out all sessions; both revoke
|
||||||
the service, delete `session-secret` from the data directory and start it again.
|
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
|
Forward auth is off by default. To enable it set
|
||||||
`SHELLBOOK_FORWARD_AUTH_HEADER=Remote-User` and trusted proxy IPs. The header is
|
`SHELLBOOK_FORWARD_AUTH_HEADER=Remote-User` and trusted proxy IPs. The header is
|
||||||
|
|||||||
+3
-1
@@ -122,7 +122,9 @@ systemctl enable shellbook
|
|||||||
systemctl restart shellbook
|
systemctl restart shellbook
|
||||||
cat <<'EOF'
|
cat <<'EOF'
|
||||||
Next steps:
|
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
|
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:
|
2. Log into Claude as the service user:
|
||||||
runuser -l shellbook -c '/home/shellbook/.local/bin/claude'
|
runuser -l shellbook -c '/home/shellbook/.local/bin/claude'
|
||||||
|
|||||||
+18
-3
@@ -157,9 +157,24 @@ only, then removed.
|
|||||||
## 7. Security
|
## 7. Security
|
||||||
|
|
||||||
- The app can run commands on every host → treat access as root-equivalent.
|
- 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
|
- Built-in login: one scrypt password hash in `auth.json`; session cookies are HMAC
|
||||||
secret persisted on disk → **logins survive restarts**. Optional: trust a
|
signed with a persisted mode-0600 secret and bound to the current password hash.
|
||||||
forward-auth header from Traefik instead.
|
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).
|
- 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.
|
- Terminal panel = shell as the service user: same trust level as the app itself.
|
||||||
- No secrets in notebooks, audit log or artifacts metadata.
|
- No secrets in notebooks, audit log or artifacts metadata.
|
||||||
|
|||||||
@@ -126,3 +126,12 @@ export type ServerEvent =
|
|||||||
export type TerminalClientMessage =
|
export type TerminalClientMessage =
|
||||||
| { type: "input"; data: string }
|
| { type: "input"; data: string }
|
||||||
| { type: "resize"; cols: number; rows: number };
|
| { 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 }
|
||||||
|
|||||||
Reference in New Issue
Block a user