feat(settings): add browser setup and administration (#10)
This commit is contained in:
@@ -94,3 +94,29 @@ uploads, and capture/runtime rendering without bash. The full shipped `ssh-key.m
|
||||
flow generates real keys and skips cleanly when bash or ssh-keygen is unavailable;
|
||||
it runs in CI/Linux, and also on Windows when a working bash with ssh-keygen is
|
||||
installed. No real target host is modified by these tests.
|
||||
|
||||
## Setup and settings (#10)
|
||||
|
||||
On first startup, `dataDir/setup-token` is created privately (0600). The startup
|
||||
message names its path, never the token. Read it locally and finish setup in the
|
||||
browser. GET `/api/auth/setup` returns `{required}`; POST accepts
|
||||
`{token,newPassword,confirmPassword}`, consumes the token, and returns 204 with a
|
||||
session cookie (409 once configured). Setup/login share a per-IP limiter and the
|
||||
origin check. Keep the data directory private and owned by the service user.
|
||||
|
||||
Authenticated routes: POST `/api/settings/password` accepts
|
||||
`{currentPassword,newPassword,confirmPassword}`; POST `/api/settings/sessions/revoke`
|
||||
rotates the signing key atomically. Both return 204 with a replacement cookie and
|
||||
close existing WebSockets. Passwords need 12 characters and at most 4096 bytes.
|
||||
Hash-bound session signatures invalidate cookies after CLI password changes too.
|
||||
Previously issued cookies from before this feature require a fresh login once.
|
||||
GET `/api/settings/session` returns `{lifetimeSeconds}`; GET `/api/settings/system`
|
||||
returns package version, workspace/data paths, and Node version. GET
|
||||
`/api/settings/claude` runs `claude --version` with no shell, a 3-second timeout
|
||||
and 4096-byte output limit. `loginAppearsPresent` checks existence only of the
|
||||
service user's `~/.claude/.credentials.json`; it cannot prove login validity
|
||||
(and does not inspect macOS Keychain credentials). All status responses are no-store.
|
||||
|
||||
Auth mutations are serialized within the single service process. Run one server
|
||||
per data directory. Already-running host jobs are not cancelled by revocation.
|
||||
Forward-auth access must be revoked at the upstream provider.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { registerSettings } from "./settings";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import websocket from "@fastify/websocket";
|
||||
import { loadConfig, type ServerConfig } from "./config";
|
||||
@@ -37,6 +38,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
|
||||
const hub = options.events ?? new EventsHub();
|
||||
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
|
||||
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
||||
await registerSettings(app, config);
|
||||
await app.register(websocket);
|
||||
await app.register(workspacePlugin, { config });
|
||||
await app.register(runsPlugin, { config, hub });
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
import { ensureSetupToken, matchesSetupToken, removeSetupToken, setupTokenPath, validNewPassword } from "./setup";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { readPasswordHash, verifyPassword } from "./credentials";
|
||||
import { loadSessionSecret, signSession, verifySession } from "./session";
|
||||
import { readPasswordHash, verifyPassword, setPassword } from "./credentials";
|
||||
import { loadSessionSecret, signSession, verifySession, rotateSessionSecret } from "./session";
|
||||
|
||||
export interface AuthOptions {
|
||||
dataDir: string;
|
||||
@@ -12,7 +14,17 @@ export interface AuthOptions {
|
||||
}
|
||||
const normalizeIp = (ip: string) => ip.replace(/^::ffff:/, "");
|
||||
export async function registerAuth(app: FastifyInstance, options: AuthOptions): Promise<void> {
|
||||
const secret = loadSessionSecret(options.dataDir);
|
||||
let secret = loadSessionSecret(options.dataDir);
|
||||
if (!await readPasswordHash(options.dataDir)) {
|
||||
await ensureSetupToken(options.dataDir);
|
||||
app.log.warn(`Set up ShellBook in the browser; read the one-time token at ${setupTokenPath(options.dataDir)}`);
|
||||
} else await removeSetupToken(options.dataDir);
|
||||
// Binding to the persisted hash also revokes sessions after CLI password changes.
|
||||
const sessionKey = async () => createHmac("sha256", secret).update(await readPasswordHash(options.dataDir) ?? "unconfigured").digest();
|
||||
let mutation: Promise<unknown> = Promise.resolve();
|
||||
const exclusive = <T,>(action: () => Promise<T>): Promise<T> => {
|
||||
const next = mutation.then(action); mutation = next.catch(() => {}); return next;
|
||||
};
|
||||
const maxAge = options.sessionMaxAgeSeconds ?? 30 * 86400;
|
||||
if (!Number.isSafeInteger(maxAge) || maxAge <= 0) throw new Error("Invalid session lifetime");
|
||||
const failures = new Map<string, { count: number; until: number }>();
|
||||
@@ -27,7 +39,7 @@ export async function registerAuth(app: FastifyInstance, options: AuthOptions):
|
||||
try { if (new URL(origin).host !== request.headers.host) return reply.code(403).send({ error: "Origin rejected" }); }
|
||||
catch { return reply.code(403).send({ error: "Origin rejected" }); }
|
||||
}
|
||||
if (path === "/api/health" || path === "/api/auth/login") return;
|
||||
if (path === "/api/health" || path === "/api/auth/login" || path === "/api/auth/setup") return;
|
||||
const forward = options.forwardAuth;
|
||||
const peer = normalizeIp(request.raw.socket?.remoteAddress ?? "");
|
||||
if (forward && forward.trustedProxyIps.some(ip => normalizeIp(ip) === peer)) {
|
||||
@@ -35,24 +47,60 @@ export async function registerAuth(app: FastifyInstance, options: AuthOptions):
|
||||
if (typeof user === "string" && user.trim()) return;
|
||||
}
|
||||
const token = request.headers.cookie?.split(";").map(part => part.trim()).find(part => part.startsWith("shellbook_session="))?.slice("shellbook_session=".length);
|
||||
if (!token || !verifySession(secret, token)) return reply.code(401).send({ error: "Authentication required" });
|
||||
if (!token || !verifySession(await sessionKey(), token)) return reply.code(401).send({ error: "Authentication required" });
|
||||
});
|
||||
app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => {
|
||||
function reserveAttempt(ip: string, reply: import("fastify").FastifyReply) {
|
||||
const now = Date.now();
|
||||
for (const [key, value] of failures) if (value.until <= now) failures.delete(key);
|
||||
const ip = request.ip;
|
||||
|
||||
const entry = failures.get(ip);
|
||||
if ((entry?.count ?? 0) >= (options.maxAttempts ?? 5) || (!entry && failures.size >= 10000)) {
|
||||
return reply.header("Retry-After", String(Math.max(1, Math.ceil(((entry?.until ?? now + 60000) - now) / 1000)))).code(429).send({ error: "Try again later" });
|
||||
}
|
||||
// Reserve before scrypt awaits, so parallel attempts cannot bypass the limit.
|
||||
failures.set(ip, { count: (entry?.count ?? 0) + 1, until: entry?.until ?? now + (options.rateWindowMs ?? 60000) });
|
||||
return undefined;
|
||||
}
|
||||
const freshCookie = async (secure: boolean) => cookie(signSession(await sessionKey(), Date.now() + maxAge * 1000), secure, maxAge);
|
||||
app.get("/api/auth/setup", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ required: !await readPasswordHash(options.dataDir) }));
|
||||
app.post("/api/auth/setup", { bodyLimit: 16384 }, async (request, reply) => exclusive(async () => {
|
||||
if (await readPasswordHash(options.dataDir)) return reply.code(409).send({ error: "Already configured" });
|
||||
const limited = reserveAttempt(request.ip, reply); if (limited) return limited;
|
||||
const body = request.body as { token?: unknown; newPassword?: unknown; confirmPassword?: unknown } | null;
|
||||
if (!await matchesSetupToken(options.dataDir, body?.token)) return reply.code(401).send({ error: "Invalid setup token" });
|
||||
if (!validNewPassword(body?.newPassword) || body.newPassword !== body.confirmPassword) return reply.code(400).send({ error: "Passwords must match and contain at least 12 characters (maximum 4096 bytes)" });
|
||||
await setPassword(options.dataDir, body.newPassword);
|
||||
await removeSetupToken(options.dataDir);
|
||||
failures.delete(request.ip);
|
||||
return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send();
|
||||
}));
|
||||
app.post("/api/settings/password", { bodyLimit: 16384 }, async (request, reply) => exclusive(async () => {
|
||||
const limited = reserveAttempt(request.ip, reply); if (limited) return limited;
|
||||
const body = request.body as { currentPassword?: unknown; newPassword?: unknown; confirmPassword?: unknown } | null;
|
||||
const hash = await readPasswordHash(options.dataDir);
|
||||
if (typeof body?.currentPassword !== "string" || !hash || !await verifyPassword(body.currentPassword, hash)) return reply.code(401).send({ error: "Invalid current password" });
|
||||
if (!validNewPassword(body.newPassword) || body.newPassword !== body.confirmPassword) return reply.code(400).send({ error: "Passwords must match and contain at least 12 characters (maximum 4096 bytes)" });
|
||||
await setPassword(options.dataDir, body.newPassword);
|
||||
app.websocketServer?.clients.forEach(socket => socket.close(1008, "Sessions revoked"));
|
||||
failures.delete(request.ip);
|
||||
return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send();
|
||||
}));
|
||||
app.post("/api/settings/sessions/revoke", async (request, reply) => exclusive(async () => {
|
||||
secret = rotateSessionSecret(options.dataDir);
|
||||
app.websocketServer?.clients.forEach(socket => socket.close(1008, "Sessions revoked"));
|
||||
return reply.header("Set-Cookie", await freshCookie(request.protocol === "https")).code(204).send();
|
||||
}));
|
||||
app.get("/api/settings/session", async () => ({ lifetimeSeconds: maxAge }));
|
||||
app.post("/api/auth/login", { bodyLimit: 8192 }, async (request, reply) => exclusive(async () => {
|
||||
const limited = reserveAttempt(request.ip, reply);
|
||||
if (limited) return limited;
|
||||
const now = Date.now();
|
||||
const password = (request.body as { password?: unknown } | null)?.password;
|
||||
const hash = await readPasswordHash(options.dataDir);
|
||||
if (typeof password !== "string" || !hash || !await verifyPassword(password, hash)) return reply.code(401).send({ error: "Invalid credentials" });
|
||||
failures.delete(ip);
|
||||
return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(secret, now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send();
|
||||
});
|
||||
failures.delete(request.ip);
|
||||
return reply.header("Cache-Control", "no-store").header("Set-Cookie", cookie(signSession(await sessionKey(), now + maxAge * 1000), request.protocol === "https", maxAge)).code(204).send();
|
||||
}));
|
||||
app.post("/api/auth/logout", async (request, reply) => reply.header("Set-Cookie", cookie("", request.protocol === "https", 0)).code(204).send());
|
||||
app.get("/api/auth/me", async (_request, reply) => reply.header("Cache-Control", "no-store").send({ authenticated: true }));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { mkdirSync, readFileSync, writeFileSync, chmodSync } from "node:fs";
|
||||
import { mkdirSync, readFileSync, writeFileSync, chmodSync, renameSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function loadSessionSecret(dataDir: string): Buffer {
|
||||
@@ -22,3 +22,12 @@ export function verifySession(secret: Buffer, cookie: string, now = Date.now()):
|
||||
const expected = signSession(secret, Number(payload)).split(".")[1]!;
|
||||
return Number(payload) > now && timingSafeEqual(Buffer.from(mac!), Buffer.from(expected));
|
||||
}
|
||||
|
||||
/** Replace before publishing the new key to request handlers. */
|
||||
export function rotateSessionSecret(dataDir: string): Buffer {
|
||||
const secret = randomBytes(32);
|
||||
const temp = join(dataDir, `session-secret.${randomBytes(8).toString("hex")}.tmp`);
|
||||
writeFileSync(temp, secret, { mode: 0o600, flag: "wx" });
|
||||
renameSync(temp, join(dataDir, "session-secret"));
|
||||
return secret;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
|
||||
import { chmod, readFile, writeFile, unlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const setupTokenPath = (dataDir: string) => join(dataDir, "setup-token");
|
||||
export async function ensureSetupToken(dataDir: string): Promise<void> {
|
||||
const path = setupTokenPath(dataDir);
|
||||
try {
|
||||
await writeFile(path, randomBytes(32).toString("hex") + "\n", {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
||||
}
|
||||
await chmod(path, 0o600);
|
||||
}
|
||||
export async function matchesSetupToken(
|
||||
dataDir: string,
|
||||
candidate: unknown,
|
||||
): Promise<boolean> {
|
||||
if (typeof candidate !== "string" || candidate.length > 4096) return false;
|
||||
try {
|
||||
const expected = (await readFile(setupTokenPath(dataDir), "utf8")).trim();
|
||||
const digest = (value: string) =>
|
||||
createHash("sha256").update(value).digest();
|
||||
return timingSafeEqual(digest(candidate), digest(expected));
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
export async function removeSetupToken(dataDir: string): Promise<void> {
|
||||
await unlink(setupTokenPath(dataDir)).catch((error) => {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
});
|
||||
}
|
||||
export function validNewPassword(value: unknown): value is string {
|
||||
return (
|
||||
typeof value === "string" &&
|
||||
value.length >= 12 &&
|
||||
Buffer.byteLength(value) <= 4096
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { access } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { ClaudeStatusResponse, SystemInfoResponse } from "@shellbook/core";
|
||||
import type { ServerConfig } from "../config";
|
||||
import { version } from "../../package.json";
|
||||
|
||||
/** No shell, bounded runtime/output, and no credential contents are accessed. */
|
||||
export async function claudeStatus(
|
||||
home = homedir(),
|
||||
env = process.env,
|
||||
): Promise<ClaudeStatusResponse> {
|
||||
const loginAppearsPresent = await access(
|
||||
join(home, ".claude", ".credentials.json"),
|
||||
).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
return new Promise((resolve) => {
|
||||
execFile(
|
||||
"claude",
|
||||
["--version"],
|
||||
{ env, timeout: 3000, maxBuffer: 4096, windowsHide: true },
|
||||
(error, stdout) => {
|
||||
resolve({
|
||||
available: !error,
|
||||
version: error ? null : stdout.trim(),
|
||||
loginAppearsPresent,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
export async function registerSettings(
|
||||
app: FastifyInstance,
|
||||
config: ServerConfig,
|
||||
): Promise<void> {
|
||||
app.get("/api/settings/claude", async (_request, reply) =>
|
||||
reply.header("Cache-Control", "no-store").send(await claudeStatus()),
|
||||
);
|
||||
app.get("/api/settings/system", async (_request, reply) => {
|
||||
const info: SystemInfoResponse = {
|
||||
version,
|
||||
workspacePath: config.workspaceDir,
|
||||
dataDirPath: config.dataDir,
|
||||
nodeVersion: process.version,
|
||||
};
|
||||
return reply.header("Cache-Control", "no-store").send(info);
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user