Merge branch 't3/implement-auth-deploy'
Integrate auth, config, watcher and terminal wiring in buildApp: auth guards every API route by default, notebook watcher events feed the /api/events hub, the terminal runs in the configured workspace, and SHELLBOOK_DATA_DIR is the single data directory variable. The systemd unit uses KillMode=process so tmux sessions survive service restarts.
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
`buildApp({ config: { workspaceDir, dataDir, sshKeyPath }, events })` accepts
|
||||
overrides for tests and embedding. Defaults come from `SHELLBOOK_WORKSPACE`
|
||||
(`workspace`), `SHELLBOOK_DATA` (`data`), and `SHELLBOOK_SSH_KEY`
|
||||
(`workspace`), `SHELLBOOK_DATA_DIR` (`data`), and `SHELLBOOK_SSH_KEY`
|
||||
(`data/id_ed25519`). Paths resolve against the service working directory.
|
||||
|
||||
The workspace contains `notebooks/**/*.md`, `hosts.yaml`, and `known_hosts`.
|
||||
|
||||
@@ -5,11 +5,14 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/main.ts",
|
||||
"build": "tsc -p tsconfig.json --noEmit",
|
||||
"build": "esbuild src/main.ts src/cli/set-password.ts --bundle --platform=node --target=node22 --format=esm --packages=external --outdir=dist --outbase=src --external:node-pty --alias:@shellbook/core=../../packages/core/src/index.ts",
|
||||
"start": "node dist/main.js",
|
||||
"set-password": "tsx src/cli/set-password.ts",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run --passWithNoTests"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/static": "^8.0.0",
|
||||
"@fastify/websocket": "^11.0.1",
|
||||
"@shellbook/core": "workspace:*",
|
||||
"fastify": "^5.1.0",
|
||||
@@ -21,6 +24,7 @@
|
||||
"devDependencies": {
|
||||
"@types/ssh2": "^1.15.6",
|
||||
"@types/ws": "^8.18.2",
|
||||
"esbuild": "^0.24.2",
|
||||
"tsx": "^4.19.2"
|
||||
}
|
||||
}
|
||||
|
||||
+37
-9
@@ -3,28 +3,56 @@ import websocket from "@fastify/websocket";
|
||||
import { loadConfig, type ServerConfig } from "./config";
|
||||
import { workspacePlugin } from "./workspace";
|
||||
import { runsPlugin, EventsHub } from "./runs";
|
||||
import { terminalPlugin, type TerminalOptions } from "./terminal";
|
||||
import { createNotebookWatcher } from "./watch";
|
||||
import { registerAuth, type AuthOptions } from "./auth";
|
||||
import { registerStatic } from "./static";
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: boolean;
|
||||
config?: Partial<ServerConfig>;
|
||||
events?: EventsHub;
|
||||
/**
|
||||
* Login protection for all /api routes. Enabled by default with `config.dataDir`.
|
||||
* `false` exists only for tests that exercise other plugins in isolation.
|
||||
*/
|
||||
auth?: Partial<AuthOptions> | false;
|
||||
trustProxy?: string[];
|
||||
/** Built web app (apps/web/dist); served only when it contains index.html. */
|
||||
staticDir?: string;
|
||||
/** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */
|
||||
watchNotebooks?: boolean;
|
||||
terminal?: Omit<TerminalOptions, "workspaceDir">;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the Fastify app. Feature areas live in their own folders and are
|
||||
* registered here as Fastify plugins, one line each:
|
||||
* M2 src/workspace/ (notebooks, hosts.yaml), src/ssh/, src/runs/ (queue, audit, artifacts, /api/events)
|
||||
* M4 src/terminal/ (node-pty + tmux, /api/terminal), src/watch/ (file.changed events)
|
||||
* M5 src/auth/ (login, persistent session secret)
|
||||
* Builds the Fastify app. Feature areas live in their own folders:
|
||||
* src/auth/ login, persistent session secret (registered first: its hook guards every /api route)
|
||||
* src/workspace/ notebooks, hosts.yaml; src/ssh/, src/runs/ queue, audit, artifacts, /api/events
|
||||
* src/terminal/ node-pty + tmux, /api/terminal; src/watch/ file.changed events into the events hub
|
||||
* src/static/ built web app with SPA fallback
|
||||
*/
|
||||
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
|
||||
const app = Fastify({ logger: options.logger ?? false });
|
||||
const config = loadConfig(options.config);
|
||||
const hub = options.events ?? new EventsHub();
|
||||
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
|
||||
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
||||
await app.register(websocket);
|
||||
await app.register(workspacePlugin, { config: loadConfig(options.config) });
|
||||
await app.register(runsPlugin, { config: loadConfig(options.config), hub: options.events ?? new EventsHub() });
|
||||
await app.register((await import("./terminal/index")).terminalPlugin);
|
||||
await app.register(workspacePlugin, { config });
|
||||
await app.register(runsPlugin, { config, hub });
|
||||
await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir });
|
||||
|
||||
if (options.watchNotebooks) {
|
||||
const watcher = createNotebookWatcher(config.workspaceDir, {
|
||||
onError: error => app.log.error({ err: error }, "notebook watcher error"),
|
||||
});
|
||||
watcher.on(event => hub.publish(event));
|
||||
app.addHook("onClose", async () => { await watcher.close(); });
|
||||
await watcher.ready;
|
||||
}
|
||||
|
||||
app.get("/api/health", async () => ({ ok: true }));
|
||||
if (options.staticDir) await registerStatic(app, options.staticDir);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { randomBytes, scrypt as derive, timingSafeEqual } from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
const scrypt = promisify(derive);
|
||||
export async function hashPassword(password: string): Promise<string> {
|
||||
if (!password || Buffer.byteLength(password) > 4096) throw new Error("Password must contain 1–4096 bytes");
|
||||
const salt = randomBytes(32).toString("hex");
|
||||
const hash = await scrypt(password, salt, 64) as Buffer;
|
||||
return `scrypt:${salt}:${hash.toString("hex")}`;
|
||||
}
|
||||
export async function verifyPassword(password: string, encoded: string): Promise<boolean> {
|
||||
if (!password || Buffer.byteLength(password) > 4096 || !/^scrypt:[a-f0-9]{64}:[a-f0-9]{128}$/.test(encoded)) return false;
|
||||
const [, salt, hash] = encoded.split(":");
|
||||
const actual = await scrypt(password, salt!, 64) as Buffer;
|
||||
return timingSafeEqual(actual, Buffer.from(hash!, "hex"));
|
||||
}
|
||||
export async function readPasswordHash(dataDir: string): Promise<string | undefined> {
|
||||
try { return (JSON.parse(await readFile(join(dataDir, "auth.json"), "utf8")) as { passwordHash: string }).passwordHash; }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw error; }
|
||||
}
|
||||
export async function setPassword(dataDir: string, password: string): Promise<void> {
|
||||
const passwordHash = await hashPassword(password);
|
||||
await mkdir(dataDir, { recursive: true, mode: 0o700 });
|
||||
const temp = join(dataDir, `auth.${randomBytes(8).toString("hex")}.tmp`);
|
||||
await writeFile(temp, JSON.stringify({ passwordHash }) + "\n", { mode: 0o600, flag: "wx" });
|
||||
await rename(temp, join(dataDir, "auth.json"));
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { readPasswordHash, verifyPassword } from "./credentials";
|
||||
import { loadSessionSecret, signSession, verifySession } from "./session";
|
||||
|
||||
export interface AuthOptions {
|
||||
dataDir: string;
|
||||
sessionMaxAgeSeconds?: number;
|
||||
forwardAuth?: { header: string; trustedProxyIps: string[] };
|
||||
/** Failed attempts permitted per IP per window. */
|
||||
maxAttempts?: number;
|
||||
rateWindowMs?: number;
|
||||
}
|
||||
const normalizeIp = (ip: string) => ip.replace(/^::ffff:/, "");
|
||||
export async function registerAuth(app: FastifyInstance, options: AuthOptions): Promise<void> {
|
||||
const secret = loadSessionSecret(options.dataDir);
|
||||
const maxAge = options.sessionMaxAgeSeconds ?? 30 * 86400;
|
||||
if (!Number.isSafeInteger(maxAge) || maxAge <= 0) throw new Error("Invalid session lifetime");
|
||||
const failures = new Map<string, { count: number; until: number }>();
|
||||
const cookie = (value: string, secure: boolean, age: number) =>
|
||||
`shellbook_session=${value}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${age}${secure ? "; Secure" : ""}`;
|
||||
app.addHook("onRequest", async (request, reply) => {
|
||||
const path = request.url.split("?")[0]!;
|
||||
if (!(path === "/api" || path.startsWith("/api/"))) return;
|
||||
// Also protect cookie-bearing WebSocket upgrades against cross-site requests.
|
||||
const origin = request.headers.origin;
|
||||
if (origin) {
|
||||
try { if (new URL(origin).host !== request.headers.host) return reply.code(403).send({ error: "Origin rejected" }); }
|
||||
catch { return reply.code(403).send({ error: "Origin rejected" }); }
|
||||
}
|
||||
if (path === "/api/health" || path === "/api/auth/login") return;
|
||||
const forward = options.forwardAuth;
|
||||
const peer = normalizeIp(request.raw.socket?.remoteAddress ?? "");
|
||||
if (forward && forward.trustedProxyIps.some(ip => normalizeIp(ip) === peer)) {
|
||||
const user = request.headers[forward.header.toLowerCase()];
|
||||
if (typeof user === "string" && user.trim()) return;
|
||||
}
|
||||
const token = request.headers.cookie?.split(";").map(part => part.trim()).find(part => part.startsWith("shellbook_session="))?.slice("shellbook_session=".length);
|
||||
if (!token || !verifySession(secret, token)) return reply.code(401).send({ error: "Authentication required" });
|
||||
});
|
||||
app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => {
|
||||
const now = Date.now();
|
||||
for (const [key, value] of failures) if (value.until <= now) failures.delete(key);
|
||||
const ip = request.ip;
|
||||
const entry = failures.get(ip);
|
||||
if ((entry?.count ?? 0) >= (options.maxAttempts ?? 5) || (!entry && failures.size >= 10000)) {
|
||||
return reply.header("Retry-After", String(Math.max(1, Math.ceil(((entry?.until ?? now + 60000) - now) / 1000)))).code(429).send({ error: "Try again later" });
|
||||
}
|
||||
// Reserve before scrypt awaits, so parallel attempts cannot bypass the limit.
|
||||
failures.set(ip, { count: (entry?.count ?? 0) + 1, until: entry?.until ?? now + (options.rateWindowMs ?? 60000) });
|
||||
const password = (request.body as { password?: unknown } | null)?.password;
|
||||
const hash = await readPasswordHash(options.dataDir);
|
||||
if (typeof password !== "string" || !hash || !await verifyPassword(password, hash)) return reply.code(401).send({ error: "Invalid credentials" });
|
||||
failures.delete(ip);
|
||||
return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(secret, now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send();
|
||||
});
|
||||
app.post("/api/auth/logout", async (request, reply) => reply.header("Set-Cookie", cookie("", request.protocol === "https", 0)).code(204).send());
|
||||
app.get("/api/auth/me", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ authenticated: true }));
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function loadSessionSecret(dataDir: string): Buffer {
|
||||
mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
||||
const path = join(dataDir, "session-secret");
|
||||
try { writeFileSync(path, randomBytes(32), { flag: "wx", mode: 0o600 }); }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
|
||||
const secret = readFileSync(path);
|
||||
if (secret.length !== 32) throw new Error("Invalid session-secret (expected 32 bytes)");
|
||||
chmodSync(path, 0o600);
|
||||
return secret;
|
||||
}
|
||||
export function signSession(secret: Buffer, expiresAt: number): string {
|
||||
const payload = String(expiresAt);
|
||||
return `${payload}.${createHmac("sha256", secret).update(payload).digest("base64url")}`;
|
||||
}
|
||||
export function verifySession(secret: Buffer, cookie: string, now = Date.now()): boolean {
|
||||
if (!/^\d{1,16}\.[A-Za-z0-9_-]{43}$/.test(cookie)) return false;
|
||||
const [payload, mac] = cookie.split(".");
|
||||
const expected = signSession(secret, Number(payload)).split(".")[1]!;
|
||||
return Number(payload) > now && timingSafeEqual(Buffer.from(mac!), Buffer.from(expected));
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { setPassword } from "../auth/credentials";
|
||||
|
||||
// TTY input is hidden; piped input is a single line (never a command-line argument).
|
||||
async function readPassword(): Promise<string> {
|
||||
if (!process.stdin.isTTY) {
|
||||
const reader = createInterface({ input: process.stdin });
|
||||
try { for await (const line of reader) return line; return ""; }
|
||||
finally { reader.close(); }
|
||||
}
|
||||
process.stderr.write("New ShellBook password: ");
|
||||
process.stdin.setRawMode(true);
|
||||
process.stdin.resume();
|
||||
process.stdin.setEncoding("utf8");
|
||||
return new Promise((resolvePassword, reject) => {
|
||||
let password = "";
|
||||
const onData = (chunk: string) => {
|
||||
for (const char of chunk) {
|
||||
if (char === "\r" || char === "\n" || char === "\u0003") {
|
||||
process.stdin.off("data", onData);
|
||||
process.stdin.setRawMode(false);
|
||||
process.stdin.pause();
|
||||
process.stderr.write("\n");
|
||||
if (char === "\u0003") reject(new Error("Cancelled")); else resolvePassword(password);
|
||||
return;
|
||||
}
|
||||
if (char === "\u007f" || char === "\b") password = password.slice(0, -1);
|
||||
else password += char;
|
||||
}
|
||||
};
|
||||
process.stdin.on("data", onData);
|
||||
});
|
||||
}
|
||||
await setPassword(resolve(process.env.SHELLBOOK_DATA_DIR ?? "data"), await readPassword());
|
||||
console.log("Password saved. Existing sessions remain valid until expiry.");
|
||||
@@ -9,7 +9,7 @@ export interface ServerConfig {
|
||||
export function loadConfig(overrides: Partial<ServerConfig> = {}): ServerConfig {
|
||||
return {
|
||||
workspaceDir: path.resolve(overrides.workspaceDir ?? process.env.SHELLBOOK_WORKSPACE ?? "workspace"),
|
||||
dataDir: path.resolve(overrides.dataDir ?? process.env.SHELLBOOK_DATA ?? "data"),
|
||||
dataDir: path.resolve(overrides.dataDir ?? process.env.SHELLBOOK_DATA_DIR ?? "data"),
|
||||
sshKeyPath: path.resolve(overrides.sshKeyPath ?? process.env.SHELLBOOK_SSH_KEY ?? "data/id_ed25519"),
|
||||
};
|
||||
}
|
||||
|
||||
+17
-1
@@ -1,7 +1,23 @@
|
||||
import { buildApp } from "./app";
|
||||
import { loadConfig } from "./config";
|
||||
|
||||
const host = process.env.SHELLBOOK_HOST ?? "127.0.0.1";
|
||||
const port = Number(process.env.SHELLBOOK_PORT ?? 8080);
|
||||
|
||||
const app = await buildApp({ logger: true });
|
||||
const proxies = process.env.SHELLBOOK_TRUSTED_PROXIES?.split(",").map(ip => ip.trim()).filter(Boolean) ?? [];
|
||||
const config = loadConfig();
|
||||
const app = await buildApp({
|
||||
logger: true,
|
||||
config,
|
||||
trustProxy: proxies,
|
||||
staticDir: process.env.SHELLBOOK_STATIC_DIR,
|
||||
watchNotebooks: true,
|
||||
auth: {
|
||||
sessionMaxAgeSeconds: Number(process.env.SHELLBOOK_SESSION_SECONDS ?? 2592000),
|
||||
forwardAuth: process.env.SHELLBOOK_FORWARD_AUTH_HEADER ? {
|
||||
header: process.env.SHELLBOOK_FORWARD_AUTH_HEADER,
|
||||
trustedProxyIps: proxies,
|
||||
} : undefined,
|
||||
},
|
||||
});
|
||||
await app.listen({ host, port });
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import fastifyStatic from "@fastify/static";
|
||||
|
||||
export async function registerStatic(app: FastifyInstance, directory: string): Promise<void> {
|
||||
const root = resolve(directory);
|
||||
if (!existsSync(resolve(root, "index.html"))) return;
|
||||
await app.register(fastifyStatic, { root, wildcard: false });
|
||||
app.setNotFoundHandler((request, reply) => {
|
||||
const path = request.url.split("?")[0]!;
|
||||
if (path === "/api" || path.startsWith("/api/") || !["GET", "HEAD"].includes(request.method)) return reply.code(404).send({ error: "Not found" });
|
||||
return reply.type("text/html").sendFile("index.html");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp, type AppOptions } from "../src/app";
|
||||
import type { AuthOptions } from "../src/auth";
|
||||
import { hashPassword, setPassword, verifyPassword } from "../src/auth/credentials";
|
||||
import { loadSessionSecret, signSession, verifySession } from "../src/auth/session";
|
||||
|
||||
const dirs: string[] = [];
|
||||
const apps: FastifyInstance[] = [];
|
||||
async function directory() { const dir = await mkdtemp(join(tmpdir(), "shellbook-auth-")); dirs.push(dir); return dir; }
|
||||
async function setup(options: AppOptions & { auth?: Partial<AuthOptions> } = {}) {
|
||||
const dataDir = options.auth?.dataDir ?? await directory();
|
||||
await setPassword(dataDir, "test password");
|
||||
const app = await buildApp({ ...options, auth: { dataDir, ...options.auth } });
|
||||
apps.push(app);
|
||||
app.get("/api/private", async () => ({ ok: true }));
|
||||
app.get("/api/ws", { websocket: true }, socket => { socket.send("authenticated"); });
|
||||
return { app, dataDir };
|
||||
}
|
||||
async function login(app: FastifyInstance, headers = {}) {
|
||||
return app.inject({ method: "POST", url: "/api/auth/login", payload: { password: "test password" }, headers });
|
||||
}
|
||||
afterEach(async () => {
|
||||
for (const app of apps.splice(0)) await app.close();
|
||||
for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
describe("passwords and sessions", () => {
|
||||
it("salts scrypt hashes and compares passwords safely", async () => {
|
||||
const hash = await hashPassword("secret");
|
||||
expect(await hashPassword("secret")).not.toBe(hash);
|
||||
expect(await verifyPassword("secret", hash)).toBe(true);
|
||||
expect(await verifyPassword("wrong", hash)).toBe(false);
|
||||
expect(await verifyPassword("secret", "malformed")).toBe(false);
|
||||
expect(await verifyPassword("x".repeat(4097), hash)).toBe(false);
|
||||
await expect(hashPassword("")).rejects.toThrow();
|
||||
});
|
||||
it("rejects tampering, wrong keys, invalid input and expired cookies", () => {
|
||||
const key = Buffer.alloc(32, 1);
|
||||
const token = signSession(key, 2000);
|
||||
expect(verifySession(key, token, 1000)).toBe(true);
|
||||
expect(verifySession(key, token, 2000)).toBe(false);
|
||||
expect(verifySession(key, token.replace("2000", "3000"), 1000)).toBe(false);
|
||||
expect(verifySession(Buffer.alloc(32, 2), token, 1000)).toBe(false);
|
||||
for (const bad of ["", "x.y", "99999999999999999.a", token + "x"]) expect(verifySession(key, bad, 1000)).toBe(false);
|
||||
});
|
||||
it("persists a private signing secret and rejects corrupt state", async () => {
|
||||
const dir = await directory();
|
||||
expect(loadSessionSecret(dir)).toEqual(loadSessionSecret(dir));
|
||||
if (process.platform !== "win32") expect((await stat(join(dir, "session-secret"))).mode & 0o777).toBe(0o600);
|
||||
await writeFile(join(dir, "session-secret"), "bad");
|
||||
expect(() => loadSessionSecret(dir)).toThrow("Invalid session-secret");
|
||||
});
|
||||
});
|
||||
describe("authentication boundary", () => {
|
||||
it("protects all API paths, including websocket handshakes, and permits health/login", async () => {
|
||||
const { app } = await setup();
|
||||
for (const url of ["/api", "/api/private", "/api/auth/me", "/api/auth/logout", "/api/unknown", "/api/health/", "/api/ws"]) {
|
||||
const response = await app.inject({ method: url.endsWith("logout") ? "POST" : "GET", url, headers: { connection: "Upgrade", upgrade: "websocket" } });
|
||||
expect(response.statusCode, url).toBe(401);
|
||||
}
|
||||
expect((await app.inject("/api/health?check=1")).statusCode).toBe(200);
|
||||
await expect(app.injectWS("/api/ws")).rejects.toThrow("401");
|
||||
expect((await app.inject({ method: "POST", url: "/api/auth/login", payload: { password: "wrong" } })).statusCode).toBe(401);
|
||||
const response = await login(app);
|
||||
expect(response.statusCode).toBe(204);
|
||||
expect(response.headers["set-cookie"]).toContain("HttpOnly; SameSite=Strict; Max-Age=2592000");
|
||||
const cookie = String(response.headers["set-cookie"]).split(";")[0]!;
|
||||
expect((await app.inject({ url: "/api/auth/me", headers: { cookie } })).json()).toEqual({ authenticated: true });
|
||||
const ws = await app.injectWS("/api/ws", { headers: { cookie } });
|
||||
ws.close();
|
||||
const logout = await app.inject({ method: "POST", url: "/api/auth/logout", headers: { cookie } });
|
||||
expect(logout.statusCode).toBe(204);
|
||||
expect(logout.headers["set-cookie"]).toContain("Max-Age=0");
|
||||
});
|
||||
it("survives app restart using the same data directory", async () => {
|
||||
const { app, dataDir } = await setup();
|
||||
const cookie = String((await login(app)).headers["set-cookie"]).split(";")[0]!;
|
||||
await app.close();
|
||||
apps.splice(apps.indexOf(app), 1);
|
||||
const second = await buildApp({ auth: { dataDir } }); apps.push(second);
|
||||
expect((await second.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode).toBe(200);
|
||||
expect(await readFile(join(dataDir, "auth.json"), "utf8")).not.toContain("test password");
|
||||
});
|
||||
it("fails closed without configured password and rejects cross-origin requests", async () => {
|
||||
const app = await buildApp({ auth: { dataDir: await directory() } }); apps.push(app);
|
||||
expect((await login(app)).statusCode).toBe(401);
|
||||
expect((await login(app, { origin: "https://evil.test", host: "shellbook.test" })).statusCode).toBe(403);
|
||||
});
|
||||
it("only trusts HTTPS forwarding from configured proxies", async () => {
|
||||
const { app } = await setup();
|
||||
expect((await login(app, { "x-forwarded-proto": "https" })).headers["set-cookie"]).not.toContain("Secure");
|
||||
const { app: trusted } = await setup({ trustProxy: ["127.0.0.1"] });
|
||||
expect((await login(trusted, { "x-forwarded-proto": "https" })).headers["set-cookie"]).toContain("Secure");
|
||||
const { app: other } = await setup({ trustProxy: ["192.0.2.1"] });
|
||||
expect((await login(other, { "x-forwarded-proto": "https" })).headers["set-cookie"]).not.toContain("Secure");
|
||||
});
|
||||
it("limits parallel failures per IP and permits retry after the window", async () => {
|
||||
const { app } = await setup({ auth: { dataDir: await directory(), maxAttempts: 2, rateWindowMs: 100 } });
|
||||
const attempt = () => app.inject({ method: "POST", url: "/api/auth/login", payload: { password: "wrong" } });
|
||||
const results = await Promise.all([attempt(), attempt(), attempt()]);
|
||||
expect(results.map(r => r.statusCode).sort()).toEqual([401, 401, 429]);
|
||||
await new Promise(resolve => setTimeout(resolve, 120));
|
||||
expect((await login(app)).statusCode).toBe(204);
|
||||
});
|
||||
it("accepts identity headers only from configured direct peers, never X-Forwarded-For", async () => {
|
||||
const dir = await directory();
|
||||
const { app } = await setup({ auth: { dataDir: dir, forwardAuth: { header: "Remote-User", trustedProxyIps: ["127.0.0.1"] } } });
|
||||
expect((await app.inject({ url: "/api/auth/me", headers: { "remote-user": "admin" } })).statusCode).toBe(200);
|
||||
expect((await app.inject({ url: "/api/auth/me", headers: { "remote-user": " " } })).statusCode).toBe(401);
|
||||
const { app: untrusted } = await setup({ auth: { dataDir: await directory(), forwardAuth: { header: "Remote-User", trustedProxyIps: ["192.0.2.1"] } } });
|
||||
expect((await untrusted.inject({ url: "/api/auth/me", headers: { "remote-user": "admin", "x-forwarded-for": "192.0.2.1" } })).statusCode).toBe(401);
|
||||
const { app: disabled } = await setup();
|
||||
expect((await disabled.inject({ url: "/api/auth/me", headers: { "remote-user": "admin" } })).statusCode).toBe(401);
|
||||
});
|
||||
it("rejects expired sessions and honors configured lifetime", async () => {
|
||||
const { app, dataDir } = await setup({ auth: { dataDir: await directory(), sessionMaxAgeSeconds: 60 } });
|
||||
expect((await login(app)).headers["set-cookie"]).toContain("Max-Age=60");
|
||||
const cookie = `shellbook_session=${signSession(loadSessionSecret(dataDir), Date.now() - 1)}`;
|
||||
expect((await app.inject({ url: "/api/auth/me", headers: { cookie } })).statusCode).toBe(401);
|
||||
});
|
||||
it("serves static assets and SPA routes without swallowing API misses", async () => {
|
||||
const root = await directory();
|
||||
await writeFile(join(root, "index.html"), "<h1>ShellBook</h1>");
|
||||
await writeFile(join(root, "asset.js"), "/* asset */");
|
||||
const { app } = await setup({ staticDir: root });
|
||||
expect((await app.inject("/notebooks/example")).body).toBe("<h1>ShellBook</h1>");
|
||||
expect((await app.inject("/asset.js")).body).toBe("/* asset */");
|
||||
const cookie = String((await login(app)).headers["set-cookie"]).split(";")[0]!;
|
||||
expect((await app.inject({ url: "/api/missing", headers: { cookie } })).statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { buildApp } from "../src/app";
|
||||
|
||||
describe("health", () => {
|
||||
it("answers on /api/health", async () => {
|
||||
const app = await buildApp();
|
||||
const app = await buildApp({ auth: false });
|
||||
const res = await app.inject({ method: "GET", url: "/api/health" });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ ok: true });
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { ServerEvent } from "@shellbook/core";
|
||||
import { buildApp } from "../src/app";
|
||||
import { EventsHub } from "../src/runs";
|
||||
import { setPassword } from "../src/auth/credentials";
|
||||
|
||||
const cleanup: Array<() => Promise<unknown>> = [];
|
||||
afterEach(async () => { for (const fn of cleanup.splice(0).reverse()) await fn(); });
|
||||
|
||||
async function workspace() {
|
||||
const root = await mkdtemp(join(tmpdir(), "shellbook-int-"));
|
||||
cleanup.push(() => rm(root, { recursive: true, force: true }));
|
||||
const workspaceDir = join(root, "workspace");
|
||||
const dataDir = join(root, "data");
|
||||
await mkdir(join(workspaceDir, "notebooks"), { recursive: true });
|
||||
await writeFile(join(workspaceDir, "hosts.yaml"), "[]\n");
|
||||
await writeFile(join(workspaceDir, "notebooks", "a.md"), "# A\n");
|
||||
return { workspaceDir, dataDir, sshKeyPath: join(dataDir, "id_ed25519") };
|
||||
}
|
||||
async function app(options: Parameters<typeof buildApp>[0]): Promise<FastifyInstance> {
|
||||
const instance = await buildApp(options);
|
||||
cleanup.push(() => instance.close());
|
||||
return instance;
|
||||
}
|
||||
|
||||
describe("app wiring", () => {
|
||||
it("publishes notebook watcher events into the /api/events hub", async () => {
|
||||
const config = await workspace();
|
||||
const hub = new EventsHub();
|
||||
const events: ServerEvent[] = [];
|
||||
hub.subscribe(event => events.push(event));
|
||||
await app({ config, events: hub, auth: false, watchNotebooks: true });
|
||||
await writeFile(join(config.workspaceDir, "notebooks", "a.md"), "# A changed\n");
|
||||
await vi.waitFor(() => expect(events).toContainEqual({ type: "file.changed", path: "a.md" }), { timeout: 5000 });
|
||||
});
|
||||
|
||||
it("guards every API route from the run, workspace and terminal plugins by default", async () => {
|
||||
const config = await workspace();
|
||||
await setPassword(config.dataDir, "pw");
|
||||
const instance = await app({ config, terminal: { ptyFactory: () => { throw new Error("no pty in this test"); } } });
|
||||
const routes: Array<[string, string]> = [
|
||||
["GET", "/api/notebooks"], ["GET", "/api/notebooks/a.md"], ["PUT", "/api/notebooks/a.md"],
|
||||
["GET", "/api/hosts"], ["POST", "/api/runs"], ["GET", "/api/events"],
|
||||
["GET", "/api/terminal?session=main"], ["GET", "/api/auth/me"],
|
||||
["GET", `/api/runs/${"0".repeat(8)}-0000-0000-0000-${"0".repeat(12)}/artifacts/x`],
|
||||
];
|
||||
for (const [method, url] of routes) {
|
||||
const res = await instance.inject({ method: method as "GET", url, payload: method === "GET" ? undefined : {} });
|
||||
expect(res.statusCode, `${method} ${url}`).toBe(401);
|
||||
}
|
||||
expect((await instance.inject("/api/health")).statusCode).toBe(200);
|
||||
const login = await instance.inject({ method: "POST", url: "/api/auth/login", payload: { password: "pw" } });
|
||||
expect(login.statusCode).toBe(204);
|
||||
const cookie = String(login.headers["set-cookie"]).split(";")[0]!;
|
||||
expect((await instance.inject({ url: "/api/notebooks", headers: { cookie } })).json().notebooks).toEqual([{ path: "a.md", title: "A" }]);
|
||||
});
|
||||
});
|
||||
@@ -105,7 +105,7 @@ async function sshFixture() {
|
||||
|
||||
describe("workspace", () => {
|
||||
it("reads nested notebooks, lists them, hashes versions, rejects stale concurrent saves", async () => {
|
||||
const app = await buildApp({ config: await fixture() }); cleanup.push(() => app.close());
|
||||
const app = await buildApp({ config: await fixture(), auth: false }); cleanup.push(() => app.close());
|
||||
const url = "/api/notebooks/nested%2Ftest.md";
|
||||
const res = await app.inject(url);
|
||||
expect(res.statusCode).toBe(200);
|
||||
@@ -117,7 +117,7 @@ describe("workspace", () => {
|
||||
expect((await app.inject(url)).json().version).not.toBe(payload.baseVersion);
|
||||
});
|
||||
it("validates inventory and applies defaults", async () => {
|
||||
const config = await fixture(); const app = await buildApp({ config }); cleanup.push(() => app.close());
|
||||
const config = await fixture(); const app = await buildApp({ config, auth: false }); cleanup.push(() => app.close());
|
||||
expect((await app.inject("/api/hosts")).json().hosts[0]).toEqual({ name: "test", address: "localhost", user: "admin", port: 22, tags: [] });
|
||||
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), "- name: bad\n address: localhost\n");
|
||||
expect((await app.inject("/api/hosts")).statusCode).toBe(400);
|
||||
@@ -128,7 +128,7 @@ describe("workspace", () => {
|
||||
it("rejects symlink notebooks and non-md paths", async () => {
|
||||
const config = await fixture();
|
||||
await symlink(path.join(config.workspaceDir, "notebooks", "nested"), path.join(config.workspaceDir, "notebooks", "link"), "junction");
|
||||
const app = await buildApp({ config }); cleanup.push(() => app.close());
|
||||
const app = await buildApp({ config, auth: false }); cleanup.push(() => app.close());
|
||||
expect((await app.inject("/api/notebooks/link%2Ftest.md")).statusCode).toBe(400);
|
||||
expect((await app.inject("/api/notebooks/hosts.yaml")).statusCode).toBe(400);
|
||||
});
|
||||
@@ -194,7 +194,7 @@ describe("SSH with a deterministic in-process server", () => {
|
||||
const req = request(); req.acceptHostKey = fp;
|
||||
await executeRun({ config, hub, runId: first, request: req, step: step(), rendered: r, host, env: {} });
|
||||
expect(events.at(-1)).toMatchObject({ exitCode: 0, artifacts: ["out.txt"] });
|
||||
const app = await buildApp({ config }); cleanup.push(() => app.close());
|
||||
const app = await buildApp({ config, auth: false }); cleanup.push(() => app.close());
|
||||
const download = await app.inject(`/api/runs/${first}/artifacts/out.txt`);
|
||||
expect(download.statusCode).toBe(200); expect(download.body).toBe("artifact bytes");
|
||||
expect((await app.inject(`/api/runs/${first}/artifacts/undeclared.txt`)).statusCode).toBe(404);
|
||||
@@ -211,7 +211,7 @@ describe("pipeline helpers", () => {
|
||||
await writeFile(path.join(config.workspaceDir, "hosts.yaml"), JSON.stringify([host]));
|
||||
vi.mocked(parseNotebook).mockReturnValueOnce({ title: "Test", params: [], blocks: [{ type: "step", step: step() }], diagnostics: [] });
|
||||
const hub = new EventsHub();
|
||||
const app = await buildApp({ config, events: hub }); cleanup.push(() => app.close());
|
||||
const app = await buildApp({ config, events: hub, auth: false }); cleanup.push(() => app.close());
|
||||
await app.ready();
|
||||
const socket = await app.injectWS("/api/events"); cleanup.push(async () => socket.close());
|
||||
const events: ServerEvent[] = [];
|
||||
|
||||
@@ -36,7 +36,7 @@ describe("terminal validation", () => {
|
||||
|
||||
describe("terminal plugin", () => {
|
||||
it("is registered by buildApp and rejects invalid sessions", async () => {
|
||||
const app = await buildApp();
|
||||
const app = await buildApp({ auth: false });
|
||||
try {
|
||||
expect(app.hasRoute({ method: "GET", url: "/api/terminal" })).toBe(true);
|
||||
expect((await app.inject("/api/terminal?session=BAD")).statusCode).toBe(400);
|
||||
@@ -65,7 +65,7 @@ describe("terminal plugin", () => {
|
||||
// injectWS uses in-memory Duplexify streams whose close handshake does not
|
||||
// finish like a TCP socket. Terminate the server peer to model a lost tab.
|
||||
const peers = [...app.websocketServer.clients];
|
||||
peers[0].terminate();
|
||||
peers[0]!.terminate();
|
||||
await vi.waitFor(() => expect(first.pty.kill).toHaveBeenCalledTimes(1));
|
||||
expect(second.pty.kill).not.toHaveBeenCalled();
|
||||
expect(first.dataDispose).toHaveBeenCalledOnce();
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
*.sh text eol=lf
|
||||
@@ -0,0 +1,63 @@
|
||||
# Deploy ShellBook (M5 / #6)
|
||||
|
||||
Access is root-equivalent across managed hosts. Restrict CT port 8080 to the
|
||||
Traefik host with the Proxmox firewall; use HTTPS and limit the router to your
|
||||
LAN/Tailscale addresses. No password is set initially: API access fails closed.
|
||||
|
||||
1. Copy `deploy/` to the Proxmox VE 9 host. As root run
|
||||
`bash deploy/proxmox/create-ct.sh`. Defaults: unprivileged Debian 13 CT 501,
|
||||
2 cores, 2 GiB RAM, 16 GiB disk, DHCP on vmbr0, onboot, nesting and TUN.
|
||||
Overrides: `CTID`, `CT_STORAGE`, `TEMPLATE_STORAGE`, `CT_BRIDGE`, `CT_IP`
|
||||
(Proxmox ip syntax), `CT_HOSTNAME`, `CT_CORES`, `CT_MEMORY`, `CT_DISK_GB`.
|
||||
Existing CTs must be unprivileged Debian 13 of the host architecture; they
|
||||
may reboot when TUN passthrough is added. No raw config appending is used.
|
||||
2. Optionally supply `SHELLBOOK_REPO`, `SHELLBOOK_REF`, `SHELLBOOK_HOST`,
|
||||
`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`.
|
||||
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.
|
||||
5. Install the Traefik example in its file-provider directory and replace the
|
||||
hostname, CT address, TLS resolver and allowed networks. Set the actual
|
||||
Traefik peer IP in `/etc/shellbook/env` as `SHELLBOOK_TRUSTED_PROXIES`, then
|
||||
`systemctl restart shellbook`. Only configured proxies can influence HTTPS
|
||||
detection (and thus Secure cookies). TLS terminates at Traefik.
|
||||
|
||||
Standalone CT installation: run `bash deploy/install.sh` as root on Debian 13.
|
||||
The installer can be rerun; it preserves env, password, workspace, SSH key and
|
||||
session signing secret. It builds the checkout but does not pull on rerun.
|
||||
Updates: `bash /opt/shellbook/deploy/update.sh` (root). Failure before restart
|
||||
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.
|
||||
|
||||
Forward auth is off by default. To enable it set
|
||||
`SHELLBOOK_FORWARD_AUTH_HEADER=Remote-User` and trusted proxy IPs. The header is
|
||||
accepted only from an exact direct peer IP on that list (IPv4-mapped IPv6 is
|
||||
normalized). Traefik must strip incoming identity headers and set its own after
|
||||
authentication; block direct CT access. Built-in password login remains available.
|
||||
WebSocket clients must send the same session cookie; cross-origin API requests
|
||||
are rejected. Custom browser clients must use the public Host header.
|
||||
|
||||
Build choices: esbuild is a well-known TypeScript bundler; it bundles the source
|
||||
`@shellbook/core` via an explicit alias, while npm dependencies (including native
|
||||
node-pty) stay external. Production therefore retains installed node_modules.
|
||||
`@fastify/static` supplies Fastify-compatible static serving and safe file paths;
|
||||
the static directory is served only when index.html exists, with SPA fallback
|
||||
outside `/api`. Node 22 comes from nodejs.org's latest-v22.x binary release,
|
||||
verified with its SHA-256 manifest downloaded over HTTPS. This avoids third-party
|
||||
apt signing-key compatibility issues on Debian 13. Rerun the installer to update
|
||||
Node 22 security releases; unattended upgrades cover Debian packages only.
|
||||
Build tools support node-pty compilation. Claude uses its native installer.
|
||||
|
||||
Local deployment regression: `bash deploy/test/template-picker.test.sh`.
|
||||
The scripts require bash, use LF endings, and avoid early-consuming pipelines
|
||||
under pipefail. Proxmox, systemd, Tailscale and SSH require deployment validation.
|
||||
Executable
+130
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
[[ $EUID == 0 ]] || { echo 'Run as root inside Debian 13' >&2; exit 1; }
|
||||
# shellcheck source=/dev/null
|
||||
source /etc/os-release
|
||||
[[ $ID == debian && $VERSION_ID == 13 ]] || { echo 'Debian 13 required' >&2; exit 1; }
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update
|
||||
apt-get install -y ca-certificates git curl jq tmux build-essential python3 unattended-upgrades openssh-client xz-utils
|
||||
# Official Node binaries, verified against the SHA-256 manifest over HTTPS.
|
||||
case $(dpkg --print-architecture) in
|
||||
amd64) node_arch=x64 ;;
|
||||
arm64) node_arch=arm64 ;;
|
||||
*) echo 'Unsupported Node binary architecture' >&2; exit 1 ;;
|
||||
esac
|
||||
node_temp=$(mktemp -d)
|
||||
trap 'rm -rf -- "$node_temp"' EXIT
|
||||
curl -fsSL https://nodejs.org/dist/latest-v22.x/SHASUMS256.txt -o "$node_temp/SHASUMS256.txt"
|
||||
node_file=$(awk -v arch="$node_arch" '$2 ~ ("^node-v22\\.[0-9]+\\.[0-9]+-linux-" arch "\\.tar\\.xz$") {print $2}' "$node_temp/SHASUMS256.txt")
|
||||
[[ -n $node_file && $node_file != *$'\n'* ]] || { echo 'No unique Node 22 binary found' >&2; exit 1; }
|
||||
curl -fsSL "https://nodejs.org/dist/latest-v22.x/$node_file" -o "$node_temp/$node_file"
|
||||
awk -v file="$node_file" '$2 == file' "$node_temp/SHASUMS256.txt" > "$node_temp/checksum"
|
||||
(cd "$node_temp"; sha256sum -c checksum)
|
||||
mkdir "$node_temp/unpacked"
|
||||
tar -xJf "$node_temp/$node_file" -C "$node_temp/unpacked" --strip-components=1
|
||||
# Replace the executable rather than truncating one a running service uses.
|
||||
install -m 0755 "$node_temp/unpacked/bin/node" /usr/local/bin/node
|
||||
rm "$node_temp/unpacked/bin/node"
|
||||
cp -a "$node_temp/unpacked/." /usr/local/
|
||||
rm -rf -- "$node_temp"
|
||||
trap - EXIT
|
||||
[[ $(node --version) == v22.* ]] || { echo 'Node 22 required' >&2; exit 1; }
|
||||
# Pin a current Corepack rather than relying on the binary bundled with Node.
|
||||
npm install -g [email protected]
|
||||
corepack enable
|
||||
corepack prepare [email protected] --activate
|
||||
if ! id shellbook >/dev/null 2>&1; then useradd --create-home --shell /bin/bash shellbook; fi
|
||||
install -d -m 0700 -o shellbook -g shellbook /var/lib/shellbook /home/shellbook/.ssh
|
||||
repo=${SHELLBOOK_REPO:-https://git.finalfactory.de/FinalFactory/ShellBook.git}
|
||||
if [[ ! -e /opt/shellbook ]]; then
|
||||
install -d -o shellbook -g shellbook /opt/shellbook
|
||||
runuser -u shellbook -- git clone "$repo" /opt/shellbook
|
||||
fi
|
||||
if [[ -n ${SHELLBOOK_REF:-} ]]; then runuser -u shellbook -- git -C /opt/shellbook checkout "$SHELLBOOK_REF"; fi
|
||||
runuser -u shellbook -- bash -c 'cd /opt/shellbook; pnpm install --frozen-lockfile; pnpm build'
|
||||
workspace=/home/shellbook/workspace
|
||||
install -d -o shellbook -g shellbook "$workspace"
|
||||
if [[ -z $(find "$workspace" -mindepth 1 -maxdepth 1 -print -quit) ]]; then
|
||||
if [[ -d /opt/shellbook/templates/workspace ]]; then cp -a /opt/shellbook/templates/workspace/. "$workspace/"; fi
|
||||
chown -R shellbook:shellbook "$workspace"
|
||||
runuser -u shellbook -- git -C "$workspace" init
|
||||
fi
|
||||
if [[ ! -f /home/shellbook/.ssh/id_ed25519 ]]; then
|
||||
runuser -u shellbook -- ssh-keygen -q -t ed25519 -N '' -f /home/shellbook/.ssh/id_ed25519 -C shellbook
|
||||
fi
|
||||
if [[ ! -x /home/shellbook/.local/bin/claude ]]; then
|
||||
runuser -u shellbook -- env HOME=/home/shellbook bash -o pipefail -c 'curl -fsSL https://claude.ai/install.sh | bash'
|
||||
fi
|
||||
install -d -m 0750 /etc/shellbook
|
||||
if [[ ! -f /etc/shellbook/env ]]; then
|
||||
host=${SHELLBOOK_HOST:-0.0.0.0}
|
||||
port=${SHELLBOOK_PORT:-8080}
|
||||
proxies=${SHELLBOOK_TRUSTED_PROXIES:-}
|
||||
[[ $host =~ ^[a-zA-Z0-9.:_-]+$ && $port =~ ^[0-9]+$ && $proxies =~ ^[a-zA-Z0-9.,:/_-]*$ ]] || { echo 'Invalid listen/proxy settings' >&2; exit 1; }
|
||||
cat > /etc/shellbook/env <<EOF
|
||||
SHELLBOOK_HOST=$host
|
||||
SHELLBOOK_PORT=$port
|
||||
SHELLBOOK_DATA_DIR=/var/lib/shellbook
|
||||
SHELLBOOK_WORKSPACE=/home/shellbook/workspace
|
||||
SHELLBOOK_SSH_KEY=/home/shellbook/.ssh/id_ed25519
|
||||
SHELLBOOK_STATIC_DIR=/opt/shellbook/apps/web/dist
|
||||
SHELLBOOK_TRUSTED_PROXIES=$proxies
|
||||
PATH=/home/shellbook/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
EOF
|
||||
fi
|
||||
chmod 600 /etc/shellbook/env
|
||||
cat > /etc/systemd/system/shellbook.service <<'EOF'
|
||||
[Unit]
|
||||
Description=ShellBook runbook server
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=shellbook
|
||||
Group=shellbook
|
||||
WorkingDirectory=/opt/shellbook
|
||||
EnvironmentFile=/etc/shellbook/env
|
||||
ExecStart=/usr/local/bin/node /opt/shellbook/apps/server/dist/main.js
|
||||
Restart=on-failure
|
||||
# tmux servers started by the terminal panel must survive service restarts (spec §6).
|
||||
KillMode=process
|
||||
RestartSec=5
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=full
|
||||
# Home and /var/lib remain writable for workspace, SSH and Claude/tmux state.
|
||||
# Avoid namespace/device hardening that breaks unprivileged LXC or PTYs.
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'EOF'
|
||||
APT::Periodic::Update-Package-Lists "1";
|
||||
APT::Periodic::Unattended-Upgrade "1";
|
||||
EOF
|
||||
if [[ -n ${TS_AUTHKEY:-} ]]; then
|
||||
curl -fsSL https://tailscale.com/install.sh | sh
|
||||
key_file=$(mktemp)
|
||||
trap 'rm -f "$key_file"' EXIT
|
||||
chmod 600 "$key_file"
|
||||
printf '%s' "$TS_AUTHKEY" > "$key_file"
|
||||
tailscale up --auth-key="file:$key_file"
|
||||
rm -f "$key_file"
|
||||
fi
|
||||
systemctl daemon-reload
|
||||
systemctl enable shellbook
|
||||
systemctl restart shellbook
|
||||
cat <<'EOF'
|
||||
Next steps:
|
||||
1. Set the password (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'
|
||||
Then use /login.
|
||||
3. Authorize this public SSH key on managed servers:
|
||||
EOF
|
||||
cat /home/shellbook/.ssh/id_ed25519.pub
|
||||
echo '4. Configure Traefik, trusted proxy IPs and the LAN/Tailscale firewall; see deploy/README.md.'
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
[[ $EUID == 0 ]] || { echo 'Run on the Proxmox host as root' >&2; exit 1; }
|
||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||
# shellcheck source=deploy/proxmox/template-picker.sh
|
||||
source "$script_dir/template-picker.sh"
|
||||
ctid=${CTID:-501}
|
||||
[[ $ctid =~ ^[0-9]+$ ]] || { echo 'Invalid CTID' >&2; exit 1; }
|
||||
arch=$(dpkg --print-architecture)
|
||||
if pct config "$ctid" >/dev/null 2>&1; then
|
||||
config=$(pct config "$ctid")
|
||||
[[ $config == *'ostype: debian'* && $config == *"arch: $arch"* && $config == *'unprivileged: 1'* ]] || {
|
||||
echo 'Refusing to touch a non-Debian, wrong-architecture, or privileged CT' >&2; exit 1;
|
||||
}
|
||||
pct start "$ctid" 2>/dev/null || [[ $(pct status "$ctid") == *running* ]]
|
||||
# These variables must expand inside the CT, not on the host.
|
||||
# shellcheck disable=SC2016
|
||||
pct exec "$ctid" -- sh -c '. /etc/os-release; test "$ID" = debian && test "$VERSION_ID" = 13' || {
|
||||
echo 'Refusing to touch a CT that is not Debian 13' >&2; exit 1;
|
||||
}
|
||||
container_arch=$(pct exec "$ctid" -- dpkg --print-architecture)
|
||||
[[ $container_arch == "$arch" ]] || { echo 'Container architecture mismatch' >&2; exit 1; }
|
||||
else
|
||||
pveam update
|
||||
available=$(pveam available --section system)
|
||||
template=$(pick_template "$arch" <<< "$available")
|
||||
[[ -n $template ]] || { echo "No Debian 13 template for $arch" >&2; exit 1; }
|
||||
pveam download "${TEMPLATE_STORAGE:-local}" "$template"
|
||||
pct create "$ctid" "${TEMPLATE_STORAGE:-local}:vztmpl/$template" \
|
||||
--hostname "${CT_HOSTNAME:-shellbook}" --ostype debian --arch "$arch" \
|
||||
--unprivileged 1 --features nesting=1 --onboot 1 \
|
||||
--cores "${CT_CORES:-2}" --memory "${CT_MEMORY:-2048}" --swap 512 \
|
||||
--rootfs "${CT_STORAGE:-local-lvm}:${CT_DISK_GB:-16}" \
|
||||
--net0 "name=eth0,bridge=${CT_BRIDGE:-vmbr0},ip=${CT_IP:-dhcp}"
|
||||
fi
|
||||
# pct manages the active config correctly even when snapshot sections exist.
|
||||
config=$(pct config "$ctid")
|
||||
needs_restart=0
|
||||
features=$(awk -F': ' '$1 == "features" {print $2}' <<< "$config")
|
||||
if [[ $features != *nesting=1* ]]; then
|
||||
features=${features//nesting=0/nesting=1}
|
||||
[[ $features == *nesting=1* ]] || features="${features:+$features,}nesting=1"
|
||||
pct set "$ctid" --features "$features"
|
||||
needs_restart=1
|
||||
fi
|
||||
pct set "$ctid" --onboot 1
|
||||
if [[ $config != *'path=/dev/net/tun'* && $config != *'dev0: /dev/net/tun'* ]]; then
|
||||
[[ $config != *'dev0:'* ]] || { echo 'dev0 already occupied; configure /dev/net/tun passthrough manually' >&2; exit 1; }
|
||||
pct set "$ctid" --dev0 /dev/net/tun
|
||||
needs_restart=1
|
||||
fi
|
||||
if [[ $needs_restart == 1 && $(pct status "$ctid") == *running* ]]; then pct shutdown "$ctid" --timeout 60; fi
|
||||
if [[ $(pct status "$ctid") != *running* ]]; then pct start "$ctid"; fi
|
||||
# Wait for init/network after creation or reboot.
|
||||
for ((attempt=0; attempt<60; attempt++)); do
|
||||
if pct exec "$ctid" -- test -d /run/systemd/system; then break; fi
|
||||
sleep 1
|
||||
done
|
||||
pct push "$ctid" "$script_dir/../install.sh" /root/shellbook-install.sh --perms 0700
|
||||
# Transfer optional settings without exposing TS_AUTHKEY in process arguments.
|
||||
settings=$(mktemp)
|
||||
trap 'rm -f "$settings"' EXIT
|
||||
chmod 600 "$settings"
|
||||
for key in SHELLBOOK_REPO SHELLBOOK_REF SHELLBOOK_HOST SHELLBOOK_PORT SHELLBOOK_TRUSTED_PROXIES TS_AUTHKEY; do
|
||||
if [[ -v $key ]]; then printf 'export %s=%q\n' "$key" "${!key}" >> "$settings"; fi
|
||||
done
|
||||
pct push "$ctid" "$settings" /root/shellbook-install.env --perms 0600
|
||||
pct exec "$ctid" -- bash -c 'trap "rm -f /root/shellbook-install.env" EXIT; source /root/shellbook-install.env; bash /root/shellbook-install.sh'
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Input: pveam available output. Filter architecture BEFORE sorting versions.
|
||||
pick_template() {
|
||||
local arch=$1
|
||||
[[ $arch =~ ^[a-z0-9]+$ ]] || return 1
|
||||
awk -v arch="$arch" '$NF ~ ("^debian-13-standard_.*_" arch "\\.tar\\.(zst|xz|gz)$") { print $NF }' |
|
||||
sort -V | tail -n 1
|
||||
}
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
# shellcheck source=deploy/proxmox/template-picker.sh
|
||||
source "$(dirname "${BASH_SOURCE[0]}")/../proxmox/template-picker.sh"
|
||||
fixtures='system debian-13-standard_13.0-1_amd64.tar.zst
|
||||
system debian-13-standard_13.0-9_arm64.tar.zst
|
||||
system debian-12-standard_12.9-1_amd64.tar.zst
|
||||
system debian-13-standard_13.0-2_amd64.tar.zst
|
||||
system debian-13-standard_13.0-10_amd64.tar.zst'
|
||||
[[ $(pick_template amd64 <<< "$fixtures") == debian-13-standard_13.0-10_amd64.tar.zst ]]
|
||||
[[ $(pick_template arm64 <<< "$fixtures") == debian-13-standard_13.0-9_arm64.tar.zst ]]
|
||||
[[ -z $(pick_template riscv64 <<< "$fixtures") ]]
|
||||
[[ -z $(pick_template amd64 <<< 'system debian-13-standard_13.0-99_arm64.tar.zst') ]]
|
||||
if pick_template '.*' <<< "$fixtures"; then exit 1; fi
|
||||
printf '5 template picker checks passed\n'
|
||||
@@ -0,0 +1,21 @@
|
||||
# Traefik v3 file-provider example. Replace host, CT IP and allowed networks.
|
||||
http:
|
||||
routers:
|
||||
shellbook:
|
||||
rule: Host(`shellbook.example.net`)
|
||||
entryPoints: [websecure]
|
||||
tls: {} # Configure the certificate resolver on the entrypoint or here.
|
||||
service: shellbook
|
||||
middlewares: [shellbook-networks]
|
||||
services:
|
||||
shellbook:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: http://192.168.1.50:8080
|
||||
# WebSocket upgrades work without extra headers/middleware.
|
||||
middlewares:
|
||||
shellbook-networks:
|
||||
ipAllowList:
|
||||
sourceRange:
|
||||
- 192.168.1.0/24
|
||||
- 100.64.0.0/10
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
|
||||
runuser -u shellbook -- bash -c 'cd /opt/shellbook; git pull --ff-only; pnpm install --frozen-lockfile; pnpm build'
|
||||
systemctl restart shellbook
|
||||
systemctl --no-pager status shellbook
|
||||
Generated
+494
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user