Compare commits

...
Author SHA1 Message Date
Codeman maintainer c51a7134eb fix(install): a headless run with a passwordless sudo gets past the sudo step
A non-root account with a working passwordless sudo and no controlling
terminal (su - user -c, cron, a CI runner, cloud-init) ended on "Failed to
obtain sudo privileges". The /dev/tty node exists there and cannot be opened;
install.sh tested [[ -e /dev/tty ]] and then ran sudo -v < /dev/tty, whose
redirect fails before sudo starts. Measured 2026-11-27 in a fresh ubuntu:24.04
container: node present, open refused, sudo -n true fine, install dead at
"Installing Git via apt".

- tty_openable() opens the node, the probe has_tty() already used, and every
  redirect from /dev/tty now sits behind it instead of a file test:
  ensure_sudo, sudo_session_try, the message choice in sudo_session_start,
  and the three sites with the same shape (Homebrew, the Tailscale installer,
  tailscale up). With no terminal they fall back to the plain command.
- ensure_sudo returns as soon as sudo -n true works. sudo -v is no substitute
  for that test: it asks for a password as soon as one sudoers entry of the
  account asks for one, so an account in the sudo group with a NOPASSWD entry
  of its own (the cloud-image layout) runs sudo <command> freely and is
  refused by sudo -v (measured on sudo 1.9.15).

test/install-sh-invariants.test.ts fails for a file test on /dev/tty and for
a redirect from it that is not directly under the probe, and drives the sudo
helpers in a real bash with no controlling terminal against a stub sudo.

Checked in a throwaway ubuntu:24.04 container, through su - user -c with
CODEMAN_NONINTERACTIVE=1: the installer before this change stops at the sudo
step, this one installs git, tmux, Node.js and the build tools, clones and
was building when the check was stopped. The helpers were also run under
bash 3.2.57. The Homebrew branch could not be run here (no macOS).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 17:54:43 +01:00
Codeman maintainer d9fce03444 fix(launch): a server running as root starts Claude without the bypass flag
Installed and started as root (a VPS, an LXC container), every local Claude
session died at once: the default permission mode launches Claude Code with
--dangerously-skip-permissions, and Claude Code refuses that flag under uid 0
("cannot be used with root/sudo privileges for security reasons", pane dead
with status 1). Shell sessions were fine. Measured 2026-11-27 with the public
installer in a fresh ubuntu:24.04 container.

Docker cases already answer the same refusal for a root container with
overlays.docker.rootCommand. This is the host-level form, as registry data:

- An enum launch param may declare rootValue, a map from a value to the value
  it takes when the server process runs as uid 0 and the launch is local.
  Claude declares claudeMode: dangerously-skip-permissions -> normal. The
  schema holds keys and replacements to the param's values.
- applyRootValues() (config/cli-registry/root-launch.ts, pure) rewrites the
  param values before the argv engine sees them and hands back the object it
  was given when nothing changes, so a launch that is not root is
  byte-identical (the spawn goldens are untouched).
- serverRunsAsRoot() (utils/server-uid.ts) reads the uid at call time. Under
  vitest it answers false unless a test stubs it.
- The uid is asked in two places only. serverRootSpawnOptions() feeds the two
  tmux launches (createSession, respawnPane), which every local tmux launch
  goes through: new session, resume, dead-pane respawn, restartCli(), cron,
  quick-start, reboot restore. buildPermissionArgs() covers the two launches
  with no tmux, the direct-PTY fallback and the one-shot run.
- Remote and Docker pane commands never read it, and auto, allowedTools and
  normal are passed through unchanged. IS_SANDBOX is not set.
- Each swap is logged once per launch, naming the cause and the way out.

