@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,929 @@
|
|
|
1
|
+
import { fork, execFileSync } from 'child_process'
|
|
2
|
+
import { isWindows, forceKill } from './platform.js'
|
|
3
|
+
import { createServer } from 'http'
|
|
4
|
+
import { dirname, resolve, join } from 'path'
|
|
5
|
+
import { createInterface } from 'readline'
|
|
6
|
+
import { fileURLToPath } from 'url'
|
|
7
|
+
import { writeFileSync, readFileSync, unlinkSync, existsSync, mkdirSync } from 'fs'
|
|
8
|
+
import { homedir } from 'os'
|
|
9
|
+
import { EventEmitter } from 'events'
|
|
10
|
+
import { createTunnel, parseTunnelArg } from './tunnel/index.js'
|
|
11
|
+
import { QUICK_TUNNEL_DNS_SETTLE_MS, waitForTunnel } from './tunnel-check.js'
|
|
12
|
+
import { createLogger } from './logger.js'
|
|
13
|
+
import QRCode from 'qrcode'
|
|
14
|
+
import { writeConnectionInfo, removeConnectionInfo } from './connection-info.js'
|
|
15
|
+
import { PushManager } from './push.js'
|
|
16
|
+
|
|
17
|
+
function maskToken(token) {
|
|
18
|
+
if (!token) return ''
|
|
19
|
+
if (token.length <= 8) return token
|
|
20
|
+
return `${token.slice(0, 4)}...${token.slice(-4)}`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// #6566: the StartupDisplay connect-block lines that carry the API token —
|
|
24
|
+
// ` Token: <token>` and ` Dashboard: …?token=<token>`. Under --show-token the
|
|
25
|
+
// supervisor prints these RAW to the operator's terminal instead of letting the
|
|
26
|
+
// redacting logger scrub them back to [REDACTED] (the child's stdout is re-logged
|
|
27
|
+
// through that logger). Deliberately narrow — only the startup banner, never an
|
|
28
|
+
// arbitrary log line that happens to mention a token. Exported for the test.
|
|
29
|
+
export function isConnectBlockTokenLine(line) {
|
|
30
|
+
return /^\s*Token:\s/.test(line) || /Dashboard:\s.*\?token=/.test(line)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const __filename = fileURLToPath(import.meta.url)
|
|
34
|
+
const __dirname = dirname(__filename)
|
|
35
|
+
const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
|
|
36
|
+
const SUPERVISOR_VERSION = packageJson.version
|
|
37
|
+
const DEFAULT_PID_FILE = join(homedir(), '.chroxy', 'supervisor.pid')
|
|
38
|
+
|
|
39
|
+
const DRAIN_TIMEOUT = 30000
|
|
40
|
+
const RESTART_BACKOFFS = [2000, 2000, 3000, 3000, 5000, 5000, 8000, 8000, 10000, 10000]
|
|
41
|
+
const DEPLOY_CRASH_WINDOW = 60000
|
|
42
|
+
const MAX_DEPLOY_FAILURES = 3
|
|
43
|
+
const MAX_STANDBY_EADDRINUSE_RETRIES = 20
|
|
44
|
+
const STANDBY_EADDRINUSE_RETRY_DELAY_MS = 500
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Supervisor process: owns the tunnel, restarts the server child on crash.
|
|
48
|
+
*
|
|
49
|
+
* Architecture:
|
|
50
|
+
* [supervisor] (long-lived)
|
|
51
|
+
* ├── cloudflared (managed by TunnelManager)
|
|
52
|
+
* └── server-cli.js (child — restarted on crash, tunnel=none)
|
|
53
|
+
*
|
|
54
|
+
* The child server runs with CHROXY_SUPERVISED=1 and tunnel=none since the
|
|
55
|
+
* supervisor owns the tunnel. During child restart, the supervisor binds the
|
|
56
|
+
* port to serve a health check that returns {"status":"restarting"}.
|
|
57
|
+
*/
|
|
58
|
+
export class Supervisor extends EventEmitter {
|
|
59
|
+
constructor(config) {
|
|
60
|
+
super()
|
|
61
|
+
this.config = config
|
|
62
|
+
this._port = config.port || parseInt(process.env.PORT || '8765', 10)
|
|
63
|
+
this._apiToken = config.apiToken || process.env.API_TOKEN
|
|
64
|
+
this._tunnelMode = config.tunnel || 'quick'
|
|
65
|
+
this._pidFilePath = config.pidFilePath || DEFAULT_PID_FILE
|
|
66
|
+
this._knownGoodFile = config.knownGoodFile || join(homedir(), '.chroxy', 'known-good-ref')
|
|
67
|
+
this._maxRestarts = (typeof config.maxRestarts === 'number' && config.maxRestarts >= 0)
|
|
68
|
+
? config.maxRestarts
|
|
69
|
+
: 10
|
|
70
|
+
|
|
71
|
+
this._child = null
|
|
72
|
+
this._restartCount = 0
|
|
73
|
+
this._standbyServer = null
|
|
74
|
+
this._standbyRetries = 0
|
|
75
|
+
this._standbyRetryTimer = null
|
|
76
|
+
// #6022: terminal-down state. When the restart budget is exhausted the
|
|
77
|
+
// supervisor flips the standby server into a terminal `status:'down'`
|
|
78
|
+
// response (reason `supervisor_gave_up`) and serves it for a bounded grace
|
|
79
|
+
// window — long enough for a polling client to observe and latch the
|
|
80
|
+
// terminal state — before exiting. Configurable: 0 keeps the prior
|
|
81
|
+
// exit-immediately behaviour; a larger value extends the signal window.
|
|
82
|
+
this._terminalDown = false
|
|
83
|
+
this._terminalDownTimer = null
|
|
84
|
+
this._terminalDownGraceMs =
|
|
85
|
+
(typeof config.terminalDownGraceMs === 'number' && config.terminalDownGraceMs >= 0)
|
|
86
|
+
? config.terminalDownGraceMs
|
|
87
|
+
: 15000
|
|
88
|
+
this._shuttingDown = false
|
|
89
|
+
this._draining = false
|
|
90
|
+
this._childReady = false
|
|
91
|
+
this._tunnel = null
|
|
92
|
+
this._heartbeatInterval = null
|
|
93
|
+
this._currentWsUrl = null
|
|
94
|
+
this._signalsRegistered = false
|
|
95
|
+
this._restartScheduledAt = null
|
|
96
|
+
this._restartDelayMs = null
|
|
97
|
+
this._restartTimer = null
|
|
98
|
+
// #6027: deploy-window reset timer. Instance-scoped (was a startChild-local
|
|
99
|
+
// closure var) so shutdown()/teardown can clear it — otherwise a child that
|
|
100
|
+
// goes ready but never exits leaves a ~DEPLOY_CRASH_WINDOW timer pending.
|
|
101
|
+
this._deployResetTimer = null
|
|
102
|
+
this._log = createLogger('supervisor')
|
|
103
|
+
|
|
104
|
+
// Deploy rollback tracking
|
|
105
|
+
this._lastDeployTimestamp = 0
|
|
106
|
+
this._deployFailureCount = 0
|
|
107
|
+
|
|
108
|
+
this._metrics = {
|
|
109
|
+
startedAt: Date.now(),
|
|
110
|
+
childStartedAt: null,
|
|
111
|
+
totalRestarts: 0,
|
|
112
|
+
consecutiveRestarts: 0,
|
|
113
|
+
lastExitReason: null,
|
|
114
|
+
lastBackoffMs: 0,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
this._pushStoragePath = config.pushStoragePath || join(homedir(), '.chroxy', 'push-tokens.json')
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Override point: fork a child process */
|
|
121
|
+
_fork(script, args, opts) {
|
|
122
|
+
return fork(script, args, opts)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Override point: create tunnel adapter instance */
|
|
126
|
+
_createTunnel() {
|
|
127
|
+
const tunnelArg = parseTunnelArg(this._tunnelMode)
|
|
128
|
+
if (!tunnelArg) {
|
|
129
|
+
throw new Error('Supervisor requires a tunnel (cannot use tunnel=none)')
|
|
130
|
+
}
|
|
131
|
+
return createTunnel({
|
|
132
|
+
port: this._port,
|
|
133
|
+
mode: tunnelArg.mode,
|
|
134
|
+
tunnelConfig: this.config.tunnelConfig,
|
|
135
|
+
tunnelName: this.config.tunnelName || null,
|
|
136
|
+
tunnelHostname: this.config.tunnelHostname || null,
|
|
137
|
+
})
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Override point: wait for tunnel to be routable */
|
|
141
|
+
_waitForTunnel(url, mode = this._tunnelMode) {
|
|
142
|
+
const tunnelArg = parseTunnelArg(mode)
|
|
143
|
+
return waitForTunnel(url, {
|
|
144
|
+
initialDelay: tunnelArg?.mode === 'quick' ? QUICK_TUNNEL_DNS_SETTLE_MS : 0,
|
|
145
|
+
})
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* #5314 (WP-1.4) — last-resort handler for an uncaught error in the supervisor
|
|
150
|
+
* process. Logs it; stays alive so the child keeps being supervised (killing
|
|
151
|
+
* the supervisor would take down the whole service). Exits only if a shutdown
|
|
152
|
+
* is already underway. Extracted so tests can drive it without real signals.
|
|
153
|
+
*/
|
|
154
|
+
_onProcessError(kind, err) {
|
|
155
|
+
// Reflect the actual action: during a deliberate shutdown we exit(1); the
|
|
156
|
+
// rest of the time we stay alive and keep supervising.
|
|
157
|
+
const action = this._shuttingDown ? 'exiting — shutdown in progress' : 'staying alive'
|
|
158
|
+
this._log.error(`Supervisor ${kind} (${action}): ${err?.stack || err}`)
|
|
159
|
+
if (this._shuttingDown) this._exit(1)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* #5314 (WP-1.4) — single cleanup path for a boot failure that occurs after
|
|
164
|
+
* cloudflared has started but before the child is forked. Stops cloudflared so
|
|
165
|
+
* it doesn't leak as an orphan, then exits(1). Best-effort stop — we're exiting
|
|
166
|
+
* regardless.
|
|
167
|
+
*/
|
|
168
|
+
async _failBoot(err) {
|
|
169
|
+
this._log.error(`Supervisor boot failed before the child started: ${err?.message || err}`)
|
|
170
|
+
try {
|
|
171
|
+
await this._tunnel.stop()
|
|
172
|
+
} catch (stopErr) {
|
|
173
|
+
this._log.error(`Failed to stop cloudflared after boot failure: ${stopErr?.message || stopErr}`)
|
|
174
|
+
}
|
|
175
|
+
this._exit(1)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Override point: exit the process */
|
|
179
|
+
_exit(code) {
|
|
180
|
+
process.exit(code)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Override point: send a push notification */
|
|
184
|
+
async _sendPushNotification(category, title, body) {
|
|
185
|
+
// Create a fresh PushManager each time to reload tokens from disk.
|
|
186
|
+
// The child process writes tokens after clients connect, so the supervisor
|
|
187
|
+
// must re-read the file to pick up any tokens registered since startup.
|
|
188
|
+
//
|
|
189
|
+
// #5430: plumb the `notifications.discord` config block through, mirroring
|
|
190
|
+
// server-cli.js — otherwise the Discord sink runs with default botName/
|
|
191
|
+
// colors/throttle and a supervisor-emitted embed update ("Chroxy server is
|
|
192
|
+
// down") looks different from every other update. The statePath default
|
|
193
|
+
// matches the child server's so both processes converge on the same
|
|
194
|
+
// status message; the sink persists that state atomically (temp+rename).
|
|
195
|
+
//
|
|
196
|
+
// prefsPath mirrors server-cli.js too: without it the per-send manager
|
|
197
|
+
// falls back to default prefs, so supervisor-sent notifications would
|
|
198
|
+
// ignore the operator's category mutes / quiet hours (both sinks gate on
|
|
199
|
+
// prefs) while the child server honors them. Read-only here — the
|
|
200
|
+
// supervisor never calls setPrefs/registerToken — and fresh-per-send
|
|
201
|
+
// picks up prefs the child persisted after startup, same as the tokens.
|
|
202
|
+
const push = new PushManager({
|
|
203
|
+
storagePath: this._pushStoragePath,
|
|
204
|
+
prefsPath: join(homedir(), '.chroxy', 'notification-prefs.json'),
|
|
205
|
+
discord: {
|
|
206
|
+
statePath: join(homedir(), '.chroxy', 'discord-webhook-state.json'),
|
|
207
|
+
...(this.config.notifications?.discord || {}),
|
|
208
|
+
},
|
|
209
|
+
})
|
|
210
|
+
try {
|
|
211
|
+
await push.send(category, title, body)
|
|
212
|
+
} finally {
|
|
213
|
+
// #5413: release sink resources (the Discord heartbeat interval) —
|
|
214
|
+
// these per-send managers are short-lived by design, and without the
|
|
215
|
+
// destroy a configured Discord sink would leak one live interval per
|
|
216
|
+
// supervisor notification.
|
|
217
|
+
push.destroy()
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Override point: display QR code */
|
|
222
|
+
async _displayQr(url) {
|
|
223
|
+
const qrText = await QRCode.toString(url, { type: 'terminal', small: true })
|
|
224
|
+
process.stdout.write(qrText)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Override point: register process signal handlers */
|
|
228
|
+
_registerSignals() {
|
|
229
|
+
if (this._signalsRegistered) return
|
|
230
|
+
this._signalsRegistered = true
|
|
231
|
+
|
|
232
|
+
if (!isWindows) {
|
|
233
|
+
// Windows does not support SIGUSR2 — deploy restart is not available
|
|
234
|
+
process.on('SIGUSR2', () => {
|
|
235
|
+
if (this._draining) {
|
|
236
|
+
this._log.info('SIGUSR2 received but drain already in progress, ignoring')
|
|
237
|
+
return
|
|
238
|
+
}
|
|
239
|
+
if (!this._childReady) {
|
|
240
|
+
this._log.info('SIGUSR2 received but child not ready yet, ignoring')
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
this._log.info('SIGUSR2 received (deploy restart)')
|
|
244
|
+
this._lastDeployTimestamp = Date.now()
|
|
245
|
+
this.restartChild()
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
process.on('SIGINT', () => this.shutdown('SIGINT'))
|
|
250
|
+
process.on('SIGTERM', () => this.shutdown('SIGTERM'))
|
|
251
|
+
|
|
252
|
+
// #5314 (WP-1.4) — the supervisor had no uncaughtException/unhandledRejection
|
|
253
|
+
// handler, so a stray fault (e.g. the routine tunnel-DNS-settle rejection from
|
|
254
|
+
// an async tunnel_recovered handler) silently killed the supervisor and
|
|
255
|
+
// orphaned the child. Its job is uptime: log loudly and KEEP SUPERVISING.
|
|
256
|
+
// Only let the process exit if we're already in a deliberate shutdown.
|
|
257
|
+
process.on('uncaughtException', (err) => this._onProcessError('uncaughtException', err))
|
|
258
|
+
process.on('unhandledRejection', (err) => this._onProcessError('unhandledRejection', err))
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async start() {
|
|
262
|
+
if (!this._apiToken) {
|
|
263
|
+
process.stderr.write('[!] No API token configured. Run \'npx chroxy init\' first.\n')
|
|
264
|
+
this._exit(1)
|
|
265
|
+
return
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const bannerText = `Chroxy Supervisor v${SUPERVISOR_VERSION}`
|
|
269
|
+
const padded = bannerText.padEnd(36)
|
|
270
|
+
process.stdout.write('\n')
|
|
271
|
+
process.stdout.write('╔════════════════════════════════════════╗\n')
|
|
272
|
+
process.stdout.write(`║ ${padded} ║\n`)
|
|
273
|
+
process.stdout.write('╚════════════════════════════════════════╝\n')
|
|
274
|
+
process.stdout.write('\n')
|
|
275
|
+
|
|
276
|
+
// 1. Start the tunnel (supervisor owns it)
|
|
277
|
+
this._tunnel = this._createTunnel()
|
|
278
|
+
|
|
279
|
+
const { wsUrl, httpUrl } = await this._tunnel.start()
|
|
280
|
+
this._currentWsUrl = wsUrl
|
|
281
|
+
|
|
282
|
+
// Compute modeLabel early so tunnel_recovered handler can reference it
|
|
283
|
+
const tunnelArg = parseTunnelArg(this._tunnelMode)
|
|
284
|
+
this._modeLabel = tunnelArg ? `cloudflare:${tunnelArg.mode}` : this._tunnelMode
|
|
285
|
+
|
|
286
|
+
this._tunnel.on('tunnel_recovered', async ({ httpUrl: newHttpUrl, wsUrl: newWsUrl, attempt }) => {
|
|
287
|
+
// #5314 (WP-1.4) — this is an ASYNC event listener; an unhandled rejection
|
|
288
|
+
// here (waitForTunnel throws on a routine DNS-settle failure) would crash
|
|
289
|
+
// the supervisor. Contain it: log and let the next tunnel_recovered retry.
|
|
290
|
+
try {
|
|
291
|
+
this._log.info(`Tunnel recovered after ${attempt} attempt(s)`)
|
|
292
|
+
await this._waitForTunnel(newHttpUrl)
|
|
293
|
+
|
|
294
|
+
if (newWsUrl !== this._currentWsUrl) {
|
|
295
|
+
this._currentWsUrl = newWsUrl
|
|
296
|
+
const connectionUrl = `chroxy://${newWsUrl.replace('wss://', '')}?token=${this._apiToken}`
|
|
297
|
+
process.stdout.write('\nNew tunnel URL:\n\n')
|
|
298
|
+
await this._displayQr(connectionUrl)
|
|
299
|
+
process.stdout.write(`\n URL: ${newWsUrl}\n`)
|
|
300
|
+
process.stdout.write(` Token: ${maskToken(this._apiToken)}\n`)
|
|
301
|
+
process.stdout.write('\n')
|
|
302
|
+
|
|
303
|
+
// Update connection info file with new tunnel URL
|
|
304
|
+
writeConnectionInfo({
|
|
305
|
+
wsUrl: newWsUrl,
|
|
306
|
+
httpUrl: newHttpUrl,
|
|
307
|
+
port: this._port, // #5683 — local loopback port for the CLI
|
|
308
|
+
apiToken: this._apiToken,
|
|
309
|
+
connectionUrl,
|
|
310
|
+
tunnelMode: this._modeLabel,
|
|
311
|
+
startedAt: new Date().toISOString(),
|
|
312
|
+
pid: process.pid,
|
|
313
|
+
})
|
|
314
|
+
}
|
|
315
|
+
} catch (err) {
|
|
316
|
+
this._log.error(`tunnel_recovered handler failed (will retry on next recovery): ${err?.message || err}`)
|
|
317
|
+
}
|
|
318
|
+
})
|
|
319
|
+
|
|
320
|
+
this._tunnel.on('tunnel_failed', ({ message }) => {
|
|
321
|
+
this._log.error(message)
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
// 2-3. Wait for the tunnel to be routable, then display + persist connection
|
|
325
|
+
// info. #5314 (WP-1.4) — every step here runs while cloudflared is already
|
|
326
|
+
// up (this._tunnel.start() above) but BEFORE the child is forked, so ANY
|
|
327
|
+
// throw must stop cloudflared first or it leaks as an orphan. waitForTunnel
|
|
328
|
+
// THROWS on a routine DNS-settle failure; _displayQr (QR encode) and
|
|
329
|
+
// writeConnectionInfo (disk) can also throw. _failBoot() is the single
|
|
330
|
+
// cleanup path. (The PID write below has its own non-fatal guard, and the
|
|
331
|
+
// child fork is past the no-leak boundary.)
|
|
332
|
+
try {
|
|
333
|
+
await this._waitForTunnel(httpUrl)
|
|
334
|
+
|
|
335
|
+
// 3. Display connection info
|
|
336
|
+
const connectionUrl = `chroxy://${wsUrl.replace('wss://', '')}?token=${this._apiToken}`
|
|
337
|
+
|
|
338
|
+
this._log.info(`${this._modeLabel} ready`)
|
|
339
|
+
process.stdout.write('📱 Scan this QR code with the Chroxy app:\n\n')
|
|
340
|
+
await this._displayQr(connectionUrl)
|
|
341
|
+
process.stdout.write('\nOr connect manually:\n')
|
|
342
|
+
process.stdout.write(` URL: ${wsUrl}\n`)
|
|
343
|
+
process.stdout.write(` Token: ${maskToken(this._apiToken)}\n`)
|
|
344
|
+
const dashboardBase = httpUrl || `http://localhost:${this._port}`
|
|
345
|
+
process.stdout.write(` Dashboard: ${dashboardBase.replace(/\/+$/, '')}/dashboard\n`)
|
|
346
|
+
process.stdout.write('\n')
|
|
347
|
+
|
|
348
|
+
// 3b. Write connection info file for programmatic access
|
|
349
|
+
writeConnectionInfo({
|
|
350
|
+
wsUrl,
|
|
351
|
+
httpUrl,
|
|
352
|
+
// #5683: the LOCAL listen port, so loopback CLIs (chroxy publish / pages)
|
|
353
|
+
// hit the right port even in tunnel mode, where httpUrl is the public
|
|
354
|
+
// trycloudflare URL with no :port to parse.
|
|
355
|
+
port: this._port,
|
|
356
|
+
apiToken: this._apiToken,
|
|
357
|
+
connectionUrl,
|
|
358
|
+
tunnelMode: this._modeLabel,
|
|
359
|
+
startedAt: new Date().toISOString(),
|
|
360
|
+
pid: process.pid,
|
|
361
|
+
})
|
|
362
|
+
} catch (err) {
|
|
363
|
+
await this._failBoot(err)
|
|
364
|
+
return
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// 4. Write PID file
|
|
368
|
+
try {
|
|
369
|
+
mkdirSync(dirname(this._pidFilePath), { recursive: true })
|
|
370
|
+
writeFileSync(this._pidFilePath, String(process.pid))
|
|
371
|
+
this._log.info(`PID file written: ${this._pidFilePath} (pid: ${process.pid})`)
|
|
372
|
+
} catch (err) {
|
|
373
|
+
this._log.error(`Failed to write PID file ${this._pidFilePath}: ${err.message}`)
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// 5. Start the first child
|
|
377
|
+
this.startChild()
|
|
378
|
+
|
|
379
|
+
// 6. Periodic heartbeat
|
|
380
|
+
this._heartbeatInterval = setInterval(() => {
|
|
381
|
+
if (!this._child || this._shuttingDown) return
|
|
382
|
+
const childUptime = this._metrics.childStartedAt ? Math.round((Date.now() - this._metrics.childStartedAt) / 1000) : 0
|
|
383
|
+
const totalUptime = Math.round((Date.now() - this._metrics.startedAt) / 1000)
|
|
384
|
+
this._log.info(`Heartbeat: uptime=${totalUptime}s, childUptime=${childUptime}s, totalRestarts=${this._metrics.totalRestarts}`)
|
|
385
|
+
}, 5 * 60 * 1000)
|
|
386
|
+
this._heartbeatInterval.unref()
|
|
387
|
+
|
|
388
|
+
// 7. Register signal handlers
|
|
389
|
+
this._registerSignals()
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
startChild() {
|
|
393
|
+
if (this._shuttingDown) return
|
|
394
|
+
|
|
395
|
+
// Defensive: cancel any pending crash-backoff restart so two startChild()
|
|
396
|
+
// calls can't fork two children. A child crash schedules
|
|
397
|
+
// `_restartTimer = setTimeout(startChild, backoff)`; if a restartChild()
|
|
398
|
+
// lands during that backoff window its `!this._child` branch calls
|
|
399
|
+
// startChild() immediately — without this, the still-pending backoff timer
|
|
400
|
+
// would later fire a SECOND startChild() and orphan the first child. The
|
|
401
|
+
// SIGUSR2 `_childReady` guard makes the race rare, but a direct/extra caller
|
|
402
|
+
// would otherwise double-fork. Clearing an already-fired timer is a no-op,
|
|
403
|
+
// so the normal timer-driven restart path is unaffected.
|
|
404
|
+
if (this._restartTimer) {
|
|
405
|
+
clearTimeout(this._restartTimer)
|
|
406
|
+
this._restartTimer = null
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// Free the port BEFORE forking the replacement child. After a crash the
|
|
410
|
+
// exit handler starts a standby health server bound to `this._port`; if it
|
|
411
|
+
// is still listening when the new child forks, the child's own `listen()`
|
|
412
|
+
// fails with EADDRINUSE and it exits before sending `ready` — so the
|
|
413
|
+
// `_stopStandbyServer()` on `ready` (below) never runs, the standby stays
|
|
414
|
+
// up, and every restart attempt hits the same EADDRINUSE until the restart
|
|
415
|
+
// cap, silently bricking the daemon on the first crash. Stopping standby
|
|
416
|
+
// here (idempotent when none is running, e.g. the first start) guarantees
|
|
417
|
+
// the port is available for the child to bind. `close()` releases the
|
|
418
|
+
// listening socket; the standby has no keep-alive clients to drain.
|
|
419
|
+
this._stopStandbyServer()
|
|
420
|
+
|
|
421
|
+
const childScript = resolve(__dirname, 'server-cli-child.js')
|
|
422
|
+
const childEnv = {
|
|
423
|
+
...process.env,
|
|
424
|
+
CHROXY_SUPERVISED: '1',
|
|
425
|
+
CHROXY_TUNNEL: 'none',
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
if (this.config.apiToken) childEnv.API_TOKEN = this.config.apiToken
|
|
429
|
+
if (this.config.port) childEnv.PORT = String(this.config.port)
|
|
430
|
+
if (this.config.cwd) childEnv.CHROXY_CWD = this.config.cwd
|
|
431
|
+
if (this.config.model) childEnv.CHROXY_MODEL = this.config.model
|
|
432
|
+
if (this.config.showToken) childEnv.CHROXY_SHOW_TOKEN = '1'
|
|
433
|
+
this._log.info(`Starting server child (attempt ${this._restartCount + 1})`)
|
|
434
|
+
this._metrics.childStartedAt = Date.now()
|
|
435
|
+
|
|
436
|
+
this._child = this._fork(childScript, [], {
|
|
437
|
+
env: childEnv,
|
|
438
|
+
stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
|
|
439
|
+
})
|
|
440
|
+
|
|
441
|
+
let stdoutRl, stderrRl
|
|
442
|
+
if (this._child.stdout) {
|
|
443
|
+
stdoutRl = createInterface({ input: this._child.stdout })
|
|
444
|
+
stdoutRl.on('line', (line) => {
|
|
445
|
+
// #6566: honour --show-token through the supervisor pipe. The child prints
|
|
446
|
+
// the real token in the connect-block when --show-token is set, but the
|
|
447
|
+
// logger's secret-redaction scrubs it on the way to the terminal. When the
|
|
448
|
+
// operator explicitly asked to see it, print those lines RAW to the
|
|
449
|
+
// terminal and log a REDACTED copy to the FILE only (toConsole:false), so
|
|
450
|
+
// the token reaches the operator's terminal but never lands on disk.
|
|
451
|
+
if (this.config.showToken && isConnectBlockTokenLine(line)) {
|
|
452
|
+
process.stdout.write(`${line}\n`)
|
|
453
|
+
this._log.info(`[child:out] ${line}`, { toConsole: false })
|
|
454
|
+
return
|
|
455
|
+
}
|
|
456
|
+
this._log.info(`[child:out] ${line}`)
|
|
457
|
+
})
|
|
458
|
+
}
|
|
459
|
+
if (this._child.stderr) {
|
|
460
|
+
stderrRl = createInterface({ input: this._child.stderr })
|
|
461
|
+
stderrRl.on('line', (line) => {
|
|
462
|
+
this._log.error(`[child:err] ${line}`)
|
|
463
|
+
})
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
this._child.on('message', (msg) => {
|
|
467
|
+
if (msg.type === 'ready') {
|
|
468
|
+
this._log.info('Server child is ready')
|
|
469
|
+
this._childReady = true
|
|
470
|
+
this._restartCount = 0
|
|
471
|
+
this._restartScheduledAt = null
|
|
472
|
+
this._restartDelayMs = null
|
|
473
|
+
this._metrics.consecutiveRestarts = 0
|
|
474
|
+
this._stopStandbyServer()
|
|
475
|
+
this.emit('child_ready')
|
|
476
|
+
|
|
477
|
+
// Only reset deploy failure count after child survives past the crash window
|
|
478
|
+
if (this._lastDeployTimestamp > 0 && this._deployFailureCount > 0) {
|
|
479
|
+
const remaining = DEPLOY_CRASH_WINDOW - (Date.now() - this._lastDeployTimestamp)
|
|
480
|
+
if (remaining > 0) {
|
|
481
|
+
this._deployResetTimer = setTimeout(() => {
|
|
482
|
+
this._deployResetTimer = null
|
|
483
|
+
this._deployFailureCount = 0
|
|
484
|
+
this._log.info('Deploy crash window passed, resetting failure count')
|
|
485
|
+
}, remaining)
|
|
486
|
+
} else {
|
|
487
|
+
this._deployFailureCount = 0
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
if (msg.type === 'drain_complete') {
|
|
493
|
+
this._log.info('Child drain complete, sending SIGTERM')
|
|
494
|
+
this._draining = false
|
|
495
|
+
try { this._child.kill('SIGTERM') } catch {}
|
|
496
|
+
}
|
|
497
|
+
})
|
|
498
|
+
|
|
499
|
+
this._child.on('exit', (code, signal) => {
|
|
500
|
+
// Use a non-async outer listener with a guarded inner async IIFE so that
|
|
501
|
+
// any uncaught throw in the handler is logged rather than becoming an
|
|
502
|
+
// unhandled promise rejection (EventEmitter does not observe returned promises).
|
|
503
|
+
void (async () => {
|
|
504
|
+
stdoutRl?.close()
|
|
505
|
+
stderrRl?.close()
|
|
506
|
+
if (this._deployResetTimer) { clearTimeout(this._deployResetTimer); this._deployResetTimer = null }
|
|
507
|
+
const childUptimeMs = this._metrics.childStartedAt ? Date.now() - this._metrics.childStartedAt : 0
|
|
508
|
+
this._child = null
|
|
509
|
+
this._childReady = false
|
|
510
|
+
if (this._shuttingDown) return
|
|
511
|
+
|
|
512
|
+
this._log.info(`Server child exited (code ${code}, signal ${signal})`)
|
|
513
|
+
this._restartCount++
|
|
514
|
+
this._metrics.totalRestarts++
|
|
515
|
+
this._metrics.consecutiveRestarts = this._restartCount
|
|
516
|
+
this._metrics.lastExitReason = { code, signal }
|
|
517
|
+
this._metrics.childStartedAt = null
|
|
518
|
+
this.emit('child_exit', { code, signal })
|
|
519
|
+
|
|
520
|
+
// Deploy crash detection
|
|
521
|
+
const timeSinceDeploy = Date.now() - this._lastDeployTimestamp
|
|
522
|
+
if (this._lastDeployTimestamp > 0 && timeSinceDeploy < DEPLOY_CRASH_WINDOW) {
|
|
523
|
+
this._deployFailureCount++
|
|
524
|
+
this._log.error(`Deploy crash detected (${this._deployFailureCount}/${MAX_DEPLOY_FAILURES}) — child lasted ${Math.round(childUptimeMs / 1000)}s`)
|
|
525
|
+
|
|
526
|
+
if (this._deployFailureCount >= MAX_DEPLOY_FAILURES) {
|
|
527
|
+
this._log.error('Max deploy failures reached, attempting rollback')
|
|
528
|
+
if (this._rollbackToKnownGood()) {
|
|
529
|
+
this._deployFailureCount = 0
|
|
530
|
+
this._lastDeployTimestamp = 0
|
|
531
|
+
this._restartCount = 0
|
|
532
|
+
this._startStandbyServer()
|
|
533
|
+
this._restartScheduledAt = Date.now()
|
|
534
|
+
this._restartDelayMs = 2000
|
|
535
|
+
this._restartTimer = setTimeout(() => this.startChild(), 2000)
|
|
536
|
+
return
|
|
537
|
+
}
|
|
538
|
+
this._log.error('Rollback failed — exiting to prevent crash loop')
|
|
539
|
+
this._exit(1)
|
|
540
|
+
return
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
if (this._restartCount > this._maxRestarts) {
|
|
545
|
+
this._log.error(`Max restarts (${this._maxRestarts}) exceeded, giving up`)
|
|
546
|
+
this.emit('max_restarts_exceeded')
|
|
547
|
+
try {
|
|
548
|
+
// Cap the push wait at 5s so a slow network cannot delay process exit
|
|
549
|
+
// meaningfully. The notification is best-effort.
|
|
550
|
+
const pushTimeout = new Promise((_, reject) =>
|
|
551
|
+
setTimeout(() => reject(new Error('push notification timed out')), 5000)
|
|
552
|
+
)
|
|
553
|
+
await Promise.race([
|
|
554
|
+
this._sendPushNotification(
|
|
555
|
+
'activity_error',
|
|
556
|
+
'Chroxy server is down',
|
|
557
|
+
'Maximum restart attempts exceeded. Restart the Chroxy daemon.',
|
|
558
|
+
),
|
|
559
|
+
pushTimeout,
|
|
560
|
+
])
|
|
561
|
+
} catch (pushErr) {
|
|
562
|
+
this._log.error(`Failed to send push notification on supervisor exit: ${pushErr.message}`)
|
|
563
|
+
}
|
|
564
|
+
// #6022: serve a terminal-down signal before exiting. The crash-looping
|
|
565
|
+
// child is dead, so there is no live WS path to broadcast a final
|
|
566
|
+
// shutdown through (the "dead-child problem"). Instead the supervisor —
|
|
567
|
+
// which still owns the port and the tunnel — flips the standby server
|
|
568
|
+
// into a terminal `status:'down'` response and serves it for a bounded
|
|
569
|
+
// grace window. A reconnecting client (local or remote, via the tunnel)
|
|
570
|
+
// polling /health during that window sees an explicit terminal-down
|
|
571
|
+
// status and can latch its "server appears down" state, instead of
|
|
572
|
+
// reconnect-looping forever once the port goes silent. After the grace
|
|
573
|
+
// window the supervisor exits(1) as before — freeing the port and
|
|
574
|
+
// preserving any outer launchd/KeepAlive recovery semantics.
|
|
575
|
+
this._serveTerminalDown()
|
|
576
|
+
return
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// Start standby health check server while child is down
|
|
580
|
+
this._startStandbyServer()
|
|
581
|
+
|
|
582
|
+
const delay = RESTART_BACKOFFS[Math.min(this._restartCount - 1, RESTART_BACKOFFS.length - 1)]
|
|
583
|
+
this._metrics.lastBackoffMs = delay
|
|
584
|
+
this._restartScheduledAt = Date.now()
|
|
585
|
+
this._restartDelayMs = delay
|
|
586
|
+
this._log.info(`Child ran for ${Math.round(childUptimeMs / 1000)}s | total restarts: ${this._metrics.totalRestarts} | next backoff: ${delay}ms`)
|
|
587
|
+
this._restartTimer = setTimeout(() => this.startChild(), delay)
|
|
588
|
+
})().catch((err) => this._log.error(`Unexpected error in child exit handler: ${err.message}`))
|
|
589
|
+
})
|
|
590
|
+
|
|
591
|
+
this._child.on('error', (err) => {
|
|
592
|
+
this._log.error(`Child process error: ${err.message}`)
|
|
593
|
+
})
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* While the child is down, serve {"status":"restarting"} on the port
|
|
598
|
+
* so the app knows the server is coming back (not permanently dead).
|
|
599
|
+
*/
|
|
600
|
+
_startStandbyServer() {
|
|
601
|
+
if (this._standbyServer) return
|
|
602
|
+
|
|
603
|
+
if (this._standbyRetries >= MAX_STANDBY_EADDRINUSE_RETRIES) {
|
|
604
|
+
this._log.error(`Standby server: giving up after ${MAX_STANDBY_EADDRINUSE_RETRIES} EADDRINUSE retries`)
|
|
605
|
+
// Reset so future restart cycles can attempt standby again
|
|
606
|
+
this._standbyRetries = 0
|
|
607
|
+
return
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
this._standbyServer = createServer((req, res) => {
|
|
611
|
+
if (req.method === 'GET' && (req.url === '/' || req.url === '/health')) {
|
|
612
|
+
// #6022: terminal-down — the restart budget is exhausted and the
|
|
613
|
+
// supervisor is about to exit. Report an explicit, non-transient down
|
|
614
|
+
// status so a polling client distinguishes "gave up" from the
|
|
615
|
+
// recoverable "restarting" state (and from a silent port = asleep).
|
|
616
|
+
if (this._terminalDown) {
|
|
617
|
+
// 200 (not 503) deliberately: the client health probe discards the
|
|
618
|
+
// body on a non-2xx response (`if (!res.ok) throw`) and keys off the
|
|
619
|
+
// `status` field — exactly as it does for the 200 `status:'restarting'`
|
|
620
|
+
// signal. A 503 would make this terminal-down body invisible to the
|
|
621
|
+
// reconnect ladder (#6023). The `status:'down'` field is the
|
|
622
|
+
// discriminator; selection still keys off `status:'ok'`, so a 'down'
|
|
623
|
+
// box is never mistaken for a healthy one.
|
|
624
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
625
|
+
res.end(JSON.stringify({
|
|
626
|
+
status: 'down',
|
|
627
|
+
reason: 'supervisor_gave_up',
|
|
628
|
+
fatal: true,
|
|
629
|
+
metrics: {
|
|
630
|
+
supervisorUptimeS: Math.round((Date.now() - this._metrics.startedAt) / 1000),
|
|
631
|
+
totalRestarts: this._metrics.totalRestarts,
|
|
632
|
+
consecutiveRestarts: this._metrics.consecutiveRestarts,
|
|
633
|
+
lastExitReason: this._metrics.lastExitReason,
|
|
634
|
+
lastBackoffMs: this._metrics.lastBackoffMs,
|
|
635
|
+
},
|
|
636
|
+
}))
|
|
637
|
+
return
|
|
638
|
+
}
|
|
639
|
+
// Calculate restart ETA: remaining backoff time + estimated child startup (~5s)
|
|
640
|
+
// Uses actual scheduled time to account for elapsed wait since the restart was queued
|
|
641
|
+
const STARTUP_ESTIMATE = 5000
|
|
642
|
+
let restartEtaMs
|
|
643
|
+
if (this._restartScheduledAt && this._restartDelayMs != null) {
|
|
644
|
+
const elapsed = Date.now() - this._restartScheduledAt
|
|
645
|
+
const remaining = Math.max(0, this._restartDelayMs - elapsed)
|
|
646
|
+
restartEtaMs = remaining + STARTUP_ESTIMATE
|
|
647
|
+
} else {
|
|
648
|
+
// Fallback: estimate from backoff schedule (first request before tracking is set)
|
|
649
|
+
const backoffIdx = Math.min(this._restartCount - 1, RESTART_BACKOFFS.length - 1)
|
|
650
|
+
const nextBackoff = backoffIdx >= 0 ? RESTART_BACKOFFS[backoffIdx] : 2000
|
|
651
|
+
restartEtaMs = nextBackoff + STARTUP_ESTIMATE
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
655
|
+
res.end(JSON.stringify({
|
|
656
|
+
status: 'restarting',
|
|
657
|
+
restartEtaMs,
|
|
658
|
+
metrics: {
|
|
659
|
+
supervisorUptimeS: Math.round((Date.now() - this._metrics.startedAt) / 1000),
|
|
660
|
+
totalRestarts: this._metrics.totalRestarts,
|
|
661
|
+
consecutiveRestarts: this._metrics.consecutiveRestarts,
|
|
662
|
+
lastExitReason: this._metrics.lastExitReason,
|
|
663
|
+
lastBackoffMs: this._metrics.lastBackoffMs,
|
|
664
|
+
},
|
|
665
|
+
}))
|
|
666
|
+
return
|
|
667
|
+
}
|
|
668
|
+
res.writeHead(503)
|
|
669
|
+
res.end()
|
|
670
|
+
})
|
|
671
|
+
|
|
672
|
+
this._standbyServer.on('error', (err) => {
|
|
673
|
+
if (err.code === 'EADDRINUSE') {
|
|
674
|
+
this._standbyRetries++
|
|
675
|
+
this._standbyRetryTimer = setTimeout(() => {
|
|
676
|
+
this._standbyRetryTimer = null
|
|
677
|
+
if (this._standbyServer) {
|
|
678
|
+
this._standbyServer.close()
|
|
679
|
+
this._standbyServer = null
|
|
680
|
+
this._startStandbyServer()
|
|
681
|
+
}
|
|
682
|
+
}, STANDBY_EADDRINUSE_RETRY_DELAY_MS)
|
|
683
|
+
return
|
|
684
|
+
}
|
|
685
|
+
this._log.error(`Standby server error: ${err.message}`)
|
|
686
|
+
})
|
|
687
|
+
|
|
688
|
+
this._standbyServer.listen(this._port, () => {
|
|
689
|
+
this._standbyRetries = 0
|
|
690
|
+
this._log.info(`Standby health check server on port ${this._port}`)
|
|
691
|
+
})
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
_stopStandbyServer() {
|
|
695
|
+
if (this._standbyRetryTimer) {
|
|
696
|
+
clearTimeout(this._standbyRetryTimer)
|
|
697
|
+
this._standbyRetryTimer = null
|
|
698
|
+
}
|
|
699
|
+
if (this._standbyServer) {
|
|
700
|
+
this._standbyServer.close()
|
|
701
|
+
this._standbyServer = null
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* #6022 — the restart budget is exhausted. Bind the port (reusing the standby
|
|
707
|
+
* server, now in terminal-down mode) to serve an explicit
|
|
708
|
+
* `status:'down' reason:'supervisor_gave_up'` health response, hold it for the
|
|
709
|
+
* configured grace window so a polling client can observe and latch the
|
|
710
|
+
* terminal state, then exit(1). A grace of 0 preserves the prior
|
|
711
|
+
* exit-immediately behaviour (the terminal server is started and torn down on
|
|
712
|
+
* the next tick).
|
|
713
|
+
*/
|
|
714
|
+
_serveTerminalDown() {
|
|
715
|
+
// Idempotent: the give-up branch is single-call by construction (the child
|
|
716
|
+
// is dead and not respawned), but guard defensively against a future caller.
|
|
717
|
+
if (this._terminalDown) return
|
|
718
|
+
this._terminalDown = true
|
|
719
|
+
// Reuse the standby server machinery (incl. its EADDRINUSE retry) — the
|
|
720
|
+
// crash-looped child is dead, so the port is normally free. The handler
|
|
721
|
+
// serves the terminal-down body while `_terminalDown` is set.
|
|
722
|
+
this._startStandbyServer()
|
|
723
|
+
this._terminalDownTimer = setTimeout(() => {
|
|
724
|
+
this._terminalDownTimer = null
|
|
725
|
+
this._stopStandbyServer()
|
|
726
|
+
this._exit(1)
|
|
727
|
+
}, this._terminalDownGraceMs)
|
|
728
|
+
// Do NOT unref: this timer is the supervisor's last responsibility — the
|
|
729
|
+
// process must stay alive serving the terminal-down status until it fires.
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* Graceful restart: drain the child, wait for completion, then restart.
|
|
734
|
+
* Used by the deploy command via SIGUSR2.
|
|
735
|
+
*/
|
|
736
|
+
restartChild() {
|
|
737
|
+
if (this._draining || this._shuttingDown) {
|
|
738
|
+
this._log.info('Restart requested but already draining/shutting down, ignoring')
|
|
739
|
+
return
|
|
740
|
+
}
|
|
741
|
+
if (!this._child) {
|
|
742
|
+
this._log.info('Restart requested but no child running, starting fresh')
|
|
743
|
+
this.startChild()
|
|
744
|
+
return
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
this._draining = true
|
|
748
|
+
this._log.info('Graceful restart: sending drain to child')
|
|
749
|
+
this._child.send({ type: 'drain', timeout: DRAIN_TIMEOUT })
|
|
750
|
+
|
|
751
|
+
const drainTimer = setTimeout(() => {
|
|
752
|
+
if (this._draining && this._child) {
|
|
753
|
+
this._log.info(`Drain timeout (${DRAIN_TIMEOUT}ms), force-killing child`)
|
|
754
|
+
this._draining = false
|
|
755
|
+
try { this._child.kill('SIGTERM') } catch {}
|
|
756
|
+
}
|
|
757
|
+
}, DRAIN_TIMEOUT)
|
|
758
|
+
// #6043: fire-and-forget drain safety net — never gate process exit on it.
|
|
759
|
+
// The supervisor stays alive via its own listening handles during a drain;
|
|
760
|
+
// this timer is only the fallback SIGTERM if the child ignores drain.
|
|
761
|
+
if (typeof drainTimer.unref === 'function') drainTimer.unref()
|
|
762
|
+
|
|
763
|
+
if (this._child) {
|
|
764
|
+
this._child.once('exit', () => clearTimeout(drainTimer))
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* Rollback to the last known-good git commit.
|
|
770
|
+
*
|
|
771
|
+
* Hardened against Adversary A9 (2026-04-11 audit): an attacker who
|
|
772
|
+
* holds a session-capable WS token could previously create a
|
|
773
|
+
* session with cwd=~/.chroxy, call `write_file` on `known-good-ref`
|
|
774
|
+
* with an arbitrary git SHA, and wait for a crash-loop restart to
|
|
775
|
+
* trigger the rollback — at which point the supervisor would check
|
|
776
|
+
* out whatever commit the attacker chose (potentially an older,
|
|
777
|
+
* exploitable version of the server).
|
|
778
|
+
*
|
|
779
|
+
* Two layers of defense now close this:
|
|
780
|
+
*
|
|
781
|
+
* 1. `~/.chroxy` is in FORBIDDEN_HOME_SUBDIRS, so sessions can no
|
|
782
|
+
* longer create a cwd inside it — the attacker can't reach
|
|
783
|
+
* `known-good-ref` via `write_file`.
|
|
784
|
+
*
|
|
785
|
+
* 2. This function validates that the ref resolves to the SAME
|
|
786
|
+
* commit as an existing `known-good-*` git tag. The tag is
|
|
787
|
+
* written by `chroxy deploy` immediately after the ref file, is
|
|
788
|
+
* never updated from the WS handlers, and lives in the git
|
|
789
|
+
* object database (not the filesystem). Even if layer 1 were
|
|
790
|
+
* bypassed, the attacker would need to also create a matching
|
|
791
|
+
* git tag — which requires filesystem access to `.git/refs/tags`
|
|
792
|
+
* or a local git invocation, both of which already imply full
|
|
793
|
+
* machine compromise.
|
|
794
|
+
*/
|
|
795
|
+
_rollbackToKnownGood() {
|
|
796
|
+
if (!existsSync(this._knownGoodFile)) {
|
|
797
|
+
this._log.error('No known-good ref file found, cannot rollback')
|
|
798
|
+
return false
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
try {
|
|
802
|
+
const ref = readFileSync(this._knownGoodFile, 'utf-8').trim()
|
|
803
|
+
// SHA-1 git commits are 40 hex chars; accept short SHAs
|
|
804
|
+
// ≥ 7 chars to match historical behavior but require
|
|
805
|
+
// hex-only content. Rejects arbitrary branch names, refspecs,
|
|
806
|
+
// option flags (-rf, --help), etc.
|
|
807
|
+
if (!/^[0-9a-f]{7,40}$/i.test(ref)) {
|
|
808
|
+
this._log.error(`Invalid known-good ref format: "${ref.slice(0, 64)}"`)
|
|
809
|
+
return false
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
const repoRoot = execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf-8' }).trim()
|
|
813
|
+
if (!repoRoot) {
|
|
814
|
+
this._log.error('Failed to determine git repository root, cannot rollback')
|
|
815
|
+
return false
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// A9 defense: require the ref to match a `known-good-*` tag's
|
|
819
|
+
// commit. This guarantees the ref was written by `chroxy deploy`
|
|
820
|
+
// and not by a compromised WS handler — deploy creates the tag
|
|
821
|
+
// immediately before/after writing the ref file.
|
|
822
|
+
let refFullSha
|
|
823
|
+
try {
|
|
824
|
+
refFullSha = execFileSync('git', ['rev-parse', '--verify', `${ref}^{commit}`], { encoding: 'utf-8', cwd: repoRoot, stdio: ['ignore', 'pipe', 'pipe'] }).trim()
|
|
825
|
+
} catch {
|
|
826
|
+
this._log.error(`Known-good ref "${ref}" does not resolve to a git commit; refusing rollback`)
|
|
827
|
+
return false
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
let knownGoodTags = ''
|
|
831
|
+
try {
|
|
832
|
+
knownGoodTags = execFileSync('git', ['tag', '--list', 'known-good-*'], { encoding: 'utf-8', cwd: repoRoot }).trim()
|
|
833
|
+
} catch {}
|
|
834
|
+
const tags = knownGoodTags ? knownGoodTags.split('\n').filter(Boolean) : []
|
|
835
|
+
let matched = false
|
|
836
|
+
for (const tag of tags) {
|
|
837
|
+
try {
|
|
838
|
+
const tagSha = execFileSync('git', ['rev-parse', '--verify', `${tag}^{commit}`], { encoding: 'utf-8', cwd: repoRoot, stdio: ['ignore', 'pipe', 'pipe'] }).trim()
|
|
839
|
+
if (tagSha === refFullSha) {
|
|
840
|
+
matched = true
|
|
841
|
+
break
|
|
842
|
+
}
|
|
843
|
+
} catch {
|
|
844
|
+
// Skip unresolvable tags — real known-good tags always resolve
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
if (!matched) {
|
|
848
|
+
this._log.error(`Known-good ref "${ref.slice(0, 8)}" does not match any known-good-* tag; refusing rollback (possible A9 poisoning attempt)`)
|
|
849
|
+
return false
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
let originalBranch = 'unknown'
|
|
853
|
+
try {
|
|
854
|
+
originalBranch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { encoding: 'utf-8', cwd: repoRoot }).trim()
|
|
855
|
+
} catch {}
|
|
856
|
+
|
|
857
|
+
this._log.info(`Rolling back to known-good commit: ${ref.slice(0, 8)}`)
|
|
858
|
+
execFileSync('git', ['checkout', ref], { stdio: 'pipe', cwd: repoRoot })
|
|
859
|
+
const recoverHint = originalBranch && originalBranch !== 'HEAD'
|
|
860
|
+
? `git checkout ${originalBranch}`
|
|
861
|
+
: 'git reflog # find your previous HEAD and git checkout <ref>'
|
|
862
|
+
this._log.info(`Rollback successful. To recover: ${recoverHint}`)
|
|
863
|
+
return true
|
|
864
|
+
} catch (err) {
|
|
865
|
+
const stderr = err.stderr?.toString?.().trim()
|
|
866
|
+
if (stderr) this._log.error(`Rollback git stderr: ${stderr}`)
|
|
867
|
+
this._log.error(`Rollback failed: ${err.message}`)
|
|
868
|
+
return false
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
async shutdown(signal) {
|
|
873
|
+
if (this._shuttingDown) return
|
|
874
|
+
this._shuttingDown = true
|
|
875
|
+
if (this._heartbeatInterval) clearInterval(this._heartbeatInterval)
|
|
876
|
+
if (this._restartTimer) clearTimeout(this._restartTimer)
|
|
877
|
+
if (this._deployResetTimer) { clearTimeout(this._deployResetTimer); this._deployResetTimer = null }
|
|
878
|
+
// #6022: a SIGINT/SIGTERM during the terminal-down grace window pre-empts it
|
|
879
|
+
// — drop the pending exit(1) timer; the shutdown path below exits(0) cleanly.
|
|
880
|
+
if (this._terminalDownTimer) { clearTimeout(this._terminalDownTimer); this._terminalDownTimer = null }
|
|
881
|
+
this._log.info(`${signal} received, shutting down...`)
|
|
882
|
+
|
|
883
|
+
// Remove PID file
|
|
884
|
+
try { unlinkSync(this._pidFilePath) } catch {}
|
|
885
|
+
removeConnectionInfo()
|
|
886
|
+
|
|
887
|
+
this._stopStandbyServer()
|
|
888
|
+
|
|
889
|
+
if (this._child) {
|
|
890
|
+
const childRef = this._child
|
|
891
|
+
childRef.send({ type: 'shutdown' })
|
|
892
|
+
const forceKillTimer = setTimeout(() => {
|
|
893
|
+
this._log.info('Force-killing child after 5s timeout')
|
|
894
|
+
try { forceKill(childRef) } catch {}
|
|
895
|
+
}, 5000)
|
|
896
|
+
// #6043: fire-and-forget shutdown safety net — never gate process exit on
|
|
897
|
+
// it. During shutdown the supervisor is held alive by the awaited
|
|
898
|
+
// tunnel.stop() and remaining handles; the goal of this path is exit, so
|
|
899
|
+
// if the loop is otherwise idle the process should exit, not be pinned for
|
|
900
|
+
// 5s. The child is in this process group and is reaped on full exit.
|
|
901
|
+
if (typeof forceKillTimer.unref === 'function') forceKillTimer.unref()
|
|
902
|
+
|
|
903
|
+
childRef.once('exit', () => clearTimeout(forceKillTimer))
|
|
904
|
+
|
|
905
|
+
// Register the exit-driven _exit(0) call BEFORE awaiting the tunnel so
|
|
906
|
+
// it is in place even if the child exits while the tunnel is stopping.
|
|
907
|
+
// The 5s force-kill above ensures the child eventually exits even if it
|
|
908
|
+
// ignores the shutdown message, so this listener always fires.
|
|
909
|
+
childRef.once('exit', () => this._exit(0))
|
|
910
|
+
|
|
911
|
+
if (this._tunnel) {
|
|
912
|
+
await this._tunnel.stop()
|
|
913
|
+
}
|
|
914
|
+
} else {
|
|
915
|
+
if (this._tunnel) {
|
|
916
|
+
await this._tunnel.stop()
|
|
917
|
+
}
|
|
918
|
+
this._exit(0)
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/**
|
|
924
|
+
* Backward-compatible wrapper: create and start a Supervisor.
|
|
925
|
+
*/
|
|
926
|
+
export async function startSupervisor(config) {
|
|
927
|
+
const supervisor = new Supervisor(config)
|
|
928
|
+
await supervisor.start()
|
|
929
|
+
}
|