@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,281 @@
|
|
|
1
|
+
import { spawn, execFileSync } from 'child_process'
|
|
2
|
+
import { BaseTunnelAdapter } from './base.js'
|
|
3
|
+
import { createLogger, redactSensitive } from '../logger.js'
|
|
4
|
+
|
|
5
|
+
const log = createLogger('tunnel')
|
|
6
|
+
|
|
7
|
+
// #5328 (WP-5.6): how much of cloudflared's recent output to retain so a
|
|
8
|
+
// startup failure can quote the REAL reason in its error, not just an exit code.
|
|
9
|
+
const CLOUDFLARED_OUTPUT_TAIL_CAP = 2000
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Redact + trim a raw cloudflared output tail for inclusion in a start-failure
|
|
13
|
+
* rejection. Centralized so the named AND quick paths redact identically — a
|
|
14
|
+
* token split across two `data` chunks survives a per-chunk redact, so the
|
|
15
|
+
* whole accumulated tail is redacted once here (#5366 review). Returns '' when
|
|
16
|
+
* the tail is empty.
|
|
17
|
+
*/
|
|
18
|
+
function redactedTail(rawTail) {
|
|
19
|
+
return redactSensitive(rawTail || '').trim()
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Cloudflare tunnel adapter.
|
|
24
|
+
*
|
|
25
|
+
* Quick mode: spawns `cloudflared tunnel --url` — random URL, no account needed.
|
|
26
|
+
* Named mode: spawns `cloudflared tunnel run <name>` — stable URL via DNS CNAME.
|
|
27
|
+
*/
|
|
28
|
+
export class CloudflareTunnelAdapter extends BaseTunnelAdapter {
|
|
29
|
+
constructor({ port, mode = 'quick', config = {}, tunnelName, tunnelHostname }) {
|
|
30
|
+
super({ port, mode, config })
|
|
31
|
+
// Support both config object keys and legacy top-level constructor args
|
|
32
|
+
this.tunnelName = config.tunnelName ?? tunnelName ?? null
|
|
33
|
+
this.tunnelHostname = config.tunnelHostname ?? tunnelHostname ?? null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
static get name() {
|
|
37
|
+
return 'cloudflare'
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
static get capabilities() {
|
|
41
|
+
return {
|
|
42
|
+
modes: ['quick', 'named'],
|
|
43
|
+
stableUrl: false,
|
|
44
|
+
binaryName: 'cloudflared',
|
|
45
|
+
setupRequired: false,
|
|
46
|
+
installHint: 'brew install cloudflared',
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
static checkBinary() {
|
|
51
|
+
try {
|
|
52
|
+
const output = execFileSync('cloudflared', ['--version'], { encoding: 'utf-8', stdio: 'pipe' })
|
|
53
|
+
const match = output.match(/cloudflared version (\S+)/)
|
|
54
|
+
return {
|
|
55
|
+
available: true,
|
|
56
|
+
version: match ? match[1] : 'unknown',
|
|
57
|
+
hint: null,
|
|
58
|
+
}
|
|
59
|
+
} catch {
|
|
60
|
+
return {
|
|
61
|
+
available: false,
|
|
62
|
+
version: null,
|
|
63
|
+
hint: 'Install with: brew install cloudflared',
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
get hasStableUrl() {
|
|
69
|
+
return this.mode === 'named'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Override point for test injection */
|
|
73
|
+
_spawnCloudflared(argv, spawnOpts) {
|
|
74
|
+
return spawn('cloudflared', argv, spawnOpts)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async _startTunnel() {
|
|
78
|
+
if (this.mode === 'named') {
|
|
79
|
+
return this._startNamedTunnel()
|
|
80
|
+
}
|
|
81
|
+
return this._startQuickTunnel()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Start a Named Tunnel. URL is known from config (no regex parsing needed).
|
|
86
|
+
* Requires: cloudflared login, tunnel created, DNS route configured.
|
|
87
|
+
*/
|
|
88
|
+
async _startNamedTunnel() {
|
|
89
|
+
if (!this.tunnelName) {
|
|
90
|
+
throw new Error('Named tunnel requires tunnelName config. Run: chroxy tunnel setup')
|
|
91
|
+
}
|
|
92
|
+
if (!this.tunnelHostname) {
|
|
93
|
+
throw new Error('Named tunnel requires tunnelHostname config. Run: chroxy tunnel setup')
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return new Promise((resolve, reject) => {
|
|
97
|
+
const argv = [
|
|
98
|
+
'tunnel', 'run',
|
|
99
|
+
'--url', `http://localhost:${this.port}`,
|
|
100
|
+
this.tunnelName,
|
|
101
|
+
]
|
|
102
|
+
const spawnOpts = {
|
|
103
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
104
|
+
}
|
|
105
|
+
const proc = this._spawnCloudflared(argv, spawnOpts)
|
|
106
|
+
|
|
107
|
+
this.process = proc
|
|
108
|
+
let resolved = false
|
|
109
|
+
// Per-attempt cold-start timeout flag. Must NOT reuse the instance-wide
|
|
110
|
+
// `intentionalShutdown` kill switch: a 30s cold-start timeout is exactly
|
|
111
|
+
// the transient failure the `start()` retry loop exists to absorb, but
|
|
112
|
+
// setting `intentionalShutdown` makes that loop give up (base.js:95) AND
|
|
113
|
+
// suppresses every future recovery. Scope the suppression to this one
|
|
114
|
+
// process so the retry budget and post-success recovery both survive.
|
|
115
|
+
let timedOut = false
|
|
116
|
+
|
|
117
|
+
const httpUrl = `https://${this.tunnelHostname}`
|
|
118
|
+
const wsUrl = `wss://${this.tunnelHostname}`
|
|
119
|
+
|
|
120
|
+
// #5328 (WP-5.6): retain a capped tail of cloudflared's startup output.
|
|
121
|
+
// handleOutput otherwise inspects each chunk only for the success pattern
|
|
122
|
+
// and discards it — so a startup failure surfaced only "exited with code
|
|
123
|
+
// N" with no hint of WHY (credentials missing, tunnel not found, DNS
|
|
124
|
+
// route absent). The tail is redacted at EMIT time (in the reject sites),
|
|
125
|
+
// not per-chunk: a token split across two `data` events would survive a
|
|
126
|
+
// per-chunk redact (neither half matches the pattern) and leak a fragment
|
|
127
|
+
// into the error — so we accumulate raw and redact the whole tail once
|
|
128
|
+
// (#5366 review). We stop accumulating after `resolved` so a long-lived,
|
|
129
|
+
// chatty named tunnel doesn't run redaction for its whole lifetime.
|
|
130
|
+
let outputTailRaw = ''
|
|
131
|
+
const handleOutput = (data) => {
|
|
132
|
+
if (resolved) return
|
|
133
|
+
const text = data.toString()
|
|
134
|
+
outputTailRaw = (outputTailRaw + text).slice(-CLOUDFLARED_OUTPUT_TAIL_CAP)
|
|
135
|
+
if (/[Rr]egistered.*connection|[Cc]onnection.*registered|Serving tunnel/i.test(text)) {
|
|
136
|
+
resolved = true
|
|
137
|
+
this.url = httpUrl
|
|
138
|
+
|
|
139
|
+
log.info(`Named tunnel established: HTTP=${httpUrl} WebSocket=${wsUrl}`)
|
|
140
|
+
|
|
141
|
+
resolve({ httpUrl, wsUrl })
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
proc.stdout.on('data', handleOutput)
|
|
146
|
+
proc.stderr.on('data', handleOutput)
|
|
147
|
+
|
|
148
|
+
proc.on('error', (err) => {
|
|
149
|
+
if (!resolved) {
|
|
150
|
+
reject(new Error(`Failed to start cloudflared: ${err.message}. Install with: brew install cloudflared`))
|
|
151
|
+
}
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
proc.on('close', (code, signal) => {
|
|
155
|
+
if (!resolved) {
|
|
156
|
+
const tail = redactedTail(outputTailRaw)
|
|
157
|
+
reject(new Error(`cloudflared exited with code ${code} before establishing tunnel${tail ? `. Last output: ${tail}` : ''}`))
|
|
158
|
+
} else if (!timedOut) {
|
|
159
|
+
// A cold-start timeout already rejected and killed the process; the
|
|
160
|
+
// `start()` retry loop owns the retry decision, so don't treat that
|
|
161
|
+
// kill as a mid-session outage to recover from.
|
|
162
|
+
void this._handleUnexpectedExit(code, signal).catch((err) => {
|
|
163
|
+
log.error(`Error while handling unexpected cloudflared exit: ${err.stack || err.message || err}`)
|
|
164
|
+
})
|
|
165
|
+
}
|
|
166
|
+
this.process = null
|
|
167
|
+
// For named tunnels, keep the URL (it never changes)
|
|
168
|
+
if (this.mode !== 'named') {
|
|
169
|
+
this.url = null
|
|
170
|
+
}
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
const timeoutHandle = setTimeout(() => {
|
|
174
|
+
if (!resolved) {
|
|
175
|
+
resolved = true
|
|
176
|
+
timedOut = true
|
|
177
|
+
proc.kill()
|
|
178
|
+
const tail = redactedTail(outputTailRaw)
|
|
179
|
+
reject(new Error(`Tunnel timed out after 30s. Is cloudflared installed and logged in? (brew install cloudflared)${tail ? `. Last output: ${tail}` : ''}`))
|
|
180
|
+
}
|
|
181
|
+
}, 30_000)
|
|
182
|
+
// Don't let the 30s start-timeout timer pin the event loop on success —
|
|
183
|
+
// it's only cleared on `proc.close`, but a healthy tunnel never closes.
|
|
184
|
+
timeoutHandle.unref?.()
|
|
185
|
+
|
|
186
|
+
proc.once('close', () => {
|
|
187
|
+
clearTimeout(timeoutHandle)
|
|
188
|
+
})
|
|
189
|
+
})
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Start a Quick Tunnel (random URL, no account needed) */
|
|
193
|
+
async _startQuickTunnel() {
|
|
194
|
+
return new Promise((resolve, reject) => {
|
|
195
|
+
const argv = [
|
|
196
|
+
'tunnel', '--url', `http://localhost:${this.port}`, '--no-autoupdate',
|
|
197
|
+
]
|
|
198
|
+
const spawnOpts = {
|
|
199
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
200
|
+
}
|
|
201
|
+
const proc = this._spawnCloudflared(argv, spawnOpts)
|
|
202
|
+
|
|
203
|
+
this.process = proc
|
|
204
|
+
let resolved = false
|
|
205
|
+
// Per-attempt cold-start timeout flag — see _startNamedTunnel for why this
|
|
206
|
+
// must not reuse the instance-wide `intentionalShutdown` kill switch.
|
|
207
|
+
let timedOut = false
|
|
208
|
+
// Retain a redacted output tail so a start failure surfaces WHY (the most
|
|
209
|
+
// common failure mode), matching the named path (#5328/#5366). Accumulate
|
|
210
|
+
// raw + redact the whole tail once at emit time; stop after `resolved`.
|
|
211
|
+
let outputTailRaw = ''
|
|
212
|
+
|
|
213
|
+
const handleOutput = (data) => {
|
|
214
|
+
const text = data.toString()
|
|
215
|
+
if (!resolved) {
|
|
216
|
+
outputTailRaw = (outputTailRaw + text).slice(-CLOUDFLARED_OUTPUT_TAIL_CAP)
|
|
217
|
+
}
|
|
218
|
+
const match = text.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/)
|
|
219
|
+
if (match && !resolved) {
|
|
220
|
+
resolved = true
|
|
221
|
+
this.url = match[0]
|
|
222
|
+
const wsUrl = this.url.replace('https://', 'wss://')
|
|
223
|
+
|
|
224
|
+
log.info(`Cloudflare tunnel established: HTTP=${this.url} WebSocket=${wsUrl}`)
|
|
225
|
+
// #5356 (visibility layer): a quick tunnel publishes the server on a
|
|
226
|
+
// public trycloudflare.com URL. Every endpoint stays bearer-token
|
|
227
|
+
// gated, but anyone who learns the URL can fingerprint the server
|
|
228
|
+
// via /health and attempt auth/pairing — make that visible once.
|
|
229
|
+
log.warn(
|
|
230
|
+
`Quick tunnel is publicly reachable at ${this.url} — endpoints are bearer-token gated, ` +
|
|
231
|
+
'but anyone with this URL can fingerprint the server via /health and attempt auth. ' +
|
|
232
|
+
'Use --tunnel none to disable remote access, or --tunnel named for a stable domain you control.'
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
resolve({ httpUrl: this.url, wsUrl })
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
proc.stdout.on('data', handleOutput)
|
|
240
|
+
proc.stderr.on('data', handleOutput)
|
|
241
|
+
|
|
242
|
+
proc.on('error', (err) => {
|
|
243
|
+
if (!resolved) {
|
|
244
|
+
reject(new Error(`Failed to start cloudflared: ${err.message}. Install with: brew install cloudflared`))
|
|
245
|
+
}
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
proc.on('close', (code, signal) => {
|
|
249
|
+
if (!resolved) {
|
|
250
|
+
const tail = redactedTail(outputTailRaw)
|
|
251
|
+
reject(new Error(`cloudflared exited with code ${code} before establishing tunnel${tail ? `. Last output: ${tail}` : ''}`))
|
|
252
|
+
} else if (!timedOut) {
|
|
253
|
+
// A cold-start timeout already rejected and killed the process; the
|
|
254
|
+
// `start()` retry loop owns the retry decision, so don't treat that
|
|
255
|
+
// kill as a mid-session outage to recover from.
|
|
256
|
+
void this._handleUnexpectedExit(code, signal).catch((err) => {
|
|
257
|
+
log.error(`Error while handling unexpected cloudflared exit: ${err.stack || err.message || err}`)
|
|
258
|
+
})
|
|
259
|
+
}
|
|
260
|
+
this.process = null
|
|
261
|
+
this.url = null
|
|
262
|
+
})
|
|
263
|
+
|
|
264
|
+
const timeoutHandle = setTimeout(() => {
|
|
265
|
+
if (!resolved) {
|
|
266
|
+
resolved = true
|
|
267
|
+
timedOut = true
|
|
268
|
+
proc.kill()
|
|
269
|
+
const tail = redactedTail(outputTailRaw)
|
|
270
|
+
reject(new Error(`Tunnel timed out after 30s. Is cloudflared installed? (brew install cloudflared)${tail ? `. Last output: ${tail}` : ''}`))
|
|
271
|
+
}
|
|
272
|
+
}, 30_000)
|
|
273
|
+
// Don't let the 30s start-timeout timer pin the event loop on success.
|
|
274
|
+
timeoutHandle.unref?.()
|
|
275
|
+
|
|
276
|
+
proc.once('close', () => {
|
|
277
|
+
clearTimeout(timeoutHandle)
|
|
278
|
+
})
|
|
279
|
+
})
|
|
280
|
+
}
|
|
281
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { CloudflareTunnelAdapter } from './cloudflare.js'
|
|
2
|
+
|
|
3
|
+
export { BaseTunnelAdapter } from './base.js'
|
|
4
|
+
export { CloudflareTunnelAdapter } from './cloudflare.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Parse a --tunnel flag value into { mode } or null (for 'none').
|
|
8
|
+
*
|
|
9
|
+
* Accepted values:
|
|
10
|
+
* 'quick' → { mode: 'quick' }
|
|
11
|
+
* 'named' → { mode: 'named' }
|
|
12
|
+
* 'cloudflare' → { mode: 'quick' }
|
|
13
|
+
* 'cloudflare:quick' → { mode: 'quick' }
|
|
14
|
+
* 'cloudflare:named' → { mode: 'named' }
|
|
15
|
+
* 'none' / '' → null
|
|
16
|
+
*
|
|
17
|
+
* @param {string} value - Raw --tunnel flag value
|
|
18
|
+
* @returns {{ mode: string } | null}
|
|
19
|
+
*/
|
|
20
|
+
export function parseTunnelArg(value) {
|
|
21
|
+
if (!value || value === 'none') return null
|
|
22
|
+
|
|
23
|
+
if (value === 'quick') return { mode: 'quick' }
|
|
24
|
+
if (value === 'named') return { mode: 'named' }
|
|
25
|
+
if (value === 'cloudflare') return { mode: 'quick' }
|
|
26
|
+
|
|
27
|
+
if (value.startsWith('cloudflare:')) {
|
|
28
|
+
const mode = value.slice('cloudflare:'.length)
|
|
29
|
+
if (!mode) {
|
|
30
|
+
throw new Error(`Invalid tunnel format "${value}". Expected "cloudflare:quick" or "cloudflare:named"`)
|
|
31
|
+
}
|
|
32
|
+
return { mode }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
throw new Error(`Unknown tunnel value "${value}". Use: quick, named, cloudflare, cloudflare:quick, cloudflare:named, or none`)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Create a CloudflareTunnelAdapter instance from a config object.
|
|
40
|
+
*
|
|
41
|
+
* @param {{ port: number, mode: string, tunnelConfig?: object, tunnelName?: string, tunnelHostname?: string }} config
|
|
42
|
+
* @returns {CloudflareTunnelAdapter}
|
|
43
|
+
*/
|
|
44
|
+
export function createTunnel(config) {
|
|
45
|
+
return new CloudflareTunnelAdapter({
|
|
46
|
+
port: config.port,
|
|
47
|
+
mode: config.mode,
|
|
48
|
+
config: {
|
|
49
|
+
...config.tunnelConfig,
|
|
50
|
+
tunnelName: config.tunnelName || null,
|
|
51
|
+
tunnelHostname: config.tunnelHostname || null,
|
|
52
|
+
},
|
|
53
|
+
})
|
|
54
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { createLogger } from './logger.js'
|
|
2
|
+
|
|
3
|
+
const log = createLogger('tunnel')
|
|
4
|
+
|
|
5
|
+
export const QUICK_TUNNEL_DNS_SETTLE_MS = 20_000
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* #5489 — cloudflared returns these statuses when the edge reached the tunnel
|
|
9
|
+
* but the origin (localhost server) is unreachable. The supervisor verifies the
|
|
10
|
+
* tunnel BEFORE forking the server child (#5314 no-orphan ordering), so the
|
|
11
|
+
* origin is intentionally down at verification time. Since this check only
|
|
12
|
+
* confirms routability (the edge resolved and proxied — i.e. DNS has settled),
|
|
13
|
+
* a 502/530 is proof of success, not a failure.
|
|
14
|
+
* 502 Bad Gateway — origin connection refused / reset
|
|
15
|
+
* 530 (Cloudflare) — origin unreachable / DNS error at the edge
|
|
16
|
+
*/
|
|
17
|
+
const ROUTABLE_ORIGIN_DOWN_STATUSES = new Set([502, 530])
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Verify a Cloudflare tunnel is fully routable before exposing it to users.
|
|
21
|
+
* New tunnel URLs need time for DNS propagation — Quick Tunnels can take
|
|
22
|
+
* 30+ seconds. Uses an optional initial delay, then linear backoff:
|
|
23
|
+
* 1s, 2s, 3s, 4s, 5s (cap), ...
|
|
24
|
+
*/
|
|
25
|
+
export async function waitForTunnel(httpUrl, { maxAttempts = 20, initialInterval = 1000, initialDelay = 0, onAttempt } = {}) {
|
|
26
|
+
log.info('Verifying tunnel is routable...')
|
|
27
|
+
const startTime = Date.now()
|
|
28
|
+
|
|
29
|
+
if (initialDelay > 0) {
|
|
30
|
+
log.info(`Waiting ${(initialDelay / 1000).toFixed(0)}s before first tunnel verification attempt...`)
|
|
31
|
+
await new Promise((r) => setTimeout(r, initialDelay))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let lastFailure = null
|
|
35
|
+
|
|
36
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
37
|
+
const attempt = i + 1
|
|
38
|
+
if (typeof onAttempt === 'function') onAttempt(attempt, maxAttempts)
|
|
39
|
+
const controller = new AbortController()
|
|
40
|
+
const timeout = setTimeout(() => controller.abort(), 5000)
|
|
41
|
+
try {
|
|
42
|
+
const res = await fetch(httpUrl, { signal: controller.signal })
|
|
43
|
+
// A successful response OR an "edge reached, origin down" response (#5489)
|
|
44
|
+
// both prove the tunnel is routable — that's all this check verifies.
|
|
45
|
+
if (res.ok || ROUTABLE_ORIGIN_DOWN_STATUSES.has(res.status)) {
|
|
46
|
+
const detail = res.ok ? '' : ` (HTTP ${res.status} — edge routable, origin not yet up)`
|
|
47
|
+
log.info(`Tunnel verified on attempt ${attempt}/${maxAttempts} (took ${((Date.now() - startTime) / 1000).toFixed(1)}s)${detail}`)
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
log.info(`Attempt ${attempt}/${maxAttempts} failed: HTTP ${res.status}`)
|
|
51
|
+
lastFailure = `HTTP ${res.status}`
|
|
52
|
+
} catch (err) {
|
|
53
|
+
const reason = err.name === 'AbortError'
|
|
54
|
+
? 'timeout'
|
|
55
|
+
: [err.cause?.code, err.message].filter(Boolean).join(': ')
|
|
56
|
+
lastFailure = reason
|
|
57
|
+
// Only log every few attempts to reduce noise
|
|
58
|
+
if (attempt <= 3 || attempt % 5 === 0 || attempt === maxAttempts) {
|
|
59
|
+
log.info(`Attempt ${attempt}/${maxAttempts} failed: ${reason}`)
|
|
60
|
+
}
|
|
61
|
+
} finally {
|
|
62
|
+
clearTimeout(timeout)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (i < maxAttempts - 1) {
|
|
66
|
+
// Backoff: 1s, 2s, 3s, 4s, 5s, 5s, 5s, ...
|
|
67
|
+
const delay = Math.min(initialInterval * (i + 1), 5000)
|
|
68
|
+
await new Promise((r) => setTimeout(r, delay))
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// UX landmine #4: throw instead of silently proceeding. A broken
|
|
73
|
+
// tunnel produces a QR that hangs the app — better to surface the
|
|
74
|
+
// error clearly than show a non-functional QR code.
|
|
75
|
+
const elapsed = ((Date.now() - startTime) / 1000).toFixed(0)
|
|
76
|
+
const err = new Error(
|
|
77
|
+
`Tunnel failed to become routable after ${maxAttempts} attempts (${elapsed}s). ` +
|
|
78
|
+
`${lastFailure ? `Last failure: ${lastFailure}. ` : ''}` +
|
|
79
|
+
'This usually means your network is blocking Cloudflare, or DNS has not propagated yet. ' +
|
|
80
|
+
'Try a named tunnel (--tunnel named) or run `npx chroxy doctor` for diagnostics.'
|
|
81
|
+
)
|
|
82
|
+
err.code = 'TUNNEL_NOT_ROUTABLE'
|
|
83
|
+
throw err
|
|
84
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* user-shell-registry.js (#6276, epic #5982) — a durable sidecar that records
|
|
3
|
+
* the OS pid of each live embedded user-shell so a boot-time reaper can clean up
|
|
4
|
+
* shells orphaned by an ungraceful daemon death.
|
|
5
|
+
*
|
|
6
|
+
* Why this exists: a user-shell is a raw `$SHELL` PTY (host RCE over the tunnel).
|
|
7
|
+
* UserShellSessions are deliberately NEVER persisted across a daemon restart
|
|
8
|
+
* (session-manager.js — restoring one would re-spawn a shell and bypass the
|
|
9
|
+
* `userShell.enabled` gate). So on a CLEAN shutdown the shells are SIGTERM'd by
|
|
10
|
+
* destroySession and nothing leaks. But on a SIGKILL / crash the daemon dies
|
|
11
|
+
* without running teardown, and its node-pty shell children are reparented to
|
|
12
|
+
* init — a leaked process with NO `user_shell_destroy` audit entry (the gap this
|
|
13
|
+
* closes, swarm-audit 2026-06-22 Guardian/Planner).
|
|
14
|
+
*
|
|
15
|
+
* The sidecar mirrors the live set: a record is added when a shell spawns and
|
|
16
|
+
* removed on clean destroy, so after a graceful shutdown the file is empty/absent
|
|
17
|
+
* and the boot reaper is a no-op. After an ungraceful death the file retains the
|
|
18
|
+
* last-known shells, which the reaper then reconciles.
|
|
19
|
+
*
|
|
20
|
+
* PID-reuse safety (#6276 + #6327): the reaper only signals a recorded pid that
|
|
21
|
+
* is still alive, whose process-command basename still matches the recorded
|
|
22
|
+
* shell (`ps -p <pid> -o comm=`), AND whose OS process start-time (`ps -o
|
|
23
|
+
* lstart=`, captured at record) is unchanged. comm proves "same program"; the
|
|
24
|
+
* start-time proves "same process incarnation" — a recycled pid (the orphan
|
|
25
|
+
* exited and the OS reused its pid onto a fresh same-binary shell) has a strictly
|
|
26
|
+
* later lstart, so the equality check closes that same-binary reuse window
|
|
27
|
+
* deterministically. A record with no captured start-time (ps unavailable at
|
|
28
|
+
* spawn, or a legacy record) falls back to the comm-only gate; a record WITH a
|
|
29
|
+
* start-time that can't be re-read at reap is skipped (we don't signal a pid we
|
|
30
|
+
* can't positively identify).
|
|
31
|
+
*
|
|
32
|
+
* Note: `lstart` is wall-clock LOCAL time, so if the host timezone / `LC_TIME`
|
|
33
|
+
* changes between the daemon incarnation that recorded the shell and the one that
|
|
34
|
+
* reaps it, the same process can format two different `lstart` strings. That
|
|
35
|
+
* makes the equality check fail-SAFE: it skips (leaks) a real orphan rather than
|
|
36
|
+
* ever wrong-killing — the never-signal-an-innocent-pid invariant holds
|
|
37
|
+
* unconditionally; only reap completeness degrades in that rare case.
|
|
38
|
+
*
|
|
39
|
+
* All I/O is best-effort and the seams (`isAlive`/`commOf`/`kill`/`startTimeOf`)
|
|
40
|
+
* are injectable
|
|
41
|
+
* so the kill path is unit-testable without spawning or signalling a real
|
|
42
|
+
* process, and so tests point the sidecar at a temp path (never the real
|
|
43
|
+
* ~/.chroxy — the test sandbox guard, #4633).
|
|
44
|
+
*/
|
|
45
|
+
import { readFileSync, writeFileSync, renameSync, existsSync, unlinkSync } from 'fs'
|
|
46
|
+
import { execFileSync } from 'child_process'
|
|
47
|
+
import { basename } from 'path'
|
|
48
|
+
import { createLogger } from './logger.js'
|
|
49
|
+
|
|
50
|
+
const log = createLogger('user-shell-registry')
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Read the sidecar. Tolerates a missing or corrupt file (returns `[]`) — a
|
|
54
|
+
* malformed sidecar must never crash boot or a shell spawn.
|
|
55
|
+
* @returns {Array<{sessionId: string, pid: number, shell: string|null}>}
|
|
56
|
+
*/
|
|
57
|
+
export function readRegistry(path) {
|
|
58
|
+
try {
|
|
59
|
+
if (!existsSync(path)) return []
|
|
60
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'))
|
|
61
|
+
if (!Array.isArray(parsed)) return []
|
|
62
|
+
return parsed.filter((r) => r && typeof r.sessionId === 'string' && Number.isInteger(r.pid) && r.pid > 0)
|
|
63
|
+
} catch {
|
|
64
|
+
return []
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function writeRegistry(path, records) {
|
|
69
|
+
// Atomic replace (tmp + rename) at 0600 — the file names host pids tied to a
|
|
70
|
+
// privileged capability; match the session-state secrecy posture.
|
|
71
|
+
const tmp = `${path}.tmp`
|
|
72
|
+
writeFileSync(tmp, JSON.stringify(records), { mode: 0o600 })
|
|
73
|
+
renameSync(tmp, path)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Record a freshly-spawned user-shell's pid. Replaces any prior record for the
|
|
78
|
+
* same sessionId (idempotent on respawn). Best-effort — a write failure is
|
|
79
|
+
* logged, never thrown (it must not fail the shell spawn).
|
|
80
|
+
*/
|
|
81
|
+
export function recordShell(path, { sessionId, pid, shell } = {}, { startTimeOf = defaultStartTimeOf } = {}) {
|
|
82
|
+
if (typeof sessionId !== 'string' || !Number.isInteger(pid) || pid <= 0) return
|
|
83
|
+
try {
|
|
84
|
+
// #6327: capture the OS process start-time so the boot reaper can prove
|
|
85
|
+
// "same process incarnation", not just "same shell binary" — a recycled pid
|
|
86
|
+
// reports a strictly later lstart, which closes the same-binary reuse window.
|
|
87
|
+
const startTime = startTimeOf(pid) || null
|
|
88
|
+
const record = { sessionId, pid, shell: shell ? basename(shell) : null }
|
|
89
|
+
// Only persist a start-time when we actually captured one — a null key would
|
|
90
|
+
// be noise, and its absence is the documented "fall back to comm-only" signal.
|
|
91
|
+
if (startTime) record.startTime = startTime
|
|
92
|
+
const records = readRegistry(path).filter((r) => r.sessionId !== sessionId)
|
|
93
|
+
records.push(record)
|
|
94
|
+
writeRegistry(path, records)
|
|
95
|
+
} catch (err) {
|
|
96
|
+
log.warn(`failed to record user-shell ${sessionId} (non-fatal): ${err?.message || err}`)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Drop a user-shell's record on clean destroy. Deletes the file once empty so a
|
|
102
|
+
* graceful shutdown leaves no sidecar for the next boot to scan.
|
|
103
|
+
*/
|
|
104
|
+
export function forgetShell(path, sessionId) {
|
|
105
|
+
try {
|
|
106
|
+
const records = readRegistry(path)
|
|
107
|
+
if (!records.some((r) => r.sessionId === sessionId)) return
|
|
108
|
+
const next = records.filter((r) => r.sessionId !== sessionId)
|
|
109
|
+
if (next.length === 0) {
|
|
110
|
+
if (existsSync(path)) unlinkSync(path)
|
|
111
|
+
} else {
|
|
112
|
+
writeRegistry(path, next)
|
|
113
|
+
}
|
|
114
|
+
} catch (err) {
|
|
115
|
+
log.warn(`failed to forget user-shell ${sessionId} (non-fatal): ${err?.message || err}`)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Default seams — overridden in tests so the kill path is exercised without
|
|
120
|
+
// signalling a real process.
|
|
121
|
+
function defaultIsAlive(pid) {
|
|
122
|
+
try {
|
|
123
|
+
process.kill(pid, 0)
|
|
124
|
+
return true
|
|
125
|
+
} catch (err) {
|
|
126
|
+
// ESRCH = no such process (dead). EPERM = alive but not signallable by us.
|
|
127
|
+
return err?.code === 'EPERM'
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function defaultCommOf(pid) {
|
|
132
|
+
try {
|
|
133
|
+
return execFileSync('ps', ['-p', String(pid), '-o', 'comm='], { encoding: 'utf8' }).trim() || null
|
|
134
|
+
} catch {
|
|
135
|
+
return null
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// The process start wall-clock (`lstart`) is fixed for a process's lifetime and
|
|
140
|
+
// differs for a recycled pid's new occupant — so a verbatim string match is a
|
|
141
|
+
// sound "same incarnation" check. Available on both macOS and Linux `ps`.
|
|
142
|
+
function defaultStartTimeOf(pid) {
|
|
143
|
+
try {
|
|
144
|
+
return execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], { encoding: 'utf8' }).trim() || null
|
|
145
|
+
} catch {
|
|
146
|
+
return null
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function defaultKill(pid) {
|
|
151
|
+
try {
|
|
152
|
+
process.kill(pid, 'SIGTERM')
|
|
153
|
+
return true
|
|
154
|
+
} catch {
|
|
155
|
+
return false
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Boot-time reap: for each recorded shell, SIGTERM it iff it is still alive AND
|
|
161
|
+
* its process-command basename matches the recorded shell (the PID-reuse safety
|
|
162
|
+
* gate). The sidecar is cleared afterwards regardless — this daemon instance
|
|
163
|
+
* starts fresh and live shells re-record on spawn.
|
|
164
|
+
*
|
|
165
|
+
* @returns {{ reaped: Array, skipped: Array }} reaped = signalled orphans (the
|
|
166
|
+
* caller emits a destroy-audit entry per item); skipped carries a `why` so the
|
|
167
|
+
* reason a record was left alone (dead / comm-mismatch / comm-unknown /
|
|
168
|
+
* starttime-unknown / starttime-mismatch / kill-failed) is observable.
|
|
169
|
+
*/
|
|
170
|
+
export function reapOrphanShells(path, { isAlive = defaultIsAlive, commOf = defaultCommOf, startTimeOf = defaultStartTimeOf, kill = defaultKill } = {}) {
|
|
171
|
+
const records = readRegistry(path)
|
|
172
|
+
const reaped = []
|
|
173
|
+
const skipped = []
|
|
174
|
+
for (const r of records) {
|
|
175
|
+
if (!isAlive(r.pid)) {
|
|
176
|
+
skipped.push({ ...r, why: 'dead' })
|
|
177
|
+
continue
|
|
178
|
+
}
|
|
179
|
+
// PID-reuse safety: never signal a live pid we can't positively identify as
|
|
180
|
+
// the same shell binary we recorded.
|
|
181
|
+
if (r.shell) {
|
|
182
|
+
const comm = commOf(r.pid)
|
|
183
|
+
const commBase = comm ? basename(comm) : null
|
|
184
|
+
if (!commBase) {
|
|
185
|
+
skipped.push({ ...r, why: 'comm-unknown' })
|
|
186
|
+
continue
|
|
187
|
+
}
|
|
188
|
+
if (commBase !== r.shell) {
|
|
189
|
+
skipped.push({ ...r, why: 'comm-mismatch', comm: commBase })
|
|
190
|
+
continue
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
// #6327: start-time identity gate — closes the same-binary pid-reuse window
|
|
194
|
+
// comm can't (orphan exits → pid recycled onto a fresh same-binary shell).
|
|
195
|
+
// When we captured an lstart, the live process must still report the SAME
|
|
196
|
+
// lstart; a recycled pid's occupant started later → different lstart → skip.
|
|
197
|
+
// A record with no captured start-time falls back to the comm-only gate.
|
|
198
|
+
if (r.startTime) {
|
|
199
|
+
const liveStart = startTimeOf(r.pid)
|
|
200
|
+
if (!liveStart) {
|
|
201
|
+
skipped.push({ ...r, why: 'starttime-unknown' })
|
|
202
|
+
continue
|
|
203
|
+
}
|
|
204
|
+
if (liveStart !== r.startTime) {
|
|
205
|
+
skipped.push({ ...r, why: 'starttime-mismatch' })
|
|
206
|
+
continue
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (kill(r.pid)) reaped.push(r)
|
|
210
|
+
else skipped.push({ ...r, why: 'kill-failed' })
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
if (existsSync(path)) unlinkSync(path)
|
|
214
|
+
} catch {
|
|
215
|
+
/* best-effort — a leftover sidecar is reconciled on the next boot */
|
|
216
|
+
}
|
|
217
|
+
return { reaped, skipped }
|
|
218
|
+
}
|