Checked end to end in a throwaway ubuntu:24.04 container running this tree's
server as root with Claude Code 2.1.332: the pane command carries no bypass
flag, the pane stays alive on Claude's first-run screen, and the log line is
there. The same run as an ordinary user keeps the flag.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 17:54:43 +01:00
19 changed files with 984 additions and 21 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"aicodeman": patch
---
Claude sessions now start when Codeman itself runs as root (a VPS, an LXC container): Claude Code refuses `--dangerously-skip-permissions` under root and every local Claude tab showed a dead pane, so a root server now starts Claude without the bypass (it asks for permission instead) and says so in the server log.
+5
View File
@@ -0,0 +1,5 @@
---
"aicodeman": patch
---
The installer no longer stops on "Failed to obtain sudo privileges" in a headless run with a working passwordless sudo (`su - user -c`, cron, a CI runner, cloud-init): it now checks whether `/dev/tty` can be opened before taking sudo's input from it, where it used to test only that the node exists.
+1 -1
View File
@@ -186,7 +186,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph
**Docker Compose deployment** (`docker/`): Codeman runs in a container and spawns Docker cases as **SIBLING** containers via the host socket, never nested. `resolveDockerDaemonMountSource()` maps HOME bind sources into the daemon's namespace (`CODEMAN_DOCKER_HOST_HOME`); `CODEMAN_CASES_PATH` makes workspaces resolve to the same absolute path on both sides. ⚠️ `CODEMAN_CASES_PATH` must move every consumer: resolve it only via `config/cases-dir.ts`. ⚠️ `.dockerignore` matches whole paths: keep `**/.env` or `docker/.env` secrets ship in the image. ⚠️ Long-form binds create missing sources ROOT-OWNED: `Start-Codeman.sh` pre-creates them, and `docker/entrypoint.sh` (root, `cap_add: [CHOWN, DAC_OVERRIDE, KILL, SETGID, SETUID]` against `cap_drop: ALL`, `KILL` for tini; pinned by the test) fixes ownership then drops to `PUID:PGID` via `setpriv`, never re-owning foreign dirs. ⚠️ Append `/opt/codeman-cli` and `~/.local/bin` to `PATH`, never prepend. ⚠️ `server.Dockerfile`, the compose file and `.env.example` feed the self-updater's environment gate (`docs/docker-self-update.md`). → [architecture-invariants#docker-compose-deployment](docs/architecture-invariants.md#docker-compose-deployment), `docs/docker-compose.md`
**CLI registry** (`src/config/cli-registry/`): every run mode is a `CliEntry` (discovery, launch argv template, env handling, `capabilities`, and the `overlays` behind remote/docker pane commands). **No code outside `stock.ts` may branch on a CLI id**: use a capability field or a NAMED PROFILE (`profiles.ts`); `test/cli-registry-no-id-branching.test.ts` and `test/frontend-cli-no-id-branching.test.ts` enforce it. ⚠️ Config holds typed argv tokens, never shell text; literals are validated at LOAD time and a bad one rejects the whole entry. ⚠️ Keep `external`, `hooks` and `altScreen` independent; never derive one from another. ⚠️ Config regexes (`discovery.version.regex`, `capabilities.workDetect.workingLine`, `capabilities.workDetect.watchingLine`, `capabilities.workDetect.awaitingLine`, `capabilities.workDetect.blockedLine`, `capabilities.workDetect.composerFooterLine`, `capabilities.workDetect.composerPopupLine`, `capabilities.modelDetect.screenLine`) must compile through `compileVersionRegex()`. ⚠️ `privilegedParams[].param` names a LAUNCH PARAM, not the legacy `<Mode>Config` field (bridged only by `launch.legacyConfigAliases`); a wrong name silently clamps nothing. ⚠️ Resolve the registry AT CALL TIME, never in a module-level const. ⚠️ Remote claude/omp arms of `buildRemoteLaunchCommand` are not covered by the pane-command golden. `~/.codeman/clis.json` overrides entries. It is WRITTEN only by the opt-in CLI management routes (`cliManagementEnabled`, default OFF; `/api/clis`, `cli-registry-routes.ts`), and only through `mutateRegistryFile()` in `registry-writer.ts` (the one exception: a config-backup restore of `clis.json`, which then calls `reloadCliRegistry()`), which serializes mutations and refuses (409) a file that does not parse or has group/world permission bits rather than overwriting it. Importing the registry still writes nothing. → [architecture-invariants#cli-registry](docs/architecture-invariants.md#cli-registry), `docs/cli-registry.md`
**CLI registry** (`src/config/cli-registry/`): every run mode is a `CliEntry` (discovery, launch argv template, env handling, `capabilities`, and the `overlays` behind remote/docker pane commands). **No code outside `stock.ts` may branch on a CLI id**: use a capability field or a NAMED PROFILE (`profiles.ts`); `test/cli-registry-no-id-branching.test.ts` and `test/frontend-cli-no-id-branching.test.ts` enforce it. ⚠️ Config holds typed argv tokens, never shell text; literals are validated at LOAD time and a bad one rejects the whole entry. ⚠️ Keep `external`, `hooks` and `altScreen` independent; never derive one from another. ⚠️ Config regexes (`discovery.version.regex`, `capabilities.workDetect.workingLine`, `capabilities.workDetect.watchingLine`, `capabilities.workDetect.awaitingLine`, `capabilities.workDetect.blockedLine`, `capabilities.workDetect.composerFooterLine`, `capabilities.workDetect.composerPopupLine`, `capabilities.modelDetect.screenLine`) must compile through `compileVersionRegex()`. ⚠️ `privilegedParams[].param` names a LAUNCH PARAM, not the legacy `<Mode>Config` field (bridged only by `launch.legacyConfigAliases`); a wrong name silently clamps nothing. ⚠️ Resolve the registry AT CALL TIME, never in a module-level const. ⚠️ Remote claude/omp arms of `buildRemoteLaunchCommand` are not covered by the pane-command golden. ⚠️ A server that runs as root (uid 0) starts a LOCAL claude without the bypass flag, which Claude Code refuses under root (a dead pane on every session): the swap is the enum param's `rootValue` (`root-launch.ts`, pure), asked through `serverRunsAsRoot()` at call time by `serverRootSpawnOptions()` (both tmux launches) and `buildPermissionArgs()` (direct PTY, one-shot) only, logged once per launch; never an id branch, never `IS_SANDBOX`, never for a remote or Docker launch, and not root stays byte-identical (`test/root-launch.test.ts`). `~/.codeman/clis.json` overrides entries. It is WRITTEN only by the opt-in CLI management routes (`cliManagementEnabled`, default OFF; `/api/clis`, `cli-registry-routes.ts`), and only through `mutateRegistryFile()` in `registry-writer.ts` (the one exception: a config-backup restore of `clis.json`, which then calls `reloadCliRegistry()`), which serializes mutations and refuses (409) a file that does not parse or has group/world permission bits rather than overwriting it. Importing the registry still writes nothing. → [architecture-invariants#cli-registry](docs/architecture-invariants.md#cli-registry), `docs/cli-registry.md`
**External CLI modes (OpenCode, Codex, Gemini, Antigravity, Pi, Grok, DeepSeek, OMP, Copilot, jcode)**: `isExternalCliMode()` in `session.ts` gates Claude-specific behavior off (Ralph tracker, BashToolParser, token parsing, ❯ readiness; readiness is output stabilization); work detection is per-CLI `capabilities.workDetect` data, not this gate. All ten **require tmux, no direct PTY fallback** (secrets go via socket-scoped `tmux setenv`, never the command line). ⚠️ `run*()` in `session-ui.js` MUST unwrap the `{success,data}` envelope. ⚠️ **Codex uses predictive write-through echo, never the buffer overlay**: `_predictHookOnData` must never `return` (wire path stays byte-identical), and flushed text and a bracketed paste must go out as separate delayed writes. ⚠️ **Pi**: no bypass flag, never invent one; `approveProjectTrust` executes repo code, so it is in the clamp's **materialize** branch; never wire `--api-key`. ⚠️ **Grok**: `alwaysApprove` is stripped for non-granted owners (only-if-sent). ⚠️ **DeepSeek**: the agent is a PROFILE (Run gates on `isDeepSeekRunnable()`); the permission switch is the `DSH_PERMISSION_MODE` env var, so `clampEnvOverridesForOwner()` must DROP `DSH_PERMISSION_MODE`, `DSH_HOME` and `DEEPSEEK_BASE_URL` for non-granted owners; `hooksAvailableForMode()` is per-SESSION for it (pass `sessionHookOptions(session)`) and is never a stand-in for `mode === 'claude'`; answers come from `deepseek-transcript.ts`, paired by header `cwd` + boot window, never newest-mtime. ⚠️ **OMP**: `OMP_AUTH_BROKER_URL`/`_TOKEN` are clamped the same way. ⚠️ **Copilot**: `allowAll` (`--yolo`) is a `privilegedParam` and `COPILOT_HOME`/`COPILOT_ALLOW_ALL`/`COPILOT_PROVIDER_*`/`COPILOT_MODEL` are privileged env keys, and so is every other `COPILOT_*` variable the CLI reads that switches approvals, runs code with no approval row or sends its sign-in token elsewhere (the 1.0.98 list is in `stock.ts`; the prefix admits whatever a later release adds, so re-read the bundle whenever the measured version moves); the resume id must start with a letter or digit (`path-segment`), since `--resume`'s value is optional and `--resume --yolo` would otherwise make `--yolo` its own flag; `--name` is dropped next to `--resume`/`--continue` (Copilot refuses the pair); its mouse DECSETs are stripped (`strip-mux-and-mouse`) so a drag selects and the wheel is forwarded by `_shouldForwardWheelToApp` while `cliMouseTracking` is on; `composerReadyMark` is the footer hint `/ commands · ? help`, NOT `❯` (the folder-trust dialog draws `❯ 1. Yes`); `last-response` reads the pane's visible screen (`transcriptNeedsScreenCapture`) through a per-CLI `PANE_DIALECTS` row, because its stream is cursor moves, not lines (a prompt row scrolled off by a tall answer reads as the answer's tail unless a banner/trust dialog is on screen, and typed composer text is not a prompt); Docker seeds no Copilot credential (`config.json` holds a plain-text token without a keyring). ⚠️ **jcode**: every pane is a client of ONE shared per-user daemon and the tools run in the daemon with ITS env, so jcode gets no agent skill and no `JCODE_*` envOverrides prefix (a per-session value would act as another session or reach every one); `last-response` is an honest empty (external + `transcript: 'none'`, never the segmenter or the Claude scan); ⚠️ that daemon is a descendant of whichever pane started it, so `capabilities.sharedDaemon` makes `killSession` spare descendants outside the pane's process group (`descendantsInPaneGroup()`, `proc-tree.ts`), or closing that one tab cuts every other jcode session off; it resolves through the generic registry resolver, with no per-CLI resolver module (`docs/jcode-integration.md`). → [architecture-invariants#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp](docs/architecture-invariants.md#external-cli-modes-opencode-codex-gemini-antigravity-pi-grok-deepseek-omp)
+6
View File
@@ -298,6 +298,12 @@ The allowlist is not a formality. If a branch is about what a CLI can DO it belo
This matters because it is invisible when it is wrong. `capabilities.privilegedParams[].param` is the multi-user bypass clamp's only handle on a CLI's privilege switch, and a name from the wrong namespace clamps **nothing**: no load error, no failing test, the clamp simply stops running. Codex is the entry where the two names differ (`bypassApprovals` as the param, `dangerouslyBypassApprovals` on the wire), so it is the one that catches a regression. `schema.ts` rejects any entry naming a param it never declared, on both `configSetenv.fromParam` and `privilegedParams.param`.
## A server that runs as root (`rootValue`)
An `enum` launch param may declare `rootValue`: a map from a value to the value it takes instead when the Codeman **server process** runs as uid 0 and the launch is **local**, where the CLI is the server's child and so runs as root too. Claude declares the one entry there is, `claudeMode: { 'dangerously-skip-permissions': 'normal' }`, because Claude Code exits on `--dangerously-skip-permissions` under root and that mode is the default: on a server installed as root (a VPS, an LXC container) every local Claude session was a dead pane. It is the host-level form of `overlays.docker.rootCommand`, which answers the same refusal by the container's uid.
`applyRootValues()` (`root-launch.ts`, pure) rewrites the param values before the argv engine sees them and hands back the object it was given when nothing changes, so a launch that is not root is byte-identical. The uid is asked at call time through `serverRunsAsRoot()` (`utils/server-uid.ts`; under vitest it answers `false` unless a test stubs it), and only by the local launch sites: `serverRootSpawnOptions()` for the two tmux launches (`createSession`, `respawnPane`) and `buildPermissionArgs()` for the direct-PTY fallback and the one-shot run. Remote and Docker pane commands never read it. Each swap is logged once per launch. The schema requires every key and every replacement to be one of the param's `values`, and refuses a replacement that is itself replaced. Tests: `test/root-launch.test.ts`.
## Fields declared for later
`accent`, `capabilities.echo`, `capabilities.keyboardAccessory` and `capabilities.maxFrameBytes` are **declared but not yet read**. (`shortBadge` was on this list until the CLI management list in Settings started showing it, and `capabilities.wheelForward` until the browser's wheel gate started reading it, see below.) They all describe frontend behaviour, and the frontend is deliberately untouched here: `app.js`, `terminal-ui.js` and `styles.css` keep their own hand-authored per-CLI rules, and moving them is its own piece of work verified by a browser/mobile suite the CI gate cannot see.
+3 -1
View File
@@ -110,7 +110,9 @@ approve those steps. With nothing else said, that also installs the first agent
catalogue when none is found; `--ai-cli` (or `CODEMAN_AI_CLI`) says which one, or none.
`CODEMAN_TAILSCALE=1` preselects the Tailscale answer, and never
installs Tailscale itself non-interactively; a non-interactive run never renames the
machine and never starts a service. Everything the unattended steps print goes to
machine and never starts a service. With no terminal there is nowhere to type a password,
so a step that needs `sudo` works only where `sudo` asks for none (a `NOPASSWD` entry, as
cloud images and CI runners have). Everything the unattended steps print goes to
`~/.codeman/install.log`, and the last lines of it are shown when a step fails.
### Without administrator rights
+11
View File
@@ -131,6 +131,17 @@ That prompt comes from Claude Code, not Codeman. Codeman's default is to start w
permission prompts skipped, which is what the security model is built around. If you would
rather it prompted, change **App Settings → Agents & CLIs → Claude → Startup Mode**.
### Claude asks for permission although Startup Mode skips the prompts (Codeman runs as root)
When the Codeman server itself runs as root (common on a VPS and in an LXC container),
Claude sessions start without the permission bypass and ask before they act. Claude Code
refuses `--dangerously-skip-permissions` under root and exits, which on older versions left
every Claude tab with a dead pane (`--dangerously-skip-permissions cannot be used with
root/sudo privileges for security reasons`). Codeman now leaves the flag out there and writes
one line to the server log for each such launch; the other startup modes are passed through
unchanged. Run Codeman as a normal user to get the default back. A session in a Docker case
or on a remote host runs under the account on that side, so this does not apply to it.
### My settings were reset, or a CLI I enabled is gone
Something rewrote a file in `~/.codeman/` (a hand edit, a restart that loaded a bad file, a
+35 -10
View File
@@ -1185,9 +1185,20 @@ ensure_sudo() {
if ! command -v sudo &>/dev/null; then
die "sudo is required but not installed. Please install packages manually or run as root."
fi
# A sudo that runs without a password (NOPASSWD, or the timestamp
# sudo_session_try keeps warm) needs no terminal and nothing validated.
# `sudo -v` is no substitute for this test: it asks for a password as soon as
# ONE sudoers entry of the account asks for one, so an account in the sudo
# group with a NOPASSWD entry of its own (the cloud-image layout) runs
# `sudo <command>` freely and is refused by `sudo -v` (measured on sudo 1.9.15).
if sudo -n true 2>/dev/null; then
return 0
fi
# Validate sudo access
# When piped (curl | bash), stdin is the pipe — redirect from /dev/tty so sudo can prompt
if [[ -e /dev/tty ]]; then
# When piped (curl | bash), stdin is the pipe: redirect from /dev/tty so sudo can prompt.
# Only when it can be opened (see tty_openable): with no terminal at all, sudo gets
# its chance as it is and fails by itself when it would have to ask.
if tty_openable; then
if ! sudo -v 2>/dev/null < /dev/tty; then
die "Failed to obtain sudo privileges."
fi
@@ -1217,8 +1228,9 @@ ensure_homebrew() {
fi
info "Installing Homebrew first..."
# When piped (curl | bash), stdin is the pipe — Homebrew needs TTY for sudo password prompt
if [[ -e /dev/tty ]]; then
# When piped (curl | bash), stdin is the pipe: Homebrew needs TTY for sudo password prompt.
# With no terminal to open (see tty_openable) it runs unattended instead.
if tty_openable; then
/bin/bash -c "$(download_to_stdout https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" < /dev/tty
else
NONINTERACTIVE=1 /bin/bash -c "$(download_to_stdout https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
@@ -2019,9 +2031,21 @@ fetch_source_archive() {
# the keyboard even though the user is sitting at a terminal. These helpers
# prompt via /dev/tty whenever a real terminal is available, and only fall back
# to defaults when there is genuinely none (CI, truly headless pipes).
# True when /dev/tty can really be OPENED. The node is there on every Linux and
# macOS, also for a process with no controlling terminal (su -c, cron, a CI
# runner, cloud-init, a container started without -t): `[[ -e /dev/tty ]]` says
# yes there, and a `< /dev/tty` behind it fails before the command ever runs.
# That ended a headless install with a working passwordless sudo on "Failed to
# obtain sudo privileges". Opening the node is the only test, so every redirect
# from /dev/tty asks this first, never `-e`.
tty_openable() {
{ : < /dev/tty; } 2>/dev/null
}
has_tty() {
[[ -t 0 ]] && return 0
{ : < /dev/tty; } 2>/dev/null
tty_openable
}
read_reply() {
@@ -2102,7 +2126,7 @@ sudo_session_try() {
if ! sudo -n true 2>/dev/null; then
echo "" >&2
info "Some steps need administrator rights. You will be asked for your password once."
if [[ -e /dev/tty ]]; then
if tty_openable; then
sudo -v < /dev/tty || return 1
else
sudo -v || return 1
@@ -2124,7 +2148,7 @@ sudo_session_start() {
if sudo_session_try; then
return 0
fi
if [[ -e /dev/tty ]]; then
if tty_openable; then
die "Failed to obtain sudo privileges."
fi
die "Failed to obtain sudo privileges. Try running the script directly instead of piping."
@@ -2920,8 +2944,9 @@ offer_install_tailscale() {
sudo_session_start
info "Running the official Tailscale installer..."
# When piped (curl | bash), stdin is our pipe: give the child installer
# the real terminal so its own sudo prompt works.
if [[ -e /dev/tty ]]; then
# the real terminal so its own sudo prompt works. A run with no terminal
# to open (see tty_openable) hands it stdin as it is.
if tty_openable; then
if ! sh -c "$(download_to_stdout https://tailscale.com/install.sh)" < /dev/tty; then
warn "Tailscale installation failed."
return 1
@@ -2966,7 +2991,7 @@ ensure_tailscale_login() {
if "$ts_bin" up --timeout=300s; then up_ok="1"; fi
else
sudo_session_start
if [[ -e /dev/tty ]]; then
if tty_openable; then
if run_as_root "$ts_bin" up --timeout=300s < /dev/tty; then up_ok="1"; fi
else
if run_as_root "$ts_bin" up --timeout=300s; then up_ok="1"; fi
+16 -5
View File
@@ -71,6 +71,20 @@ function renderToken(value: string, style: QuoteStyle | undefined): string {
}
}
/**
* The value an enum param resolves to: the caller's when it is a declared one, else the
* default. Exported so `applyRootValues()` (root-launch.ts) judges the same value the
* renderer is about to emit, rather than restating this rule.
*/
export function resolveEnumValue(
spec: Extract<ParamSpec, { type: 'enum' }>,
raw: string | boolean | undefined
): string | undefined {
if (raw === undefined) return spec.default;
const s = String(raw);
return spec.values.includes(s) ? s : spec.default;
}
/** Resolve one parameter to a plain string, or undefined if it is unset / invalid. */
function resolveParam(
name: string,
@@ -82,13 +96,10 @@ function resolveParam(
if (spec.type === 'engine') return engineValues[spec.source];
const raw = params[name];
if (raw === undefined) return spec.type === 'enum' ? spec.default : undefined;
if (spec.type === 'enum') return resolveEnumValue(spec, raw);
if (raw === undefined) return undefined;
if (spec.type === 'bool') return typeof raw === 'boolean' ? String(raw) : undefined;
if (spec.type === 'enum') {
const s = String(raw);
return spec.values.includes(s) ? s : spec.default;
}
// token
const s = String(raw);
return matchesPattern(spec.pattern, s) ? s : undefined;
+79
View File
@@ -0,0 +1,79 @@
/**
* @fileoverview The launch params a CLI takes a different value for when it is started as
* root. Pure: the caller says whether the launch runs as root, this module never asks.
*
* Claude Code refuses `--dangerously-skip-permissions` under uid 0 and exits, so a Codeman
* server that runs as root (a VPS, an LXC container) showed a dead pane for every local
* Claude session, the default permission mode being exactly that flag. Docker cases already
* answer the same refusal for a root container with `overlays.docker.rootCommand`; this is
* the host-level form, for a CLI the server process starts as its own child.
*
* Which value gives way to which is registry DATA (`ParamSpec.rootValue` on an enum param),
* so no code here or at the call sites names a CLI. `applyRootValues()` runs BEFORE the argv
* engine and only rewrites the param values handed to it: the engine, and with it every
* command line of a launch that is not root, is untouched.
*
* ⚠️ Local launches only. A remote or Docker launch runs under another account, which the
* server's uid says nothing about; those keep their own handling (`buildRemoteLaunchCommand`,
* `rootCommand`). The callers decide that, by passing `runsAsRoot` false.
*
* @module config/cli-registry/root-launch
*/
import { resolveEnumValue, type ParamValues } from './argv.js';
import type { CliLaunch } from './types.js';
/** One param that was launched with its `rootValue` instead of the value it resolved to. */
export interface RootValueChange {
param: string;
from: string;
to: string;
}
/**
* Apply every declared `rootValue` to `params`.
*
* Returns the SAME `params` object when nothing changes (not root, or no param whose
* resolved value has a replacement), so a caller can rely on a launch that is not root
* rendering from exactly the values it passed in. Otherwise a copy, with `changes` naming
* what was swapped so the caller can log it.
*
* The value judged is the one the renderer would emit: an absent or undeclared value counts
* as the param's default, which is how the default permission mode is caught although no
* caller ever sends it.
*/
export function applyRootValues(
launch: CliLaunch,
params: ParamValues,
runsAsRoot: boolean
): { params: ParamValues; changes: RootValueChange[] } {
const changes: RootValueChange[] = [];
if (!runsAsRoot) return { params, changes };
let out = params;
for (const [name, spec] of Object.entries(launch.params)) {
if (spec.type !== 'enum' || !spec.rootValue) continue;
const from = resolveEnumValue(spec, params[name]);
if (from === undefined || !Object.hasOwn(spec.rootValue, from)) continue;
const to = spec.rootValue[from];
// Schema-validated at load; belt and braces, since a value outside `values` would
// resolve back to the default, which is the very value being replaced.
if (to === from || !spec.values.includes(to)) continue;
if (out === params) out = { ...params };
out[name] = to;
changes.push({ param: name, from, to });
}
return { params: out, changes };
}
/**
* The one log line for a launch that took a `rootValue`. `what` names the launch ("Claude
* Code session 0f9c2b14"); the wording stays free of any CLI's vocabulary because the
* params and values in it are the registry's own.
*/
export function describeRootValueChanges(what: string, changes: readonly RootValueChange[]): string {
const swapped = changes.map((c) => `${c.param} "${c.from}" as "${c.to}"`).join(', ');
return (
`${what} is launched with ${swapped}: the Codeman server runs as root (uid 0), and the CLI refuses ` +
`the configured value under root. Run Codeman as a normal user to get the configured value back.`
);
}
+30 -1
View File
@@ -67,7 +67,13 @@ const condSchema: z.ZodType<import('./types.js').Cond> = z.lazy(() =>
const paramSpecSchema = z.union([
z
.object({ type: z.literal('enum'), values: z.array(z.string()).min(1).max(16), default: z.string().optional() })
.object({
type: z.literal('enum'),
values: z.array(z.string()).min(1).max(16),
default: z.string().optional(),
// Cross-checked against `values` in launchSchema's superRefine below.
rootValue: z.record(z.string(), z.string()).optional(),
})
.strict(),
z.object({ type: z.literal('bool') }).strict(),
z.object({ type: z.literal('token'), pattern: z.enum(TOKEN_PATTERNS as [string, ...string[]]) }).strict(),
@@ -145,6 +151,29 @@ const launchSchema = z
});
}
}
// `rootValue` swaps one declared value for another when the server runs as root. A key or
// a replacement outside `values` could never apply (or would launch with a value no arg
// tests for), and a replacement that is itself replaced would make the outcome depend on
// how many passes the reader makes.
for (const [paramName, spec] of Object.entries(launch.params)) {
if (spec.type !== 'enum' || !spec.rootValue) continue;
for (const [from, to] of Object.entries(spec.rootValue)) {
const path = ['params', paramName, 'rootValue', from];
if (!spec.values.includes(from)) {
ctx.addIssue({ code: 'custom', message: `rootValue key "${from}" is not one of this param's values`, path });
}
if (!spec.values.includes(to)) {
ctx.addIssue({ code: 'custom', message: `rootValue "${to}" is not one of this param's values`, path });
}
if (to === from || Object.hasOwn(spec.rootValue, to)) {
ctx.addIssue({
code: 'custom',
message: `rootValue "${to}" must be a value that is launched as it is under root`,
path,
});
}
}
}
if (launch.legacyConfigAliases) {
for (const paramName of Object.keys(launch.legacyConfigAliases)) {
if (!paramNames.has(paramName)) {
+7
View File
@@ -142,6 +142,13 @@ const CLAUDE: CliEntry = {
type: 'enum',
values: ['dangerously-skip-permissions', 'auto', 'normal', 'allowedTools'],
default: 'dangerously-skip-permissions',
// ⚠️ Claude Code REFUSES the bypass flag under uid 0 ("cannot be used with root/sudo
// privileges for security reasons") and exits, so under a server that runs as root (a
// VPS, an LXC container) every local session was a dead pane, this being the default.
// There it starts as `normal` and asks. The same refusal `overlays.docker.rootCommand`
// below answers for a root container; the other three modes do not carry the flag
// and stay as they are. Never force the bypass back on with `IS_SANDBOX`.
rootValue: { 'dangerously-skip-permissions': 'normal' },
},
allowedTools: { type: 'token', pattern: 'tool-list' },
model: { type: 'token', pattern: 'model-claude' },
+19 -1
View File
@@ -45,7 +45,25 @@ export type EngineValue =
* the only ones that need a pattern; `engine` params are produced in code.
*/
export type ParamSpec =
| { type: 'enum'; values: string[]; default?: string }
| {
type: 'enum';
values: string[];
default?: string;
/**
* The value this param takes INSTEAD when the Codeman server process runs as uid 0 and
* the launch is LOCAL (the CLI is then a child of that process, so it runs as root too).
* Keyed by the value the param would otherwise resolve to, the default included; a
* value with no key is launched as it is.
*
* For a value the CLI REFUSES under root, where the alternative is a pane that dies at
* once. It is the host-level form of `overlays.docker.rootCommand`, which answers the
* same refusal for a container whose exec user is uid 0. Remote and Docker launches
* never read it: the server's uid says nothing about the account on the other side.
* Applied by `applyRootValues()` (root-launch.ts); the schema requires every key and
* every replacement to be one of `values`, and no replacement to be replaced again.
*/
rootValue?: Record<string, string>;
}
| { type: 'bool' }
| { type: 'token'; pattern: TokenPattern }
| { type: 'engine'; source: EngineValue };
+39 -1
View File
@@ -14,12 +14,50 @@ import { getAugmentedPath } from './utils/index.js';
import { compareVersions } from './utils/dependency-checker.js';
import { dataPath } from './config/instance.js';
import { getCli } from './config/cli-registry/registry.js';
import { applyRootValues, describeRootValueChanges } from './config/cli-registry/root-launch.js';
import { serverRunsAsRoot } from './utils/server-uid.js';
/** Narrow a registry value back to the wire type; anything else keeps the caller's own mode. */
function isClaudeMode(value: unknown): value is ClaudeMode {
return value === 'dangerously-skip-permissions' || value === 'auto' || value === 'normal' || value === 'allowedTools';
}
/**
* The permission mode a claude process started DIRECTLY by this server gets (the direct-PTY
* fallback and the one-shot `-p` run, both children of the server process).
*
* Under a server that runs as root the bypass mode gives way to the registry's declared
* `rootValue` (`normal`): Claude Code exits on `--dangerously-skip-permissions` under uid 0.
* The tmux path applies the same registry data through `serverRootSpawnOptions()`; this is
* its counterpart for the two launches that never reach the argv engine. Pure: the caller
* says whether the server is root, and `onChange` gets the log line when the mode moved.
*/
export function directLaunchClaudeMode(
claudeMode: ClaudeMode,
runsAsRoot: boolean,
onChange?: (line: string) => void
): ClaudeMode {
const launch = getCli('claude')?.launch;
if (!launch) return claudeMode;
const { params, changes } = applyRootValues(launch, { claudeMode }, runsAsRoot);
const effective = params.claudeMode;
if (changes.length === 0 || !isClaudeMode(effective)) return claudeMode;
onChange?.(describeRootValueChanges('A directly started Claude Code process', changes));
return effective;
}
/**
* Build Claude CLI permission flags based on the configured mode.
* Returns an array of args to pass to the CLI.
*
* ⚠️ Both direct launches (`buildInteractiveArgs`, `buildPromptArgs`) get their flags here,
* so this is where the root downgrade is applied for them: see `directLaunchClaudeMode`.
* The uid is asked at call time (`serverRunsAsRoot()`), never cached.
*/
function buildPermissionArgs(claudeMode: ClaudeMode, allowedTools?: string): string[] {
function buildPermissionArgs(configuredMode: ClaudeMode, allowedTools?: string): string[] {
const claudeMode = directLaunchClaudeMode(configuredMode, serverRunsAsRoot(), (line) =>
console.warn(`[Session] ${line}`)
);
switch (claudeMode) {
case 'dangerously-skip-permissions':
return ['--dangerously-skip-permissions'];
+19 -1
View File
@@ -21,6 +21,7 @@ import { getDiscordStartupHint } from './discord-bridge.js';
import type { CliEntry } from './config/cli-registry/types.js';
import { renderLaunch, type EngineValues, type ParamValues } from './config/cli-registry/argv.js';
import { matchesPattern } from './config/cli-registry/patterns.js';
import { applyRootValues, type RootValueChange } from './config/cli-registry/root-launch.js';
import { buildAdvisorSettings, buildEffortCliArgs, sanitizeCliSessionName } from './session-cli-builder.js';
import { compareVersions } from './utils/dependency-checker.js';
import { resolveSessionCliVersion } from './utils/cli-resolver.js';
@@ -77,6 +78,16 @@ export interface SpawnBridgeOptions {
* passed) by TmuxManager._resolveIdleCompactionOptOut, which records it on the mux record.
*/
idleCompactionOff?: boolean;
/**
* True when this command will run as a child of a server process whose uid is 0: a LOCAL
* launch under a root server. Params that declare a `rootValue` then take it (see
* config/cli-registry/root-launch.ts). Decided by the caller, never here: this bridge also
* renders commands that run under another account (the remote omp relaunch), where the
* server's uid means nothing. Absent or false leaves the command byte-identical.
*/
runsAsServerRoot?: boolean;
/** Told which params took their `rootValue`, so the launch site can log it. Never called with none. */
onRootValue?: (changes: RootValueChange[]) => void;
}
/**
@@ -209,7 +220,14 @@ function gateVersion(entry: CliEntry, explicit: string | null | undefined): stri
export function buildSpawnCommandFromRegistry(entry: CliEntry, options: SpawnBridgeOptions): string | undefined {
if (entry.kind === 'shell' || entry.launch.variants.length === 0) return undefined;
const params = buildParamsFromLegacyConfig(entry, legacyConfigFor(entry, options));
// A value the CLI refuses under root gives way to its declared `rootValue` before the engine
// sees it. Not root: `applyRootValues` hands back the very object it was given.
const { params, changes: rootChanges } = applyRootValues(
entry.launch,
buildParamsFromLegacyConfig(entry, legacyConfigFor(entry, options)),
options.runsAsServerRoot === true
);
if (rootChanges.length > 0) options.onRootValue?.(rootChanges);
const engineValues: EngineValues = {
sessionId: options.sessionId,
+52
View File
@@ -81,6 +81,8 @@ import {
} from './session-cli-registry-bridge.js';
import { keepWarmOn } from './prompt-cache-keepwarm.js';
import type { CliEntry } from './config/cli-registry/types.js';
import { describeRootValueChanges, type RootValueChange } from './config/cli-registry/root-launch.js';
import { serverRunsAsRoot } from './utils/server-uid.js';
import {
resolveStatusLineCliCommand,
readPlanUsageTelemetryEnabled,
@@ -1258,6 +1260,44 @@ export function decideIdleCompactionOptOut(o: {
);
}
/** What `serverRootSpawnOptions()` adds to a `buildSpawnCommand` call; empty for every launch that is not root. */
export interface ServerRootSpawnOptions {
runsAsServerRoot?: true;
onRootValue?: (changes: RootValueChange[]) => void;
}
/**
* The `buildSpawnCommand` options for a launch under a Codeman server that itself runs as
* root (uid 0), which is common on a VPS and in an LXC container.
*
* A CLI started locally is the server's child and runs as root too, and Claude Code exits
* on `--dangerously-skip-permissions` there, so its default launch was a dead pane. With
* these options a param that declares a `rootValue` takes it (registry data, see
* config/cli-registry/root-launch.ts), and the swap is logged once per launch.
*
* ⚠️ The ONE place the tmux launch path asks for the uid. `createSession` and `respawnPane`
* both spread the result into `buildSpawnCommand`, and every local tmux launch (new
* session, resume, dead-pane respawn, `restartCli()`, cron, quick-start, reboot restore) is
* one of those two calls. The two launches with no tmux (direct-PTY fallback, one-shot) get
* the same registry data in `buildPermissionArgs()` (session-cli-builder.ts).
* ⚠️ `launchedElsewhere` (remote, Docker, adopted) returns nothing: that CLI runs under
* another account, and the local command built for it is never used. Docker answers the
* same refusal with `overlays.docker.rootCommand`, by the CONTAINER's uid.
* ⚠️ Not root returns `{}`, so the command line stays byte-identical.
*/
export function serverRootSpawnOptions(o: {
mode: SessionMode;
sessionId: string;
launchedElsewhere: boolean;
}): ServerRootSpawnOptions {
if (o.launchedElsewhere || !serverRunsAsRoot()) return {};
const what = `${getCli(o.mode)?.label ?? o.mode} session ${o.sessionId.slice(0, 8)}`;
return {
runsAsServerRoot: true,
onRootValue: (changes) => console.warn(`[TmuxManager] ${describeRootValueChanges(what, changes)}`),
};
}
export function buildSpawnCommand(options: {
mode: SessionMode;
sessionId: string;
@@ -1292,6 +1332,14 @@ export function buildSpawnCommand(options: {
* gate measuring the RIGHT binary, the local one.
*/
claudeCliVersion?: string | null;
/**
* The command will run as a child of a server process whose uid is 0, so a param declaring
* a `rootValue` takes it. Only ever supplied through `serverRootSpawnOptions()`, which the
* two local launch sites spread in; absent, the command is byte-identical.
*/
runsAsServerRoot?: boolean;
/** Told which params took their `rootValue` (see `serverRootSpawnOptions`). */
onRootValue?: (changes: RootValueChange[]) => void;
}): string {
// Every CLI's command shape is registry DATA, rendered by the argv engine — see
// config/cli-registry/argv.ts for why config can never contain shell text. A `shell`-kind
@@ -2731,6 +2779,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
statusLineCommand,
idleCompactionOff,
sessionName: cliName,
// A local launch under a server that runs as root: see serverRootSpawnOptions.
...serverRootSpawnOptions({ mode, sessionId, launchedElsewhere: !!(remote || docker || adopt) }),
});
const config = niceConfig || DEFAULT_NICE_CONFIG;
@@ -3055,6 +3105,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
statusLineCommand,
idleCompactionOff,
sessionName: cliName,
// Same as createSession: a respawn under a root server must not bring the refused value back.
...serverRootSpawnOptions({ mode, sessionId, launchedElsewhere: !!(remote || docker || adopt) }),
});
const config = niceConfig || DEFAULT_NICE_CONFIG;
const cmd = wrapWithNice(baseCmd, config);
+36
View File
@@ -0,0 +1,36 @@
/**
* @fileoverview Whether the Codeman server process itself runs as root (uid 0).
*
* A CLI the server starts LOCALLY is its child, so it runs under the same uid, and some
* CLIs refuse part of their own command line there: Claude Code exits on
* `--dangerously-skip-permissions` under root ("cannot be used with root/sudo privileges").
* A server installed and started as root is common on a VPS and in an LXC container, and
* there every such session showed a dead pane.
*
* The answer is read at CALL time, never cached in a module-level const: every local launch
* asks again, and a test stands in for the uid through `stubServerUidForTest()`.
*
* Test hermeticity: under vitest the real uid is never consulted (`false` unless a test
* stubbed one), so the suite gives the same command lines when it is run as root, in a
* container for instance.
*
* @module utils/server-uid
*/
/** A test's stand-in for the process uid: `null` = no stub, `undefined` = a platform with no uid. */
let stubbedUid: number | undefined | null = null;
/**
* True when this process runs as uid 0. False on a platform with no uid (`process.getuid`
* is absent on Windows).
*/
export function serverRunsAsRoot(): boolean {
if (stubbedUid !== null) return stubbedUid === 0;
if (process.env.VITEST) return false;
return typeof process.getuid === 'function' && process.getuid() === 0;
}
/** Test seam: answer as if the server ran under `uid`; `null` puts the hermetic default back. */
export function stubServerUidForTest(uid: number | undefined | null): void {
stubbedUid = uid;
}
+35
View File
@@ -460,6 +460,41 @@ describe('cross-field integrity', () => {
expect(CliEntrySchema.safeParse(wrong).success).toBe(false);
});
it('holds a rootValue to the values its param declares', () => {
// `rootValue` swaps one declared value for another when the server runs as root (claude's
// bypass mode, which Claude Code refuses under uid 0). A key or a replacement outside
// `values` is a swap that can never apply, or one that launches with a value no arg tests.
const withRootValue = (rootValue: Record<string, string>): Record<string, unknown> => {
const entry = baseEntry('claude');
const params = (entry.launch as { params: Record<string, Record<string, unknown>> }).params;
params.claudeMode.rootValue = rootValue;
return entry;
};
expect(CliEntrySchema.safeParse(withRootValue({ 'dangerously-skip-permissions': 'normal' })).success).toBe(true);
expect(CliEntrySchema.safeParse(withRootValue({})).success).toBe(true);
expect(CliEntrySchema.safeParse(withRootValue({ 'no-such-mode': 'normal' })).success, 'unknown key').toBe(false);
expect(
CliEntrySchema.safeParse(withRootValue({ 'dangerously-skip-permissions': 'no-such-mode' })).success,
'unknown replacement'
).toBe(false);
expect(
CliEntrySchema.safeParse(withRootValue({ 'dangerously-skip-permissions': 'dangerously-skip-permissions' }))
.success,
'a value replaced by itself'
).toBe(false);
expect(
CliEntrySchema.safeParse(withRootValue({ 'dangerously-skip-permissions': 'auto', auto: 'normal' })).success,
'a replacement that is replaced again'
).toBe(false);
});
it('takes a rootValue on an enum param only', () => {
expectRejected((e) => {
const params = (e.launch as { params: Record<string, Record<string, unknown>> }).params;
params.rootToggle = { type: 'bool', rootValue: { true: 'false' } };
}, 'the strict bool spec has no rootValue key');
});
it('rejects a profile name this build does not implement', () => {
expectRejected((e) => {
(e.discovery as Record<string, unknown>).launcherProfile = 'no-such-profile';
+156
View File
@@ -197,6 +197,162 @@ describe('install.sh runtime safety', () => {
});
});
describe('install.sh and a /dev/tty that exists but cannot be opened', () => {
// The /dev/tty node is there on every Linux and macOS, also for a process with no controlling
// terminal (`su - user -c`, cron, a CI runner, cloud-init). `[[ -e /dev/tty ]]` says yes
// there, and the `< /dev/tty` behind it fails before the command runs. Measured 2026-11-27 in
// a fresh ubuntu:24.04 container: a headless run with a working passwordless sudo ended on
// "Failed to obtain sudo privileges", because `sudo -v < /dev/tty` never started sudo.
// The fix is one probe, `tty_openable`, which OPENS the node.
/** A file test on the node (`[[ -e /dev/tty ]]`, `test -c /dev/tty`): true with no terminal behind it. */
const NODE_TEST = /(?:\[\[?|\btest)\s+!?\s*-[a-zA-Z]\s+"?\/dev\/tty"?/;
/**
* Every command that takes its stdin from /dev/tty, and the ones that do not sit directly
* under `if tty_openable; then`. The probe itself and the two readers are the exceptions:
* read_reply and read_secret run only after has_tty said yes, and with stdin not a terminal
* that IS tty_openable.
*/
function ttyRedirects(source: string): { sites: string[]; unguarded: string[] } {
const exempt = (line: string): boolean =>
/^\s*\{ : < \/dev\/tty; \} 2>\/dev\/null$/.test(line) || /^\s*read -rs? "\$1" < \/dev\/tty$/.test(line);
const lines = source.split('\n');
const indentOf = (line: string): number => line.length - line.trimStart().length;
const sites: string[] = [];
const unguarded: string[] = [];
lines.forEach((line, i) => {
if (/^\s*#/.test(line) || !/<\s*\/dev\/tty\b/.test(line) || exempt(line)) return;
sites.push(line.trim());
// The enclosing statement: the nearest line above with less indentation.
let j = i - 1;
while (j >= 0 && (lines[j].trim() === '' || indentOf(lines[j]) >= indentOf(line))) j--;
if (j < 0 || lines[j].trim() !== 'if tty_openable; then') unguarded.push(`${i + 1}: ${line.trim()}`);
});
return { sites, unguarded };
}
it('never tests the /dev/tty node, only whether it opens', () => {
const offenders = CODE_LINES.filter((line) => NODE_TEST.test(line));
expect(
offenders,
`a file test on /dev/tty says nothing about a controlling terminal; use tty_openable:\n ${offenders.join('\n ')}`
).toEqual([]);
expect(SOURCE).toMatch(/^tty_openable\(\) \{\n {4}\{ : < \/dev\/tty; \} 2>\/dev\/null\n\}$/m);
});
it('takes stdin from /dev/tty only directly under `if tty_openable; then`', () => {
const { sites, unguarded } = ttyRedirects(SOURCE);
expect(unguarded, `redirect from /dev/tty without the open probe:\n ${unguarded.join('\n ')}`).toEqual([]);
// Anti-vacuity: both sudo sites are among what was checked.
expect(sites.filter((line) => /\bsudo -v\b/.test(line)).length).toBe(2);
expect(sites.length).toBeGreaterThanOrEqual(5);
});
it('fails for a sudo site that redirects from /dev/tty behind a bare -e test (anti-vacuity)', () => {
// The shape ensure_sudo had when the headless install died.
const old = [
'ensure_sudo() {',
' if [[ -e /dev/tty ]]; then',
' if ! sudo -v 2>/dev/null < /dev/tty; then',
' die "Failed to obtain sudo privileges."',
' fi',
' fi',
'}',
];
expect(old.filter((line) => NODE_TEST.test(line))).toEqual([' if [[ -e /dev/tty ]]; then']);
expect(ttyRedirects(old.join('\n')).unguarded).toEqual(['3: if ! sudo -v 2>/dev/null < /dev/tty; then']);
// And the same site behind the probe passes.
old[1] = ' if tty_openable; then';
expect(ttyRedirects(old.join('\n'))).toEqual({
sites: ['if ! sudo -v 2>/dev/null < /dev/tty; then'],
unguarded: [],
});
});
/**
* Drive the sudo helpers in a real bash that has NO controlling terminal: `detached` puts
* the child in a session of its own, which is what `su -c`, cron and a CI runner do. `sudo`
* is a shell function that records its arguments and answers from the environment, so no
* real sudo runs. Each stub reads stdin's state the way the real one would.
*/
function driveSudo(body: string, sudo: { n: number; v: number }) {
const driver = `
set -euo pipefail
export CODEMAN_INSTALL_SH_LIB=1
. "$1"
[[ -e /dev/tty ]] && echo "node=present"
if { : < /dev/tty; } 2>/dev/null; then echo "tty=open"; else echo "tty=closed"; fi
sudo() {
echo "sudo $*"
case "$1" in
-n) return "$SUDO_N_RC" ;;
-v) return "$SUDO_V_RC" ;;
esac
return 0
}
NO_ADMIN=0
${body}
`;
const env = { ...process.env, SUDO_N_RC: String(sudo.n), SUDO_V_RC: String(sudo.v) };
return spawnSync('bash', ['-c', driver, 'bash', INSTALL_SH], {
encoding: 'utf-8',
timeout: 30_000,
env,
detached: true,
});
}
// As root the helpers return before they reach sudo, so there is nothing to drive.
const asUser = it.skipIf(process.getuid?.() === 0);
asUser('reproduces the condition: the node is there and does not open', () => {
const result = driveSudo('true', { n: 0, v: 0 });
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain('node=present');
expect(result.stdout).toContain('tty=closed');
});
asUser('ensure_sudo passes on a passwordless sudo with no terminal, without validating', () => {
const result = driveSudo('ensure_sudo; echo "ensure=ok"', { n: 0, v: 1 });
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain('ensure=ok');
expect(result.stdout).toContain('sudo -n true');
// `sudo -v` wants a password wherever one sudoers entry of the account asks for one,
// even when `sudo <command>` does not, so a sudo that already runs is not validated.
expect(result.stdout).not.toContain('sudo -v');
});
asUser('ensure_sudo falls back to a plain `sudo -v` when the terminal cannot be opened', () => {
const result = driveSudo('ensure_sudo; echo "ensure=ok"', { n: 1, v: 0 });
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain('sudo -v');
expect(result.stdout).toContain('ensure=ok');
});
asUser('ensure_sudo names the missing terminal when sudo would have to ask', () => {
const result = driveSudo('ensure_sudo; echo "ensure=ok"', { n: 1, v: 1 });
expect(result.status).toBe(1);
expect(result.stdout).not.toContain('ensure=ok');
expect(result.stderr).toContain('Failed to obtain sudo privileges. Try running the script directly');
});
asUser('sudo_session_try reaches sudo instead of failing on the redirect', () => {
// -n fails, so the keepalive loop it starts ends at once and the driver does not wait for it.
const result = driveSudo('sudo_session_try >/dev/null; echo "try=$?"', { n: 1, v: 0 });
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain('try=0');
expect(result.stderr).not.toContain('/dev/tty');
});
asUser('sudo_session_start says to run it directly when there is no terminal to ask on', () => {
const result = driveSudo('sudo_session_start >/dev/null', { n: 1, v: 1 });
expect(result.status).toBe(1);
expect(result.stderr).toContain('Failed to obtain sudo privileges. Try running the script directly');
expect(result.stderr).not.toContain('/dev/tty');
});
});
describe('install.sh DeepSeek identity probe', () => {
it('greps for the same banner the registry identity regex demands', () => {
// dsh_banner_probe is the ONE hand-written identity check left in the script (the
+430
View File
@@ -0,0 +1,430 @@
/**
* @fileoverview A Codeman server that runs as root (uid 0) starts local Claude sessions
* without the permission bypass.
*
* Claude Code exits on `--dangerously-skip-permissions` under uid 0 ("cannot be used with
* root/sudo privileges for security reasons"). That flag is the default permission mode, so
* a server installed and started as root (a VPS, an LXC container) showed a dead pane for
* every local Claude session. Measured 2026-11-27 with the public installer in a fresh
* `ubuntu:24.04` container.
*
* What is pinned here:
* - the pure rule (`applyRootValues`) and the registry data it reads (`rootValue`);
* - the uid helper is hermetic under vitest and only a stub makes it say "root";
* - under uid 0 the LOCAL command lines (tmux fresh + resume, direct PTY, one-shot) carry
* no bypass flag, and say so in one log line;
* - under any other uid every command line is byte-identical to the golden pins;
* - `auto`, `allowedTools` and `normal` are untouched under root;
* - remote and Docker pane commands never read the server's uid.
*
* Port: none (pure functions over registry data).
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { applyRootValues, describeRootValueChanges } from '../src/config/cli-registry/root-launch.js';
import { getCli } from '../src/config/cli-registry/registry.js';
import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
import { DEFAULT_AGENT_IMAGE, defaultDockerCommandForMode, toSessionDocker } from '../src/docker-hosts.js';
import { buildInteractiveArgs, buildPromptArgs, directLaunchClaudeMode } from '../src/session-cli-builder.js';
import { buildSpawnCommandFromRegistry } from '../src/session-cli-registry-bridge.js';
import {
buildDockerLaunchCommand,
buildRemoteLaunchCommand,
buildSpawnCommand,
serverRootSpawnOptions,
type DockerLaunchOptions,
} from '../src/tmux-manager.js';
import type { ClaudeMode, DockerCase, DockerHost, SessionMode, SessionRemote } from '../src/types.js';
import { serverRunsAsRoot, stubServerUidForTest } from '../src/utils/server-uid.js';
const SID = '0f9c2b14-1111-2222-3333-444455556666';
const BYPASS = '--dangerously-skip-permissions';
/** The golden pins of test/cli-registry-spawn-golden.test.ts, restated: the command lines of a launch that is not root. */
const GOLDEN_FRESH = `claude ${BYPASS} --session-id "${SID}"`;
const GOLDEN_RESUME = `claude ${BYPASS} --resume "abc-123-def" || claude ${BYPASS} --session-id "${SID}"`;
function claudeLaunch() {
const entry = getCli('claude');
if (!entry) throw new Error('no claude entry');
return entry.launch;
}
/** The local tmux pane command, built the way `createSession` and `respawnPane` build it. */
function localCommand(extra: Partial<Parameters<typeof buildSpawnCommand>[0]> = {}, launchedElsewhere = false): string {
const mode = (extra.mode ?? 'claude') as SessionMode;
return buildSpawnCommand({
mode,
sessionId: SID,
claudeCliVersion: null,
...extra,
...serverRootSpawnOptions({ mode, sessionId: SID, launchedElsewhere }),
});
}
afterEach(() => {
stubServerUidForTest(null);
vi.restoreAllMocks();
});
describe('serverRunsAsRoot', () => {
it('never reads the real uid under vitest, so the suite is the same when run as root', () => {
const getuid = vi.spyOn(process, 'getuid').mockReturnValue(0);
expect(serverRunsAsRoot()).toBe(false);
expect(getuid).not.toHaveBeenCalled();
});
it('answers from the stubbed uid, asked again on every call', () => {
stubServerUidForTest(0);
expect(serverRunsAsRoot()).toBe(true);
stubServerUidForTest(1000);
expect(serverRunsAsRoot()).toBe(false);
// A platform with no uid at all (process.getuid is absent on Windows).
stubServerUidForTest(undefined);
expect(serverRunsAsRoot()).toBe(false);
stubServerUidForTest(null);
expect(serverRunsAsRoot()).toBe(false);
});
});
describe('the registry data', () => {
it('declares the swap on the claude permission mode, and on nothing else', () => {
const declared = STOCK_CLIS.flatMap((entry) =>
Object.entries(entry.launch.params).flatMap(([param, spec]) =>
spec.type === 'enum' && spec.rootValue ? [{ cli: entry.id as string, param, rootValue: spec.rootValue }] : []
)
);
// A new line here is a decision about what another CLI does under root, to be measured first.
expect(declared).toEqual([
{ cli: 'claude', param: 'claudeMode', rootValue: { 'dangerously-skip-permissions': 'normal' } },
]);
});
});
describe('applyRootValues', () => {
it('hands back the very object it was given when the launch is not root', () => {
const params = { claudeMode: 'dangerously-skip-permissions' };
const result = applyRootValues(claudeLaunch(), params, false);
expect(result.params).toBe(params);
expect(result.changes).toEqual([]);
});
it('swaps the bypass mode for normal under root, whether it was sent or is the default', () => {
for (const params of [{}, { claudeMode: 'dangerously-skip-permissions' }, { claudeMode: 'no-such-mode' }]) {
const before = { ...params };
const result = applyRootValues(claudeLaunch(), params, true);
expect(result.params.claudeMode).toBe('normal');
expect(result.changes).toEqual([{ param: 'claudeMode', from: 'dangerously-skip-permissions', to: 'normal' }]);
expect(params, 'the caller object is never mutated').toEqual(before);
}
});
it('leaves every other mode alone under root', () => {
for (const claudeMode of ['auto', 'allowedTools', 'normal']) {
const params = { claudeMode, allowedTools: 'Read' };
const result = applyRootValues(claudeLaunch(), params, true);
expect(result.params, claudeMode).toBe(params);
expect(result.changes, claudeMode).toEqual([]);
}
});
it('keeps the other params of a launch it changes', () => {
const result = applyRootValues(claudeLaunch(), { model: 'opus', resumeId: 'abc-123-def' }, true);
expect(result.params).toEqual({ model: 'opus', resumeId: 'abc-123-def', claudeMode: 'normal' });
});
it('does nothing for a launch spec that declares no rootValue', () => {
const codex = getCli('codex');
if (!codex) throw new Error('no codex entry');
const params = { dangerouslyBypassApprovals: true };
expect(applyRootValues(codex.launch, params, true).params).toBe(params);
});
it('ignores a replacement the param does not declare (a hand-built spec the schema never saw)', () => {
const launch = {
params: { m: { type: 'enum' as const, values: ['a', 'b'], default: 'a', rootValue: { a: 'zzz' } } },
variants: [{ id: 'new', args: [] }],
};
const params = {};
const result = applyRootValues(launch, params, true);
expect(result.params).toBe(params);
expect(result.changes).toEqual([]);
});
it('describes the swap in one line that names the cause and the way out', () => {
const line = describeRootValueChanges('Claude Code session 0f9c2b14', [
{ param: 'claudeMode', from: 'dangerously-skip-permissions', to: 'normal' },
]);
expect(line).toContain('Claude Code session 0f9c2b14');
expect(line).toContain('claudeMode "dangerously-skip-permissions" as "normal"');
expect(line).toContain('runs as root (uid 0)');
expect(line).toContain('normal user');
expect(line).not.toContain('\n');
});
});
describe('the local tmux pane command under a server that runs as root', () => {
it('starts a fresh session without the bypass flag', () => {
stubServerUidForTest(0);
vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(localCommand()).toBe(`claude --session-id "${SID}"`);
expect(localCommand({ claudeMode: 'dangerously-skip-permissions' })).toBe(`claude --session-id "${SID}"`);
});
it('drops the flag from BOTH halves of the resume fallback', () => {
stubServerUidForTest(0);
vi.spyOn(console, 'warn').mockImplementation(() => {});
const command = localCommand({ resumeSessionId: 'abc-123-def' });
expect(command).toBe(`claude --resume "abc-123-def" || claude --session-id "${SID}"`);
expect(command).not.toContain(BYPASS);
});
it('is exactly the command an explicit normal mode gives, with every other flag kept', () => {
stubServerUidForTest(0);
vi.spyOn(console, 'warn').mockImplementation(() => {});
const rest = {
model: 'opus[1m]',
effort: 'max' as const,
advisorModel: 'opus',
sessionName: 'w3-myapp',
claudeCliVersion: '2.1.300',
resumeSessionId: 'abc-123-def',
statusLineCommand: '/tmp/exporter.sh',
};
const underRoot = localCommand(rest);
stubServerUidForTest(1000);
expect(underRoot).toBe(localCommand({ ...rest, claudeMode: 'normal' }));
expect(underRoot).toContain('--model "opus[1m]"');
expect(underRoot).toContain("--effort 'max'");
expect(underRoot).toContain('--name "w3-myapp"');
});
it('says so in one log line per launch', () => {
stubServerUidForTest(0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
localCommand();
expect(warn).toHaveBeenCalledTimes(1);
const line = String(warn.mock.calls[0][0]);
expect(line).toMatch(/^\[TmuxManager\] Claude Code session 0f9c2b14 /);
expect(line).toContain('claudeMode "dangerously-skip-permissions" as "normal"');
expect(line).toContain('runs as root (uid 0)');
localCommand({ resumeSessionId: 'abc-123-def' });
expect(warn).toHaveBeenCalledTimes(2);
});
it('leaves auto, allowedTools and normal exactly as they are, and logs nothing', () => {
const cases: Array<{ claudeMode: ClaudeMode; allowedTools?: string }> = [
{ claudeMode: 'auto' },
{ claudeMode: 'allowedTools', allowedTools: 'Bash(git:*), Read' },
{ claudeMode: 'allowedTools' },
{ claudeMode: 'normal' },
];
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
for (const options of cases) {
stubServerUidForTest(1000);
const asUser = localCommand(options);
const resumedAsUser = localCommand({ ...options, resumeSessionId: 'abc-123-def' });
stubServerUidForTest(0);
expect(localCommand(options), options.claudeMode).toBe(asUser);
expect(localCommand({ ...options, resumeSessionId: 'abc-123-def' }), options.claudeMode).toBe(resumedAsUser);
}
expect(warn).not.toHaveBeenCalled();
stubServerUidForTest(0);
expect(localCommand({ claudeMode: 'auto' })).toBe(`claude --permission-mode auto --session-id "${SID}"`);
expect(localCommand({ claudeMode: 'allowedTools', allowedTools: 'Bash(git:*), Read' })).toBe(
`claude --allowedTools "Bash(git:*), Read" --session-id "${SID}"`
);
});
it('renders every CLI that declares no rootValue the same as for a normal user', () => {
const untouched = STOCK_CLIS.filter(
(entry) => !Object.values(entry.launch.params).some((spec) => spec.type === 'enum' && spec.rootValue)
).map((entry) => entry.id as SessionMode);
expect(untouched.length).toBeGreaterThanOrEqual(10);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
for (const mode of untouched) {
// Each CLI's own bypass switch is on, so a swap that leaked to another entry would show.
const options = {
mode,
codexConfig: { dangerouslyBypassApprovals: true },
antigravityConfig: { dangerouslySkipPermissions: true },
geminiConfig: { approvalMode: 'yolo' as const },
grokConfig: { alwaysApprove: true },
copilotConfig: { allowAll: true },
};
stubServerUidForTest(1000);
const asUser = localCommand(options);
stubServerUidForTest(0);
expect(localCommand(options), mode).toBe(asUser);
}
expect(warn).not.toHaveBeenCalled();
});
});
describe('the local tmux pane command under any other uid', () => {
it('adds nothing to the launch options, so the command is byte-identical', () => {
for (const uid of [1000, 501, 1, undefined]) {
stubServerUidForTest(uid);
expect(serverRootSpawnOptions({ mode: 'claude', sessionId: SID, launchedElsewhere: false })).toEqual({});
expect(localCommand()).toBe(GOLDEN_FRESH);
expect(localCommand({ resumeSessionId: 'abc-123-def' })).toBe(GOLDEN_RESUME);
}
});
it('is unchanged without a stub too (the hermetic default)', () => {
expect(localCommand()).toBe(GOLDEN_FRESH);
expect(localCommand({ resumeSessionId: 'abc-123-def' })).toBe(GOLDEN_RESUME);
});
it('never swaps on the bridge unless the caller said the launch runs as root', () => {
// The bridge also renders commands that run under another account (the remote omp
// relaunch), so it must not ask for the uid itself.
stubServerUidForTest(0);
const entry = getCli('claude');
if (!entry) throw new Error('no claude entry');
const onRootValue = vi.fn();
expect(
buildSpawnCommandFromRegistry(entry, { mode: 'claude', sessionId: SID, claudeCliVersion: null, onRootValue })
).toBe(GOLDEN_FRESH);
expect(onRootValue).not.toHaveBeenCalled();
expect(
buildSpawnCommandFromRegistry(entry, {
mode: 'claude',
sessionId: SID,
claudeCliVersion: null,
runsAsServerRoot: true,
onRootValue,
})
).toBe(`claude --session-id "${SID}"`);
expect(onRootValue).toHaveBeenCalledTimes(1);
});
});
describe('remote and Docker launches', () => {
const remote: SessionRemote = {
hostId: 'gpu-box',
label: 'GPU Box',
host: '10.0.0.42',
username: 'ubuntu',
remotePath: '/home/ubuntu/work',
};
const HOST: DockerHost = { id: 'local', label: 'Local', image: DEFAULT_AGENT_IMAGE };
const CASE: DockerCase = {
name: 'myproj',
type: 'docker',
hostId: 'local',
hostWorkspacePath: '/home/user/cases/myproj',
};
function dockerOpts(runsAsRoot?: boolean): DockerLaunchOptions {
const docker = { ...toSessionDocker(HOST, CASE), ...(runsAsRoot === undefined ? {} : { runsAsRoot }) };
return {
mode: 'claude',
docker,
sessionId: '1a2b3c4d5e6f',
createContext: {
docker,
sessionId: '1a2b3c4d5e6f',
instance: '',
userArgs: ['--user', '1000:0'],
credentialMounts: [],
extraMounts: [],
envCreate: { HOME: '/home/agent' },
addHostGateway: true,
gatewayAlias: 'host.docker.internal',
},
execEnv: { TERM: 'xterm-256color', CODEMAN_SESSION_ID: '1a2b3c4d', CODEMAN_MUX: '1' },
execEnvNames: [],
};
}
it('add nothing to the launch options, whatever the server uid', () => {
stubServerUidForTest(0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(serverRootSpawnOptions({ mode: 'claude', sessionId: SID, launchedElsewhere: true })).toEqual({});
// The local command built beside a remote or Docker launch is discarded; it must not log a swap that never ran.
expect(localCommand({}, true)).toBe(GOLDEN_FRESH);
expect(warn).not.toHaveBeenCalled();
});
it('keep the remote claude pane command, bypass flag included, under a root server', () => {
const build = (claudeMode?: ClaudeMode) =>
buildRemoteLaunchCommand({ mode: 'claude', remote, sessionId: SID, claudeMode });
stubServerUidForTest(1000);
const asUser = { fresh: build(), auto: build('auto'), normal: build('normal') };
stubServerUidForTest(0);
expect(build()).toBe(asUser.fresh);
expect(build('auto')).toBe(asUser.auto);
expect(build('normal')).toBe(asUser.normal);
expect(asUser.fresh).toContain(`claude ${BYPASS} --session-id ${SID}`);
expect(asUser.normal).not.toContain(BYPASS);
});
it('keep the Docker pane command: the CONTAINER uid decides there, not the server uid', () => {
stubServerUidForTest(1000);
const asUser = { user: buildDockerLaunchCommand(dockerOpts()), root: buildDockerLaunchCommand(dockerOpts(true)) };
stubServerUidForTest(0);
expect(buildDockerLaunchCommand(dockerOpts())).toBe(asUser.user);
expect(buildDockerLaunchCommand(dockerOpts(true))).toBe(asUser.root);
expect(asUser.user).toContain(BYPASS);
expect(asUser.root).not.toContain(BYPASS);
expect(defaultDockerCommandForMode('claude')).toBe(`exec claude ${BYPASS}`);
expect(defaultDockerCommandForMode('claude', true)).toBe('exec claude');
});
});
describe('claude processes the server starts directly (direct PTY fallback, one-shot)', () => {
it('carry no bypass flag under root, and log it', () => {
stubServerUidForTest(0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(buildInteractiveArgs(SID, 'dangerously-skip-permissions')).toEqual(['--session-id', SID]);
expect(buildPromptArgs('hello')).toEqual(['-p', '--verbose', '--output-format', 'stream-json', 'hello']);
expect(warn).toHaveBeenCalledTimes(2);
expect(String(warn.mock.calls[0][0])).toMatch(/^\[Session\] .*runs as root \(uid 0\)/);
});
it('are unchanged under any other uid', () => {
for (const uid of [1000, undefined, null]) {
stubServerUidForTest(uid);
expect(buildInteractiveArgs(SID, 'dangerously-skip-permissions')).toEqual([BYPASS, '--session-id', SID]);
expect(buildPromptArgs('hello')).toEqual(['-p', '--verbose', BYPASS, '--output-format', 'stream-json', 'hello']);
}
});
it('keep auto, allowedTools and normal under root', () => {
stubServerUidForTest(0);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(buildInteractiveArgs(SID, 'auto')).toEqual(['--permission-mode', 'auto', '--session-id', SID]);
expect(buildInteractiveArgs(SID, 'allowedTools', undefined, 'Read')).toEqual([
'--allowedTools',
'Read',
'--session-id',
SID,
]);
expect(buildInteractiveArgs(SID, 'normal')).toEqual(['--session-id', SID]);
expect(buildPromptArgs('hello', undefined, 'auto')).toEqual([
'-p',
'--verbose',
'--permission-mode',
'auto',
'--output-format',
'stream-json',
'hello',
]);
expect(warn).not.toHaveBeenCalled();
});
it('directLaunchClaudeMode is pure: the caller says whether the server is root', () => {
const onChange = vi.fn();
expect(directLaunchClaudeMode('dangerously-skip-permissions', false, onChange)).toBe(
'dangerously-skip-permissions'
);
expect(onChange).not.toHaveBeenCalled();
expect(directLaunchClaudeMode('dangerously-skip-permissions', true, onChange)).toBe('normal');
expect(onChange).toHaveBeenCalledTimes(1);
for (const mode of ['auto', 'allowedTools', 'normal'] as const) {
expect(directLaunchClaudeMode(mode, true, onChange)).toBe(mode);
}
expect(onChange).toHaveBeenCalledTimes(1);
});
});