@chroxy/server 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Docker image allowlist for create_environment.
|
|
3
|
+
*
|
|
4
|
+
* Adversary A7 (2026-04-11 audit): the create_environment WS handler
|
|
5
|
+
* accepted any string as a Docker image name and passed it straight
|
|
6
|
+
* through to the environment manager. An authenticated attacker could
|
|
7
|
+
* register an attacker-controlled image (containing an exploit payload
|
|
8
|
+
* or pre-installed persistence) and run it inside the operator's
|
|
9
|
+
* Docker daemon.
|
|
10
|
+
*
|
|
11
|
+
* Defense: two-layer allowlist.
|
|
12
|
+
*
|
|
13
|
+
* 1. Default allowlist — a small set of common base images and
|
|
14
|
+
* devcontainer sources that are reasonable for dev environments and
|
|
15
|
+
* come from well-known publishers. Each entry supports an optional
|
|
16
|
+
* trailing `*` wildcard for tag/path flexibility (`node:*` matches
|
|
17
|
+
* `node:22`, `node:18-slim`, etc.; `mcr.microsoft.com/devcontainers/*`
|
|
18
|
+
* matches any subtree).
|
|
19
|
+
*
|
|
20
|
+
* 2. Operator override — `config.allowedDockerImages` (array of the
|
|
21
|
+
* same pattern shape) replaces the default. An empty array in the
|
|
22
|
+
* config means "no client-supplied images at all" (force the
|
|
23
|
+
* manager's built-in default); explicit entries are strictly
|
|
24
|
+
* enforced.
|
|
25
|
+
*
|
|
26
|
+
* The allowlist is a soft defense — an attacker who can run arbitrary
|
|
27
|
+
* Bash on the machine can already call `docker pull` directly. This
|
|
28
|
+
* check prevents the WS handler itself from being used as a
|
|
29
|
+
* privileged pull primitive.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
export const DEFAULT_ALLOWED_DOCKER_IMAGES = [
|
|
33
|
+
// Node.js base images
|
|
34
|
+
'node:*',
|
|
35
|
+
// Python base images
|
|
36
|
+
'python:*',
|
|
37
|
+
// Common Linux bases
|
|
38
|
+
'ubuntu:*',
|
|
39
|
+
'debian:*',
|
|
40
|
+
'alpine:*',
|
|
41
|
+
// Devcontainer registries — Microsoft and GitHub published
|
|
42
|
+
'mcr.microsoft.com/devcontainers/*',
|
|
43
|
+
'ghcr.io/devcontainers/*',
|
|
44
|
+
// Rust toolchain
|
|
45
|
+
'rust:*',
|
|
46
|
+
// Go toolchain
|
|
47
|
+
'golang:*',
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Check whether a given image string matches any pattern in the
|
|
52
|
+
* allowlist. Patterns support a single trailing `*` for wildcarding.
|
|
53
|
+
*
|
|
54
|
+
* @param {string} image - The image reference to check (e.g. `node:22`)
|
|
55
|
+
* @param {string[]} patterns - Allowlist patterns (exact or prefix-with-*)
|
|
56
|
+
* @returns {boolean}
|
|
57
|
+
*/
|
|
58
|
+
export function imageMatchesAllowlist(image, patterns) {
|
|
59
|
+
if (typeof image !== 'string' || image.length === 0) return false
|
|
60
|
+
if (!Array.isArray(patterns) || patterns.length === 0) return false
|
|
61
|
+
for (const pattern of patterns) {
|
|
62
|
+
if (typeof pattern !== 'string' || pattern.length === 0) continue
|
|
63
|
+
if (pattern === image) return true
|
|
64
|
+
if (pattern.endsWith('*')) {
|
|
65
|
+
const prefix = pattern.slice(0, -1)
|
|
66
|
+
if (image.startsWith(prefix)) return true
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return false
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Validate that a client-supplied Docker image is allowed by the
|
|
74
|
+
* current config. Returns null if allowed, or an error string describing
|
|
75
|
+
* the denial.
|
|
76
|
+
*
|
|
77
|
+
* @param {string|undefined} image - The image from the WS message. If
|
|
78
|
+
* undefined, returns null (the environment manager's default will be
|
|
79
|
+
* used — no user-supplied image to validate).
|
|
80
|
+
* @param {object} [config] - Runtime config. `config.allowedDockerImages`
|
|
81
|
+
* overrides the default allowlist if set.
|
|
82
|
+
* @returns {string|null}
|
|
83
|
+
*/
|
|
84
|
+
export function validateDockerImage(image, config = null) {
|
|
85
|
+
// No image specified — caller gets the environment manager's
|
|
86
|
+
// built-in default, which is always safe.
|
|
87
|
+
if (!image) return null
|
|
88
|
+
const configured = Array.isArray(config?.allowedDockerImages)
|
|
89
|
+
? config.allowedDockerImages
|
|
90
|
+
: null
|
|
91
|
+
const patterns = configured || DEFAULT_ALLOWED_DOCKER_IMAGES
|
|
92
|
+
if (imageMatchesAllowlist(image, patterns)) return null
|
|
93
|
+
// Don't leak the full allowlist to the client — it helps attackers
|
|
94
|
+
// enumerate accepted prefixes. Log details server-side only.
|
|
95
|
+
if (patterns.length === 0) {
|
|
96
|
+
return "Docker image rejected: the allowedDockerImages list is empty (no client-supplied images permitted). To allow images, edit 'allowedDockerImages' in your chroxy config file."
|
|
97
|
+
}
|
|
98
|
+
return `Docker image '${image}' is not in the allowlist. To add this image, edit 'allowedDockerImages' in your chroxy config file.`
|
|
99
|
+
}
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import { execFile } from 'child_process'
|
|
2
|
+
import { SdkSession } from './sdk-session.js'
|
|
3
|
+
import { createLogger } from './logger.js'
|
|
4
|
+
import { classifyDockerError } from './docker-session.js'
|
|
5
|
+
import { DockerBackend, FORWARDED_ENV_KEYS, DEFAULT_CONTAINER_CLI_PATH } from './environments/backends/docker.js'
|
|
6
|
+
import { BILLING_CLASSES } from './billing-class.js'
|
|
7
|
+
import { VALID_USERNAME_RE } from './utils/validation-patterns.js'
|
|
8
|
+
|
|
9
|
+
const log = createLogger('docker-sdk')
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* DockerSdkSession runs Claude Code inside an isolated Docker container
|
|
13
|
+
* using the Agent SDK's spawnClaudeCodeProcess callback.
|
|
14
|
+
*
|
|
15
|
+
* Unlike DockerSession (which extends CliSession and uses `docker exec` to
|
|
16
|
+
* run `claude -p` as a subprocess), this class extends SdkSession and injects
|
|
17
|
+
* a custom `spawnClaudeCodeProcess` into the SDK's query() options. The SDK
|
|
18
|
+
* manages the conversation loop in-process; only the actual CLI process is
|
|
19
|
+
* containerized.
|
|
20
|
+
*
|
|
21
|
+
* Container lifecycle:
|
|
22
|
+
* start() -> _startContainer() -> `docker run -d --init --rm ... sleep infinity`
|
|
23
|
+
* -> create non-root user
|
|
24
|
+
* -> install Claude Code CLI
|
|
25
|
+
* query() -> spawnClaudeCodeProcess -> `docker exec -i <id> node <cli.js> ...`
|
|
26
|
+
* destroy() -> `docker rm -f <id>`
|
|
27
|
+
*
|
|
28
|
+
* Key findings from spike (#2472):
|
|
29
|
+
* 1. The SDK passes host's absolute path to cli.js as args[0] -- must remap
|
|
30
|
+
* 2. Claude Code refuses --dangerously-skip-permissions as root -- need non-root user
|
|
31
|
+
* 3. Node's ChildProcess from spawn() satisfies SpawnedProcess interface natively
|
|
32
|
+
*/
|
|
33
|
+
export class DockerSdkSession extends SdkSession {
|
|
34
|
+
static get capabilities() {
|
|
35
|
+
return { ...SdkSession.capabilities, containerized: true }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Preflight credentials block — overrides SdkSession's host-side spec (#4780).
|
|
40
|
+
*
|
|
41
|
+
* Mirror of DockerSession.preflight — see that class for the full rationale.
|
|
42
|
+
* The container has no ~/.claude state and the host Keychain is invisible,
|
|
43
|
+
* so `claude login` is futile inside the container. Only `ANTHROPIC_API_KEY`
|
|
44
|
+
* gets forwarded (see `_startContainer` and `DockerBackend.FORWARDED_ENV_KEYS`),
|
|
45
|
+
* so it is the only env var we advertise here — listing CLAUDE_CODE_OAUTH_TOKEN
|
|
46
|
+
* would falsely report ready when the container would still be unauthed.
|
|
47
|
+
*/
|
|
48
|
+
static get preflight() {
|
|
49
|
+
const parent = SdkSession.preflight
|
|
50
|
+
return {
|
|
51
|
+
...parent,
|
|
52
|
+
credentials: {
|
|
53
|
+
envVars: ['ANTHROPIC_API_KEY'],
|
|
54
|
+
hint: 'set ANTHROPIC_API_KEY on the host so it is forwarded into the container (no OAuth fallback inside the container — the container has no ~/.claude state)',
|
|
55
|
+
optional: true,
|
|
56
|
+
},
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Resolve runtime auth state for the dashboard (#4769, #4780).
|
|
62
|
+
*
|
|
63
|
+
* Mirror of DockerSession.resolveAuth — overrides SdkSession's OAuth
|
|
64
|
+
* fallback because the container has no ~/.claude state, so env var is
|
|
65
|
+
* the only valid path. See DockerSession for the full rationale.
|
|
66
|
+
*
|
|
67
|
+
* @param {NodeJS.ProcessEnv} env
|
|
68
|
+
* @returns {{ready:boolean, source:string, envVar:string|null, envVars:string[], hint:string, detail:string, billingClass:string}}
|
|
69
|
+
*/
|
|
70
|
+
static resolveAuth(env) {
|
|
71
|
+
const credSpec = this.preflight.credentials
|
|
72
|
+
const envVars = credSpec.envVars
|
|
73
|
+
const hint = credSpec.hint
|
|
74
|
+
|
|
75
|
+
// docker-sdk forwards the host's ANTHROPIC_API_KEY into the container and
|
|
76
|
+
// has NO OAuth fallback, so it always bills the raw API account — api-key,
|
|
77
|
+
// era-independent. The host subscription/credit pool never applies inside
|
|
78
|
+
// the container.
|
|
79
|
+
const matched = envVars.find(v => env[v])
|
|
80
|
+
if (matched) {
|
|
81
|
+
return {
|
|
82
|
+
ready: true,
|
|
83
|
+
source: 'env',
|
|
84
|
+
envVar: matched,
|
|
85
|
+
envVars,
|
|
86
|
+
hint: '',
|
|
87
|
+
detail: `Docker-isolated — Anthropic API (your ${matched})`,
|
|
88
|
+
billingClass: BILLING_CLASSES.API_KEY,
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
ready: false,
|
|
93
|
+
source: 'none',
|
|
94
|
+
envVar: null,
|
|
95
|
+
envVars,
|
|
96
|
+
hint,
|
|
97
|
+
detail: 'Not configured — set ANTHROPIC_API_KEY on the host (forwarded into the container at run time). No OAuth fallback inside the container — the container has no ~/.claude state.',
|
|
98
|
+
billingClass: BILLING_CLASSES.API_KEY,
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
constructor(opts = {}) {
|
|
103
|
+
super(opts)
|
|
104
|
+
const containerId = opts.containerId?.trim() || null
|
|
105
|
+
const containerCliPath = opts.containerCliPath?.trim() || null
|
|
106
|
+
this._containerId = containerId
|
|
107
|
+
this._containerOwned = !containerId
|
|
108
|
+
this._image = opts.image || 'node:22-slim'
|
|
109
|
+
this._memoryLimit = opts.memoryLimit || '2g'
|
|
110
|
+
this._cpuLimit = opts.cpuLimit || '2'
|
|
111
|
+
const user = opts.containerUser || 'chroxy'
|
|
112
|
+
if (!VALID_USERNAME_RE.test(user)) {
|
|
113
|
+
throw new Error(`Invalid containerUser "${user}" — must match POSIX username rules`)
|
|
114
|
+
}
|
|
115
|
+
this._containerUser = user
|
|
116
|
+
this._containerCliPath = containerCliPath
|
|
117
|
+
// #3468 + #3501: `_stdinForwardingDisabled` is initialised by the
|
|
118
|
+
// SdkSession parent constructor from the `stdinForwardingDisabled` opt
|
|
119
|
+
// (see #3540 + #3576 — restored sessions hydrate the latched flag via
|
|
120
|
+
// SessionManager.restoreState). Do NOT reassign here: a hard `= false`
|
|
121
|
+
// would clobber the hydrated value on cold restart and silently re-arm
|
|
122
|
+
// stdin forwarding for a session the previous run had already latched
|
|
123
|
+
// off, defeating the persistence introduced in PR #3564.
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Start the session: launch the container, set up the non-root user,
|
|
128
|
+
* install Claude Code, then call super.start() to mark ready.
|
|
129
|
+
*
|
|
130
|
+
* When an external containerId was provided (containerOwned: false),
|
|
131
|
+
* skips container creation and only discovers the CLI path if needed.
|
|
132
|
+
*/
|
|
133
|
+
start() {
|
|
134
|
+
if (this._containerId) {
|
|
135
|
+
// External container — verify it's reachable, then discover CLI path if needed
|
|
136
|
+
this._verifyContainer((err) => {
|
|
137
|
+
if (err) {
|
|
138
|
+
const classified = classifyDockerError(err)
|
|
139
|
+
log.warn(`External container verification failed [${classified.code}]: ${classified.message}`)
|
|
140
|
+
this.emit('error', { code: classified.code, message: classified.message })
|
|
141
|
+
this.destroy()
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
if (!this._containerCliPath) {
|
|
145
|
+
this._discoverCliPath((discoverErr) => {
|
|
146
|
+
if (discoverErr) {
|
|
147
|
+
this._containerCliPath = DEFAULT_CONTAINER_CLI_PATH
|
|
148
|
+
log.warn(`CLI path discovery failed on external container, using default: ${discoverErr.message}`)
|
|
149
|
+
}
|
|
150
|
+
super.start()
|
|
151
|
+
})
|
|
152
|
+
return
|
|
153
|
+
}
|
|
154
|
+
super.start()
|
|
155
|
+
})
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
this._startContainer((err) => {
|
|
160
|
+
if (err) {
|
|
161
|
+
this.emit('error', { code: err.code || 'docker_error', message: `Failed to start Docker container: ${err.message}` })
|
|
162
|
+
this.destroy()
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
super.start()
|
|
166
|
+
})
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Verify that an external container is reachable via docker exec.
|
|
171
|
+
* Fails fast if the container is not running or Docker is unavailable.
|
|
172
|
+
*/
|
|
173
|
+
_verifyContainer(callback) {
|
|
174
|
+
execFile('docker', [
|
|
175
|
+
'exec', this._containerId, 'true',
|
|
176
|
+
], { encoding: 'utf-8', timeout: 10_000 }, (err, _stdout, stderr) => {
|
|
177
|
+
if (err) {
|
|
178
|
+
// Attach stderr so classifyDockerError can inspect it
|
|
179
|
+
err.stderr = stderr || ''
|
|
180
|
+
callback(err)
|
|
181
|
+
} else {
|
|
182
|
+
callback(null)
|
|
183
|
+
}
|
|
184
|
+
})
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Discover the CLI path on an existing container via npm prefix -g.
|
|
189
|
+
* Used when connecting to an externally-managed container.
|
|
190
|
+
*/
|
|
191
|
+
_discoverCliPath(callback) {
|
|
192
|
+
execFile('docker', [
|
|
193
|
+
'exec', this._containerId,
|
|
194
|
+
'npm', 'prefix', '-g',
|
|
195
|
+
], { encoding: 'utf-8', timeout: 10_000 }, (prefixErr, prefixOut) => {
|
|
196
|
+
if (!prefixErr && prefixOut) {
|
|
197
|
+
this._containerCliPath = `${prefixOut.trim()}/lib/node_modules/@anthropic-ai/claude-code/cli.js`
|
|
198
|
+
log.info(`Discovered container CLI path: ${this._containerCliPath}`)
|
|
199
|
+
callback(null)
|
|
200
|
+
} else {
|
|
201
|
+
callback(prefixErr || new Error('Empty npm prefix output'))
|
|
202
|
+
}
|
|
203
|
+
})
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Launch a long-lived container with security constraints.
|
|
208
|
+
* Uses async execFile to avoid blocking the event loop during image pull.
|
|
209
|
+
*/
|
|
210
|
+
_startContainer(callback) {
|
|
211
|
+
const runArgs = [
|
|
212
|
+
'run', '-d', '--init', '--rm',
|
|
213
|
+
'--memory', this._memoryLimit,
|
|
214
|
+
'--cpus', this._cpuLimit,
|
|
215
|
+
'--pids-limit', '512',
|
|
216
|
+
'--cap-drop', 'ALL',
|
|
217
|
+
'--security-opt', 'no-new-privileges',
|
|
218
|
+
'-v', `${this.cwd || process.cwd()}:/workspace`,
|
|
219
|
+
'-w', '/workspace',
|
|
220
|
+
]
|
|
221
|
+
|
|
222
|
+
// Pass ANTHROPIC_API_KEY so Claude can authenticate
|
|
223
|
+
const apiKey = process.env.ANTHROPIC_API_KEY
|
|
224
|
+
if (apiKey) {
|
|
225
|
+
runArgs.push('--env', `ANTHROPIC_API_KEY=${apiKey}`)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// On Linux, host.docker.internal is not available by default
|
|
229
|
+
if (process.platform === 'linux') {
|
|
230
|
+
runArgs.push('--add-host', 'host.docker.internal:host-gateway')
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
runArgs.push(this._image, 'sleep', 'infinity')
|
|
234
|
+
|
|
235
|
+
log.info(`Starting container (image: ${this._image}, memory: ${this._memoryLimit}, cpus: ${this._cpuLimit})`)
|
|
236
|
+
|
|
237
|
+
execFile('docker', runArgs, { encoding: 'utf-8', timeout: 120_000 }, (err, stdout, stderr) => {
|
|
238
|
+
if (err) {
|
|
239
|
+
const classified = classifyDockerError(err, stderr)
|
|
240
|
+
log.warn(`Docker start failed [${classified.code}]: ${classified.message}`)
|
|
241
|
+
const error = new Error(classified.message)
|
|
242
|
+
error.code = classified.code
|
|
243
|
+
callback(error)
|
|
244
|
+
return
|
|
245
|
+
}
|
|
246
|
+
this._containerId = stdout.trim()
|
|
247
|
+
log.info(`Container started: ${this._containerId.slice(0, 12)}`)
|
|
248
|
+
|
|
249
|
+
// Create non-root user and install Claude Code
|
|
250
|
+
this._setupContainer(callback)
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Create a non-root user inside the container and install Claude Code CLI.
|
|
256
|
+
* Claude Code refuses --dangerously-skip-permissions as root.
|
|
257
|
+
*/
|
|
258
|
+
_setupContainer(callback) {
|
|
259
|
+
const user = this._containerUser
|
|
260
|
+
const setupCmd = [
|
|
261
|
+
`useradd -m -s /bin/bash ${user}`,
|
|
262
|
+
`chown ${user}:${user} /workspace`,
|
|
263
|
+
].join(' && ')
|
|
264
|
+
|
|
265
|
+
execFile('docker', [
|
|
266
|
+
'exec', this._containerId,
|
|
267
|
+
'bash', '-c', setupCmd,
|
|
268
|
+
], { encoding: 'utf-8', timeout: 10_000 }, (err) => {
|
|
269
|
+
if (err) {
|
|
270
|
+
callback(new Error(`Failed to create container user: ${err.message}`))
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
log.info(`Created non-root user "${user}" in container`)
|
|
274
|
+
|
|
275
|
+
this._installClaudeCode(callback)
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Install Claude Code CLI globally in the container and discover the CLI path.
|
|
281
|
+
*/
|
|
282
|
+
_installClaudeCode(callback) {
|
|
283
|
+
execFile('docker', [
|
|
284
|
+
'exec', this._containerId,
|
|
285
|
+
'npm', 'install', '-g', '@anthropic-ai/claude-code',
|
|
286
|
+
], { encoding: 'utf-8', timeout: 120_000 }, (installErr) => {
|
|
287
|
+
if (installErr) {
|
|
288
|
+
callback(new Error(`Failed to install Claude Code in container: ${installErr.message}`))
|
|
289
|
+
return
|
|
290
|
+
}
|
|
291
|
+
log.info('Claude Code installed in container')
|
|
292
|
+
|
|
293
|
+
// Discover the container's CLI path
|
|
294
|
+
execFile('docker', [
|
|
295
|
+
'exec', this._containerId,
|
|
296
|
+
'npm', 'prefix', '-g',
|
|
297
|
+
], { encoding: 'utf-8', timeout: 10_000 }, (prefixErr, prefixOut) => {
|
|
298
|
+
if (!prefixErr && prefixOut) {
|
|
299
|
+
this._containerCliPath = `${prefixOut.trim()}/lib/node_modules/@anthropic-ai/claude-code/cli.js`
|
|
300
|
+
log.info(`Container CLI path: ${this._containerCliPath}`)
|
|
301
|
+
} else {
|
|
302
|
+
this._containerCliPath = DEFAULT_CONTAINER_CLI_PATH
|
|
303
|
+
log.warn(`Could not determine CLI path, using default: ${this._containerCliPath}`)
|
|
304
|
+
}
|
|
305
|
+
callback(null)
|
|
306
|
+
})
|
|
307
|
+
})
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Augment query options with the spawnClaudeCodeProcess callback.
|
|
312
|
+
* Called by SdkSession.sendMessage() before passing options to query().
|
|
313
|
+
*/
|
|
314
|
+
_augmentQueryOptions(options) {
|
|
315
|
+
if (!this._containerId) {
|
|
316
|
+
log.warn('No container ID — spawnClaudeCodeProcess will not be injected')
|
|
317
|
+
return
|
|
318
|
+
}
|
|
319
|
+
options.spawnClaudeCodeProcess = this._createSpawnCallback()
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Create the spawnClaudeCodeProcess callback for the SDK.
|
|
324
|
+
*
|
|
325
|
+
* The SDK calls this with SpawnOptions { command, args, cwd, env, signal }
|
|
326
|
+
* and expects a SpawnedProcess (Node ChildProcess satisfies this).
|
|
327
|
+
*
|
|
328
|
+
* Delegates to DockerBackend.streamCliInEnvironment so the docker-exec
|
|
329
|
+
* invocation shape (containerUser, env allowlist, HOME/PATH, cli.js path
|
|
330
|
+
* remap, stderr logging, abort wiring) has a single source of truth.
|
|
331
|
+
*
|
|
332
|
+
* #3468: When the backend returns a SidecarProcess-shaped EventEmitter (i.e.
|
|
333
|
+
* K8sBackend after a WS reconnect), stdin forwarding can become permanently
|
|
334
|
+
* disabled mid-turn. The proc emits a one-shot `'stdin_disabled'` signal at
|
|
335
|
+
* that point — subscribe so the loss is observable instead of silent.
|
|
336
|
+
*/
|
|
337
|
+
_createSpawnCallback() {
|
|
338
|
+
const backend = this._backend || (this._backend = new DockerBackend())
|
|
339
|
+
const containerId = this._containerId
|
|
340
|
+
const containerCliPath = this._containerCliPath || DEFAULT_CONTAINER_CLI_PATH
|
|
341
|
+
const containerUser = this._containerUser
|
|
342
|
+
const hostCwd = this.cwd || process.cwd()
|
|
343
|
+
|
|
344
|
+
return (options) => {
|
|
345
|
+
const { command, args, cwd, env, signal } = options
|
|
346
|
+
const proc = backend.streamCliInEnvironment(containerId, {
|
|
347
|
+
cmd: command,
|
|
348
|
+
args,
|
|
349
|
+
env,
|
|
350
|
+
cwd,
|
|
351
|
+
signal,
|
|
352
|
+
containerUser,
|
|
353
|
+
containerCliPath,
|
|
354
|
+
hostCwd,
|
|
355
|
+
})
|
|
356
|
+
// Attach default warn-log listeners for SidecarProcess stdin failure
|
|
357
|
+
// signals (#3402, #3468, #3474). Docker procs are plain ChildProcess
|
|
358
|
+
// and never fire these events; the helper is a no-op on them so this
|
|
359
|
+
// is safe to wire unconditionally. Note: a K8s session class (when
|
|
360
|
+
// it lands) would extend SdkSession directly, not DockerSdkSession,
|
|
361
|
+
// so it must call `_attachSidecarProcessListeners` from its own
|
|
362
|
+
// spawn path — the helper lives on SdkSession precisely so any
|
|
363
|
+
// subclass can reuse it.
|
|
364
|
+
this._attachSidecarProcessListeners(proc)
|
|
365
|
+
return proc
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Destroy the session: interrupt active query, optionally remove the container,
|
|
371
|
+
* and clean up SdkSession state.
|
|
372
|
+
*
|
|
373
|
+
* When containerOwned is false (external container), the container is left
|
|
374
|
+
* running — it's managed by EnvironmentManager or the caller.
|
|
375
|
+
*/
|
|
376
|
+
destroy() {
|
|
377
|
+
const containerId = this._containerId
|
|
378
|
+
this._containerId = null
|
|
379
|
+
|
|
380
|
+
super.destroy()
|
|
381
|
+
|
|
382
|
+
if (containerId && this._containerOwned) {
|
|
383
|
+
log.info(`Removing container ${containerId.slice(0, 12)}`)
|
|
384
|
+
execFile('docker', ['rm', '-f', containerId], { stdio: 'ignore' }, (err) => {
|
|
385
|
+
if (err) log.warn(`Failed to remove container ${containerId.slice(0, 12)}: ${err.message}`)
|
|
386
|
+
})
|
|
387
|
+
} else if (containerId) {
|
|
388
|
+
log.info(`Disconnecting from external container ${containerId.slice(0, 12)} (not removing)`)
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// Re-export the forwarded env keys and default CLI path for testing.
|
|
394
|
+
// Both are owned by ./environments/backends/docker.js — re-exported here for
|
|
395
|
+
// callers that import from docker-sdk-session.js.
|
|
396
|
+
export { FORWARDED_ENV_KEYS, DEFAULT_CONTAINER_CLI_PATH }
|