mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
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>
This commit is contained in:
1 parent
6db166f3f8
commit
d9fce03444
15 files changed
+785
-10
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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.`
|
||||
);
|
||||
}
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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' },
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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'];
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user