remove the dead multi-user surface

Officer is single-user: the server owner is the only account, created once by
/auth/bootstrap. Everything that existed to serve additional users was
unreachable, so it is gone rather than left looking like it does something.

Accounts: drop the invite / resend-invite / delete / list-users routes and the
Users settings screen, the inert /auth/signup handler, and the account
verification chain it fed (verify, resend-verification, VerifyScreen, the
UserInvite + VerifyAdmin + VerifyRegistration templates). /auth/verify-token
survives for password resets only, and now requires a reset-password token
rather than accepting any signed JWT.

Roles: drop the users.role column and the four-value USER_ROLES enum. The
permissions table granted every role identical methods, and every
role === 'Super Admin' check was permanently true. The JWT no longer carries a
role claim.

Sandbox: remove sidecar/sandbox.ts and its five call sites. bwrap was selected
only for non-Super-Admin users, so it never ran. It was also not a usable agent
jail as written — --share-net, the project root (with .env) bound read-only,
and runuser dropping to the server's own uid. Rebuilding it for agent
containment would be a different construction, and git history keeps this one.

getHomeDir keeps its DATA_PATH meaning; the new getOwnerHomeDir resolves the
owner's real login home, which is what terminals, chats and task runs use.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
brunorezio
2026-07-25 23:30:20 +01:00
co-authored by Claude Opus 5
parent 92de996412
commit 044aacf4d5
85 changed files with 2761 additions and 2121 deletions
+11 -27
View File
@@ -2,7 +2,6 @@ import { join } from 'node:path';
import type { Subprocess } from 'bun';
import type { ChatEvent } from '../../api/chat/types';
import type { ClaudeSpawnParams, ClaudeSpawnStreamingParams, ClaudeCodeResult } from '../protocol';
import { buildSandboxPrefix, buildRunuserSuffix, SANDBOX_HOME } from '../sandbox';
import { setClaudeSession, clearClaudeSession, getClaudeSession } from './state';
import { parseStream } from './stream-parser';
@@ -16,26 +15,13 @@ const CLAUDE_BIN = '/usr/local/bin/claude';
const HOST_HOME = process.env.HOME!;
const DATA_PATH = process.env.DATA_PATH ?? join(process.cwd(), 'data');
// Build full bwrap sandbox args for Claude (prefix + Anthropic env + runuser suffix)
function buildSandboxArgs(email: string): string[] {
const prefix = buildSandboxPrefix(email);
// Claude-specific env vars
if (process.env.ANTHROPIC_BASE_URL) prefix.push('--setenv', 'ANTHROPIC_BASE_URL', process.env.ANTHROPIC_BASE_URL);
if (process.env.ANTHROPIC_API_KEY) prefix.push('--setenv', 'ANTHROPIC_API_KEY', process.env.ANTHROPIC_API_KEY);
return [...prefix, ...buildRunuserSuffix()];
}
// Active streaming processes
const activeProcs = new Map<string, Subprocess>();
// MCP config paths, set by user-instance at startup
let mcpSandboxPath: string | undefined; // path inside bwrap sandbox (/data/...)
let mcpHostPath: string | undefined; // path on the host filesystem
export function setMcpConfigPath(sandboxPath: string, hostPath: string): void {
mcpSandboxPath = sandboxPath;
export function setMcpConfigPath(hostPath: string): void {
mcpHostPath = hostPath;
}
@@ -57,8 +43,7 @@ export async function spawnClaude(params: ClaudeSpawnParams): Promise<ClaudeCode
const claudeArgs = [CLAUDE_BIN, '-p', prompt, '--dangerously-skip-permissions', '--output-format', 'json'];
const isSuperAdmin = params.role === 'Super Admin';
const mcpConfig = isSuperAdmin ? mcpHostPath : mcpSandboxPath;
const mcpConfig = mcpHostPath;
if (mcpConfig) claudeArgs.push('--mcp-config', mcpConfig);
const subModel = params.model?.split('/')[1];
@@ -68,10 +53,10 @@ export async function spawnClaude(params: ClaudeSpawnParams): Promise<ClaudeCode
claudeArgs.push('--resume', existingSession);
}
const spawnCmd = isSuperAdmin ? claudeArgs : [...buildSandboxArgs(email), ...claudeArgs];
// Honor a caller-provided working directory (e.g. /chat runs from a dedicated general_chat_sessions dir);
// fall back to the host home for Super Admin, or the sandbox default otherwise.
const spawnCwd = isSuperAdmin ? (params.cwd ?? HOST_HOME) : undefined;
const spawnCmd = claudeArgs;
// Honor a caller-provided working directory (e.g. /chat runs from a dedicated general_chat_sessions
// dir); fall back to the owner's host home.
const spawnCwd = params.cwd ?? HOST_HOME;
const proc = Bun.spawn(spawnCmd, {
stdin: 'pipe',
@@ -156,8 +141,7 @@ export async function spawnClaudeStreaming(
];
const { CLAUDECODE: _, ...cleanEnv } = process.env;
const isSuperAdmin = params.role === 'Super Admin';
const mcpConfig = isSuperAdmin ? mcpHostPath : mcpSandboxPath;
const mcpConfig = mcpHostPath;
if (mcpConfig) claudeArgs.push('--mcp-config', mcpConfig);
const subModel = params.model?.split('/')[1];
@@ -171,10 +155,10 @@ export async function spawnClaudeStreaming(
if (!existingSession) setClaudeSession(sessionKey, resumeId);
}
const spawnCmd = isSuperAdmin ? claudeArgs : [...buildSandboxArgs(email), ...claudeArgs];
// Honor a caller-provided working directory (e.g. /chat runs from a dedicated general_chat_sessions dir);
// fall back to the host home for Super Admin, or the sandbox default otherwise.
const spawnCwd = isSuperAdmin ? (params.cwd ?? HOST_HOME) : undefined;
const spawnCmd = claudeArgs;
// Honor a caller-provided working directory (e.g. /chat runs from a dedicated general_chat_sessions
// dir); fall back to the owner's host home.
const spawnCwd = params.cwd ?? HOST_HOME;
const proc = Bun.spawn(spawnCmd, {
stdin: 'ignore',
+11 -65
View File
@@ -4,7 +4,6 @@ import { homedir } from 'node:os';
import type { SidecarCommand, SidecarEvent } from '../protocol';
import { initPaths, loadState, flushAndSave, acquireLock, releaseLock } from './state';
import { setMcpConfigPath } from './claude-manager';
import { SANDBOX_DATA } from '../sandbox';
import * as claudeManager from './claude-manager';
import { createSidecarConnector } from '../connect';
import { sign } from '../../jwt';
@@ -27,16 +26,12 @@ if (!dbUser) {
console.error(`[user-instance] no user found for ${email}`);
process.exit(1);
}
const OFFICER_AUTH_TOKEN = await sign(
{ id: dbUser.id, email, username: dbUser.username, role: dbUser.role },
'30d',
);
const OFFICER_AUTH_TOKEN = await sign({ id: dbUser.id, email, username: dbUser.username }, '30d');
// Single-user platform: the Super Admin runs Claude with no isolation — real HOME, real ~/.claude —
// so platform sessions have perfect parity with terminal sessions (same config, credentials, and
// transcript store, interchangeable via `claude --resume`). Any non-super-admin keeps an isolated home.
const homeDir =
dbUser.role === 'Super Admin' ? (process.env.HOME_DIR ?? homedir()) : join(DATA_PATH, email, 'home');
// Single-user platform: the owner runs Claude with no isolation — real HOME, real ~/.claude — so
// platform sessions have perfect parity with terminal sessions (same config, credentials and
// transcript store, interchangeable via `claude --resume`).
const homeDir = process.env.HOME_DIR ?? homedir();
const globalToolsDir = join(DATA_PATH, 'tools');
// The email_db MCP tool reads one account's SQLite store; match the API's choice (first enabled).
@@ -60,52 +55,14 @@ if (!acquireLock()) {
loadState();
// ── CLAUDE.md refresh ──
function refreshClaudeMd(): void {
const claudeDir = join(homeDir, '.claude');
if (!existsSync(claudeDir)) mkdirSync(claudeDir, { recursive: true });
// generateContainerContext writes and returns the file path
// Import inline to avoid circular deps at module level
const { generateContainerContext } = require('../../generate-container-context') as {
generateContainerContext: (email: string) => string;
};
const contextFile = generateContainerContext(email!);
writeFileSync(join(claudeDir, 'CLAUDE.md'), readFileSync(contextFile, 'utf-8'));
}
// ── MCP config ──
type McpPaths = { sandboxPath: string; hostPath: string };
function generateMcpConfig(): McpPaths {
function generateMcpConfig(): string {
const contextDir = join(DATA_PATH, email!, '.container-context');
mkdirSync(contextDir, { recursive: true });
const userRoot = join(DATA_PATH, email!);
// Sandbox config (paths relative to /data mount)
const sandboxToolsDirs = [globalToolsDir, ...(existsSync(userToolsDir) ? [`${SANDBOX_DATA}/tools`] : [])].join(':');
const sandboxConfig = {
mcpServers: {
'officer-tools': {
type: 'stdio',
command: 'bun',
args: ['run', MCP_SERVER_SCRIPT],
env: {
PI_TOOLS_DIRS: sandboxToolsDirs,
OFFICER_EMAIL_DB: `${SANDBOX_DATA}/${emailDbRel}`,
MCP_TOOLS_LOG: `${SANDBOX_DATA}/logs/mcp-tools.log`,
OFFICER_API_URL,
OFFICER_AUTH_TOKEN,
},
},
},
};
writeFileSync(join(contextDir, 'mcp.json'), JSON.stringify(sandboxConfig));
// Host config (real filesystem paths, for Super Admin)
const hostToolsDirs = [globalToolsDir, ...(existsSync(userToolsDir) ? [userToolsDir] : [])].join(':');
const hostConfig = {
mcpServers: {
@@ -125,27 +82,16 @@ function generateMcpConfig(): McpPaths {
};
writeFileSync(join(contextDir, 'mcp-host.json'), JSON.stringify(hostConfig));
return {
sandboxPath: `${SANDBOX_DATA}/.container-context/mcp.json`,
hostPath: join(contextDir, 'mcp-host.json'),
};
return join(contextDir, 'mcp-host.json');
}
// ── Startup ──
// Only sandboxed users get the generated container CLAUDE.md. For the un-isolated Super Admin, HOME is
// the real home, so writing it there would pollute the personal global ~/.claude/CLAUDE.md (loaded by
// the terminal `claude` too) — parity means running as the user, not injecting platform context.
if (dbUser.role !== 'Super Admin') {
try {
refreshClaudeMd();
} catch (err) {
console.error(`[claude:${email}] failed to refresh CLAUDE.md:`, err instanceof Error ? err.message : err);
}
}
// The owner runs un-isolated with HOME as their real home, so the generated container CLAUDE.md is
// deliberately not written — it would pollute the personal global ~/.claude/CLAUDE.md that the
// terminal `claude` loads too.
const mcpPaths = generateMcpConfig();
setMcpConfigPath(mcpPaths.sandboxPath, mcpPaths.hostPath);
setMcpConfigPath(generateMcpConfig());
console.log(`[claude:${email}] started (HOME=${homeDir})`);
-3
View File
@@ -70,7 +70,6 @@ export type ClaudeSpawnParams = {
prompt: string;
sessionKey: string;
model?: string;
role?: string;
cwd?: string;
};
@@ -82,7 +81,6 @@ export type ClaudeSpawnStreamingParams = {
sessionKey: string;
cwd?: string;
model?: string;
role?: string;
resumeSessionId?: string; // resume this Claude session uuid (from the /chat session list)
};
@@ -108,7 +106,6 @@ export type OpenCodeRunParams = {
export type VncStartParams = {
email: string;
username: string;
role: string | null;
resolution?: string;
};
-126
View File
@@ -1,126 +0,0 @@
import { existsSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
// Resolve paths for sandbox
const BUN_DIR = (() => {
const result = Bun.spawnSync({ cmd: ['which', 'bun'], stdout: 'pipe', stderr: 'ignore' });
const binDir = dirname(result.stdout.toString().trim());
return dirname(binDir); // e.g. /home/pastilhas/.bun
})();
const PROJECT_ROOT = resolve(import.meta.dir, '../../..');
const DATA_PATH = process.env.DATA_PATH ?? join(process.cwd(), 'data');
const OFFICER_ITEMS_DIR = process.env.OFFICER_ITEMS_DIR ?? join(process.cwd(), 'officer-items');
const HOST_HOME = process.env.HOME!;
// Resolve the OS username for runuser to drop privileges inside the sandbox
const OS_USERNAME = (() => {
const result = Bun.spawnSync({ cmd: ['id', '-un'], stdout: 'pipe', stderr: 'ignore' });
return result.stdout.toString().trim() || 'pastilhas';
})();
// Sandbox mount points
export const SANDBOX_DATA = '/data';
export const SANDBOX_HOME = `${SANDBOX_DATA}/home`;
export const SANDBOX_GLOBAL_ROOT = '/officer';
export const SANDBOX_GLOBAL_SKILLS = `${SANDBOX_GLOBAL_ROOT}/skills`;
export const SANDBOX_GLOBAL_EXTENSIONS = `${SANDBOX_GLOBAL_ROOT}/extensions`;
export const SANDBOX_GLOBAL_TOOLS = `${SANDBOX_GLOBAL_ROOT}/tools`;
// Build bwrap sandbox prefix for a given user email.
// Returns args up to (but not including) the `-- runuser` suffix.
// Callers can append extra `--setenv` args before calling `buildRunuserSuffix()`.
export function buildSandboxPrefix(email: string): string[] {
const userDataDir = join(DATA_PATH, email);
const globalSkillsDir = join(OFFICER_ITEMS_DIR, 'skills');
const globalToolsDir = join(OFFICER_ITEMS_DIR, 'tools');
const globalExtensionsDir = join(OFFICER_ITEMS_DIR, 'extensions');
const args = [
'sudo',
'bwrap',
'--share-net',
'--die-with-parent',
'--proc',
'/proc',
'--dev',
'/dev',
'--perms',
'1777',
'--tmpfs',
'/tmp',
// System (read-only)
'--ro-bind',
'/usr',
'/usr',
'--ro-bind',
'/lib',
'/lib',
'--ro-bind',
'/bin',
'/bin',
'--ro-bind',
'/etc',
'/etc',
// /run is needed for systemd-resolved DNS (resolv.conf symlink target)
'--ro-bind',
'/run',
'/run',
];
// Optional system paths
if (existsSync('/lib64')) args.push('--ro-bind', '/lib64', '/lib64');
if (existsSync('/sbin')) args.push('--ro-bind', '/sbin', '/sbin');
// Ensure intermediate dirs under HOME are traversable after runuser drops privileges
// (bwrap auto-creates them as root-owned drwx------)
const homeDir = HOST_HOME;
args.push('--perms', '0755', '--dir', homeDir);
// Bun runtime (e.g. /home/pastilhas/.bun)
args.push('--ro-bind', BUN_DIR, BUN_DIR);
// User-local installs (~/.local) — claude binary, pi npm packages, etc.
const localDir = join(homeDir, '.local');
if (existsSync(localDir)) {
args.push('--ro-bind', localDir, localDir);
}
// Project source (for MCP server)
args.push('--ro-bind', PROJECT_ROOT, PROJECT_ROOT);
// Ensure DATA_PATH intermediate dirs are traversable (same issue as HOME)
args.push('--perms', '0755', '--dir', DATA_PATH);
// Global content mounted at original paths for existing host-path references
if (existsSync(globalSkillsDir)) args.push('--ro-bind', globalSkillsDir, globalSkillsDir);
if (existsSync(globalToolsDir)) args.push('--ro-bind', globalToolsDir, globalToolsDir);
if (existsSync(globalExtensionsDir)) args.push('--ro-bind', globalExtensionsDir, globalExtensionsDir);
// Ensure sandbox-local global root is traversable before mounting nested paths under it.
args.push('--perms', '0755', '--dir', SANDBOX_GLOBAL_ROOT);
// Global content also mounted at short sandbox-local paths so nested imports do not
// depend on traversing host-specific parent directories created by bwrap.
if (existsSync(globalSkillsDir)) args.push('--ro-bind', globalSkillsDir, SANDBOX_GLOBAL_SKILLS);
if (existsSync(globalToolsDir)) args.push('--ro-bind', globalToolsDir, SANDBOX_GLOBAL_TOOLS);
if (existsSync(globalExtensionsDir)) args.push('--ro-bind', globalExtensionsDir, SANDBOX_GLOBAL_EXTENSIONS);
// User data (read-write, mounted at /data to avoid intermediate dir permission issues)
args.push('--bind', userDataDir, SANDBOX_DATA);
// Common env vars inside the sandbox (sudo strips the environment)
args.push('--setenv', 'HOME', SANDBOX_HOME);
args.push('--setenv', 'PATH', process.env.PATH ?? '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin');
// Set working directory inside the sandbox
args.push('--chdir', SANDBOX_HOME);
return args;
}
// Build the runuser suffix that drops privileges to the OS user.
// Append this after any extra --setenv args.
export function buildRunuserSuffix(): string[] {
return ['--', 'runuser', '--preserve-environment', '-u', OS_USERNAME, '--'];
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync } from 'node:fs';
import { join } from 'node:path';
import type { VncStartParams, VncSessionInfo } from '../protocol';
import { getHomeDirForRole } from '@@/data-path';
import { getOwnerHomeDir } from '@@/data-path';
// Mirrors the physical display instead of spawning a virtual desktop per user, so the
// browser shows the same session as the screen. There is exactly one :0, hence one
@@ -106,7 +106,7 @@ export async function startSession(params: VncStartParams): Promise<{ port: numb
}
mirror = null;
const homeDir = getHomeDirForRole(params.email, params.role);
const homeDir = getOwnerHomeDir(params.email);
const passwdFile = await ensureVncPassword(homeDir);
const xauthority = resolveXauthority();