@chroxy/server 0.10.0 → 0.11.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.
Files changed (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -29,9 +29,12 @@
29
29
  * cannot meaningfully check it.
30
30
  */
31
31
 
32
- import { existsSync, accessSync, constants } from 'fs'
33
- import { isAbsolute } from 'path'
34
32
  import { resolveBinary } from './resolve-binary.js'
33
+ import { verifyBinary as defaultVerifyBinary, BINARY_STATUS, describeBinaryHealth } from './verify-binary.js'
34
+ import { verifyProvenance as defaultVerifyProvenance, PROVENANCE_STATUS } from './verify-provenance.js'
35
+ import { createLogger } from '../logger.js'
36
+
37
+ const log = createLogger('preflight')
35
38
 
36
39
  /**
37
40
  * Thrown when a provider's required binary cannot be located or executed.
@@ -52,6 +55,51 @@ export class ProviderBinaryNotFoundError extends Error {
52
55
  }
53
56
  }
54
57
 
58
+ /**
59
+ * Thrown when a provider's binary is present but blocked by macOS Gatekeeper
60
+ * (a `com.apple.quarantine` xattr whose assessment-OK bit is clear). Distinct
61
+ * from ProviderBinaryNotFoundError so the client / doctor can render a
62
+ * quarantine-specific remediation (`xattr -d …`) rather than "install …". (#6708)
63
+ */
64
+ export class ProviderBinaryQuarantinedError extends Error {
65
+ constructor({ provider, binary, path, quarantine, installHint }) {
66
+ const { message } = describeBinaryHealth(
67
+ { status: BINARY_STATUS.QUARANTINED, path },
68
+ { binary, installHint },
69
+ )
70
+ super(`${provider}: ${message}`)
71
+ this.name = 'ProviderBinaryQuarantinedError'
72
+ this.code = 'PROVIDER_BINARY_QUARANTINED'
73
+ this.provider = provider
74
+ this.binary = binary
75
+ this.path = path
76
+ this.quarantine = quarantine || null
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Thrown when the opt-in provenance gate (#6858) blocks a spawn: either the
82
+ * binary's pinned SHA-256 changed in place (`binaryProvenance.mode: 'block'`) or
83
+ * it failed the macOS signature/notarization gate. Distinct code so the client /
84
+ * doctor can render a provenance-specific remediation. Never thrown when the
85
+ * gate is off (the default) — behaviour is then identical to #6708.
86
+ */
87
+ export class ProviderBinaryProvenanceError extends Error {
88
+ constructor({ provider, binary, path, status, message, remediation, pinnedHash, hash }) {
89
+ const detail = message || 'binary failed provenance verification'
90
+ super(`${provider}: "${binary}" at ${path} ${detail}${remediation ? ` — ${remediation}` : ''}`)
91
+ this.name = 'ProviderBinaryProvenanceError'
92
+ this.code = 'PROVIDER_BINARY_PROVENANCE'
93
+ this.provider = provider
94
+ this.binary = binary
95
+ this.path = path
96
+ this.provenanceStatus = status
97
+ this.remediation = remediation || null
98
+ this.pinnedHash = pinnedHash || null
99
+ this.hash = hash || null
100
+ }
101
+ }
102
+
55
103
  /**
56
104
  * Thrown when none of a provider's required credential env vars are present.
57
105
  */
@@ -68,38 +116,47 @@ export class ProviderCredentialMissingError extends Error {
68
116
  }
69
117
  }
70
118
 
71
- /**
72
- * Verify a binary path exists and is executable by the current process.
73
- * Returns true if the resolved path is absolute, exists, and the X bit is set.
74
- *
75
- * @param {string} resolvedPath
76
- * @returns {boolean}
77
- */
78
- function isExecutableFile(resolvedPath) {
79
- if (!isAbsolute(resolvedPath)) return false
80
- if (!existsSync(resolvedPath)) return false
81
- try {
82
- accessSync(resolvedPath, constants.X_OK)
83
- return true
84
- } catch {
85
- return false
86
- }
87
- }
88
-
89
119
  /**
90
120
  * Run binary + credential preflight for a provider class.
91
121
  *
92
- * Throws ProviderBinaryNotFoundError or ProviderCredentialMissingError if
93
- * the spec's requirements aren't met. No-op when:
122
+ * Throws ProviderBinaryNotFoundError, ProviderBinaryQuarantinedError, or
123
+ * ProviderCredentialMissingError if the spec's requirements aren't met. No-op
124
+ * when:
94
125
  * - The provider doesn't declare a `static get preflight()`
95
126
  * - The provider is containerised (binary lives inside the container)
96
127
  *
128
+ * The binary is re-resolved fresh here (per session-create), not read off a
129
+ * frozen module-load path, so a binary quarantined/moved AFTER daemon start is
130
+ * caught before spawn. When the provider exposes its real spawn path via
131
+ * `static get resolvedBinary`, we verify THAT exact path so preflight and the
132
+ * eventual spawn can't diverge (#6708 defect #3).
133
+ *
134
+ * ## Opt-in provenance gate (#6858)
135
+ *
136
+ * When `provenance` is supplied AND enabled (`mode` is 'warn'/'block', or the
137
+ * signature gate is on), a healthy binary is additionally run through
138
+ * `verifyProvenance`: a SHA-256 pin-ledger check plus (opt-in) a macOS signature
139
+ * gate. A `block`-mode hash mismatch or a failed signature gate throws
140
+ * `ProviderBinaryProvenanceError` — fail-safe: the spawn is refused, never
141
+ * silently allowed. A `warn`-mode issue logs and proceeds. When `provenance` is
142
+ * absent or disabled (the default), this step is skipped entirely and behaviour
143
+ * is identical to #6708.
144
+ *
97
145
  * @param {Function} ProviderClass - Session class with optional `preflight` getter
98
146
  * @param {object} [options]
99
147
  * @param {NodeJS.ProcessEnv} [options.env=process.env] - Env source (for tests)
100
- * @throws {ProviderBinaryNotFoundError|ProviderCredentialMissingError}
148
+ * @param {Function} [options.verifyBinary] - integrity checker (injected in tests)
149
+ * @param {{ mode?: string, signatureGate?: boolean, ledger?: object }|null} [options.provenance]
150
+ * - opt-in provenance config + pin ledger; null/disabled ⇒ gate skipped
151
+ * @param {Function} [options.verifyProvenance] - provenance checker (injected in tests)
152
+ * @throws {ProviderBinaryNotFoundError|ProviderBinaryQuarantinedError|ProviderBinaryProvenanceError|ProviderCredentialMissingError}
101
153
  */
102
- export function runProviderPreflight(ProviderClass, { env = process.env } = {}) {
154
+ export function runProviderPreflight(ProviderClass, {
155
+ env = process.env,
156
+ verifyBinary = defaultVerifyBinary,
157
+ provenance = null,
158
+ verifyProvenance = defaultVerifyProvenance,
159
+ } = {}) {
103
160
  if (!ProviderClass) return
104
161
 
105
162
  // Containerised providers run their binary inside the container, so a host
@@ -114,10 +171,30 @@ export function runProviderPreflight(ProviderClass, { env = process.env } = {})
114
171
 
115
172
  if (spec.binary && spec.binary.name) {
116
173
  const candidates = spec.binary.candidates || []
117
- const resolved = resolveBinary(spec.binary.name, candidates)
118
- // resolveBinary returns the bare name when nothing on PATH or in
119
- // candidates matched — that's the failure signal.
120
- if (!isExecutableFile(resolved)) {
174
+ // Prefer the provider's live spawn path when it exposes one — that is the
175
+ // exact path child_process.spawn will exec — so the existence gate and the
176
+ // real spawn always agree. Fall back to a fresh PATH/candidate resolve.
177
+ let resolved
178
+ try {
179
+ resolved = ProviderClass.resolvedBinary
180
+ } catch { /* subclass throws if unset — fall through */ }
181
+ if (typeof resolved !== 'string' || resolved.length === 0) {
182
+ resolved = resolveBinary(spec.binary.name, candidates)
183
+ }
184
+ const health = verifyBinary(resolved)
185
+ if (health.status === BINARY_STATUS.QUARANTINED) {
186
+ throw new ProviderBinaryQuarantinedError({
187
+ provider: providerLabel,
188
+ binary: spec.binary.name,
189
+ path: health.path,
190
+ quarantine: health.quarantine,
191
+ installHint: spec.binary.installHint,
192
+ })
193
+ }
194
+ // NOT_FOUND / NOT_EXECUTABLE both mean "can't spawn it" — resolveBinary
195
+ // returns the bare name when nothing matched, which verifyBinary reports as
196
+ // NOT_FOUND.
197
+ if (!health.ok) {
121
198
  throw new ProviderBinaryNotFoundError({
122
199
  provider: providerLabel,
123
200
  binary: spec.binary.name,
@@ -125,6 +202,41 @@ export function runProviderPreflight(ProviderClass, { env = process.env } = {})
125
202
  installHint: spec.binary.installHint,
126
203
  })
127
204
  }
205
+
206
+ // #6858: opt-in provenance gate on the SAME healthy path the spawn will use.
207
+ // Skipped entirely unless the operator opted in (mode warn/block or the
208
+ // signature gate). Fail-safe: a `block`-mode hash mismatch or a failed
209
+ // signature gate throws; a `warn`-mode issue logs and proceeds.
210
+ const provenanceOn = provenance
211
+ && (provenance.mode === 'warn' || provenance.mode === 'block' || provenance.signatureGate === true)
212
+ if (provenanceOn) {
213
+ const verdict = verifyProvenance({
214
+ resolvedPath: health.path,
215
+ mode: provenance.mode,
216
+ signatureGate: provenance.signatureGate === true,
217
+ ledger: provenance.ledger || null,
218
+ })
219
+ if (verdict.blocked) {
220
+ throw new ProviderBinaryProvenanceError({
221
+ provider: providerLabel,
222
+ binary: spec.binary.name,
223
+ path: verdict.path,
224
+ status: verdict.status,
225
+ message: verdict.message,
226
+ remediation: verdict.remediation,
227
+ pinnedHash: verdict.pinnedHash,
228
+ hash: verdict.hash,
229
+ })
230
+ }
231
+ if (
232
+ verdict.status === PROVENANCE_STATUS.HASH_MISMATCH
233
+ || verdict.status === PROVENANCE_STATUS.SIGNATURE_INVALID
234
+ || verdict.status === PROVENANCE_STATUS.UNREADABLE
235
+ ) {
236
+ // warn-mode (or unverifiable-but-allowed) — surface loudly, still spawn.
237
+ log.warn(`Provider "${spec.binary.name}" provenance ${verdict.status}: ${verdict.message || ''} (allowed — mode=${provenance.mode})`)
238
+ }
239
+ }
128
240
  }
129
241
 
130
242
  if (spec.credentials && Array.isArray(spec.credentials.envVars) && spec.credentials.envVars.length > 0) {
@@ -24,6 +24,7 @@
24
24
  * non-denylisted credential keys are eligible for store injection.
25
25
  */
26
26
  import { resolveCredential, isKnownCredentialKey } from '../credential-store.js'
27
+ import { getChroxyHostEnv } from '../chroxy-host-metadata.js'
27
28
 
28
29
  // Standard vars every child process needs for its runtime to function.
29
30
  // Shell PATH, locale, TERM, TMPDIR, user/home identity.
@@ -163,7 +164,11 @@ export function buildSpawnEnv(provider, extras = {}) {
163
164
  if (resolved.value) env[key] = resolved.value
164
165
  }
165
166
  }
166
- return { ...env, ...extras }
167
+ // #6633: inject Chroxy's own host identity (version/channel/git/platform).
168
+ // These are COMPUTED (not passed through from process.env), so they are
169
+ // authoritative and safe for allowlist-mode providers — non-sensitive
170
+ // metadata, never an operator secret. `extras` still wins on any collision.
171
+ return { ...env, ...getChroxyHostEnv(), ...extras }
167
172
  }
168
173
 
169
174
  // denylist mode: start from full parent env, remove sensitive keys.
@@ -189,5 +194,6 @@ export function buildSpawnEnv(provider, extras = {}) {
189
194
  const resolved = resolveCredential(key)
190
195
  if (resolved.value) parentEnv[key] = resolved.value
191
196
  }
192
- return { ...parentEnv, ...extras }
197
+ // #6633: Chroxy host identity, computed and authoritative (see allowlist branch).
198
+ return { ...parentEnv, ...getChroxyHostEnv(), ...extras }
193
199
  }
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Pre-spawn binary integrity + quarantine verification (#6708).
3
+ *
4
+ * Chroxy execs external provider binaries (`claude`, `codex`, `gemini`,
5
+ * `cloudflared`) resolved off PATH. Before this module the only gate was
6
+ * "exists + X-bit" (see the old `isExecutableFile` in preflight.js), which
7
+ * green-lights a binary that macOS Gatekeeper will refuse to launch: a
8
+ * quarantined binary keeps its execute bit and only fails at `exec()`, so the
9
+ * failure surfaced later as a confusing mid-turn error instead of a clean,
10
+ * actionable preflight rejection.
11
+ *
12
+ * `verifyBinary()` classifies a resolved path into one of {@link BINARY_STATUS}
13
+ * and (on macOS) detects a **blocking `com.apple.quarantine` xattr** so the
14
+ * caller can distinguish "quarantined/blocked by Gatekeeper" from "not
15
+ * installed". The mac-specific probe is cleanly skipped on Linux/Windows —
16
+ * there the check is exactly the existence + executable check it always was.
17
+ *
18
+ * ## Why the assessment-OK flag matters (no false positives)
19
+ *
20
+ * The `com.apple.quarantine` xattr value is `flags;timestamp;agent;uuid`. The
21
+ * low bits of the first (hex) field encode quarantine state; bit `0x0040`
22
+ * (`QTN_FLAG_ASSESSMENT_OK`) is set once Gatekeeper has assessed the file OK or
23
+ * the user has approved it — such a binary launches normally and MUST NOT be
24
+ * flagged. We therefore treat a quarantine xattr as *blocking* only when that
25
+ * bit is CLEAR. An unparseable flags field is treated conservatively as
26
+ * blocking (surfaced as a labeled, fixable error rather than a silent exec
27
+ * failure). Homebrew / package-manager installs strip the xattr entirely and
28
+ * so are never flagged.
29
+ *
30
+ * Signature / notarization gating (`codesign`/`spctl`) is deliberately NOT done
31
+ * here: chroxy's bundled provider binaries are ad-hoc/linker-signed and
32
+ * `spctl --assess` rejects them, so a hard spctl gate would break every
33
+ * un-notarized provider. That is P2 (opt-in) territory — see
34
+ * docs/security/spawned-binary-provenance.md.
35
+ *
36
+ * Every filesystem / subprocess touchpoint is an injectable seam so the whole
37
+ * module is unit-testable over a mocked fs/xattr layer with no real quarantined
38
+ * binary required.
39
+ */
40
+
41
+ import { existsSync as fsExistsSync, accessSync as fsAccessSync, constants as fsConstants } from 'fs'
42
+ import { isAbsolute as pathIsAbsolute } from 'path'
43
+ import { execFileSync } from 'child_process'
44
+
45
+ /**
46
+ * Classification of a resolved binary path.
47
+ * @enum {string}
48
+ */
49
+ export const BINARY_STATUS = Object.freeze({
50
+ /** Absolute path, exists, executable, and not blocked by Gatekeeper. */
51
+ OK: 'ok',
52
+ /** Path is not absolute, or does not exist on disk. */
53
+ NOT_FOUND: 'not_found',
54
+ /** Exists but the current process cannot execute it (no X bit / EACCES). */
55
+ NOT_EXECUTABLE: 'not_executable',
56
+ /** macOS: present + executable but carries a blocking com.apple.quarantine xattr. */
57
+ QUARANTINED: 'quarantined',
58
+ })
59
+
60
+ // macOS quarantine flag: Gatekeeper assessment passed / user approved. When set,
61
+ // the binary launches normally, so a quarantine xattr with this bit is NOT a block.
62
+ const QTN_FLAG_ASSESSMENT_OK = 0x0040
63
+
64
+ // Absolute path to the system `xattr`. This is security-hardening code — reading
65
+ // it by bare name (`xattr`) would resolve through PATH, so a shadowed `xattr`
66
+ // planted earlier on PATH could lie about the quarantine state and defeat the
67
+ // whole check. `/usr/bin/xattr` is a fixed, SIP-protected macOS system binary.
68
+ export const MACOS_XATTR = '/usr/bin/xattr'
69
+
70
+ /**
71
+ * Default macOS reader for the `com.apple.quarantine` xattr. Returns the raw
72
+ * attribute value, or `null` when the attribute is absent (the common case —
73
+ * `xattr -p` exits non-zero, which we swallow). Only ever called on darwin.
74
+ *
75
+ * Invokes the ABSOLUTE system path {@link MACOS_XATTR} (never a PATH lookup) so
76
+ * a shadowed `xattr` cannot subvert the integrity check. `execFile` is injected
77
+ * in tests to assert exactly that.
78
+ *
79
+ * @param {string} path
80
+ * @param {object} [opts]
81
+ * @param {Function} [opts.execFile=execFileSync]
82
+ * @returns {string|null}
83
+ */
84
+ export function readQuarantineXattr(path, { execFile = execFileSync } = {}) {
85
+ try {
86
+ const out = execFile(MACOS_XATTR, ['-p', 'com.apple.quarantine', path], {
87
+ encoding: 'utf-8',
88
+ stdio: ['ignore', 'pipe', 'ignore'],
89
+ timeout: 3000,
90
+ })
91
+ const trimmed = out.trim()
92
+ return trimmed.length > 0 ? trimmed : null
93
+ } catch {
94
+ // No such xattr (exit 1) or xattr unavailable — treat as "not quarantined".
95
+ return null
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Decide whether a `com.apple.quarantine` xattr value blocks launch. Blocks
101
+ * unless the ASSESSMENT_OK bit is set. An unparseable flags field is treated
102
+ * as blocking (conservative — better a fixable labeled error than a silent
103
+ * exec failure).
104
+ *
105
+ * @param {string|null|undefined} xattrValue
106
+ * @returns {boolean}
107
+ */
108
+ export function isBlockingQuarantine(xattrValue) {
109
+ if (typeof xattrValue !== 'string' || xattrValue.length === 0) return false
110
+ const firstField = xattrValue.split(';')[0].trim()
111
+ const flags = parseInt(firstField, 16)
112
+ if (Number.isNaN(flags)) return true
113
+ return (flags & QTN_FLAG_ASSESSMENT_OK) === 0
114
+ }
115
+
116
+ /**
117
+ * @typedef {Object} BinaryHealth
118
+ * @property {boolean} ok True only when status === 'ok'.
119
+ * @property {string} status One of {@link BINARY_STATUS}.
120
+ * @property {string} path The resolved path that was checked.
121
+ * @property {string|null} quarantine Raw quarantine xattr value when blocking, else null.
122
+ */
123
+
124
+ /**
125
+ * Verify a resolved binary path is safe to spawn: absolute, present,
126
+ * executable, and (macOS) not blocked by a quarantine xattr.
127
+ *
128
+ * Pure/deterministic given its injected seams — pass mocks in tests; production
129
+ * calls pass nothing and use the real fs + `xattr`.
130
+ *
131
+ * @param {string} resolvedPath - absolute path from resolveBinary()
132
+ * @param {object} [opts]
133
+ * @param {string} [opts.platform=process.platform]
134
+ * @param {(p:string)=>boolean} [opts.existsSync]
135
+ * @param {(p:string,mode:number)=>void} [opts.accessSync] - throws when not accessible
136
+ * @param {(p:string)=>boolean} [opts.isAbsolute]
137
+ * @param {(p:string)=>(string|null)} [opts.readQuarantineXattr] - macOS xattr reader
138
+ * @returns {BinaryHealth}
139
+ */
140
+ export function verifyBinary(resolvedPath, {
141
+ platform = process.platform,
142
+ existsSync = fsExistsSync,
143
+ accessSync = fsAccessSync,
144
+ isAbsolute = pathIsAbsolute,
145
+ readQuarantineXattr: readXattr = readQuarantineXattr,
146
+ } = {}) {
147
+ const path = typeof resolvedPath === 'string' ? resolvedPath : ''
148
+
149
+ // resolveBinary returns the bare name when nothing matched — a non-absolute
150
+ // path is the "not found on PATH or in candidates" signal.
151
+ if (!path || !isAbsolute(path) || !existsSync(path)) {
152
+ return { ok: false, status: BINARY_STATUS.NOT_FOUND, path, quarantine: null }
153
+ }
154
+
155
+ try {
156
+ accessSync(path, fsConstants.X_OK)
157
+ } catch {
158
+ return { ok: false, status: BINARY_STATUS.NOT_EXECUTABLE, path, quarantine: null }
159
+ }
160
+
161
+ // macOS-only: a Gatekeeper-quarantined binary keeps its X bit but refuses to
162
+ // launch. Skip entirely off darwin — there is no equivalent block.
163
+ if (platform === 'darwin') {
164
+ const xattrValue = readXattr(path)
165
+ if (isBlockingQuarantine(xattrValue)) {
166
+ return { ok: false, status: BINARY_STATUS.QUARANTINED, path, quarantine: xattrValue }
167
+ }
168
+ }
169
+
170
+ return { ok: true, status: BINARY_STATUS.OK, path, quarantine: null }
171
+ }
172
+
173
+ /**
174
+ * POSIX shell-quote a string so it survives copy-paste as a single argument.
175
+ * Leaves an already-safe token (the common `/opt/homebrew/bin/codex` case)
176
+ * unquoted; single-quotes anything containing whitespace or shell metacharacters
177
+ * (e.g. a path with spaces), escaping embedded single quotes. Keeps the
178
+ * `xattr -d …` / `chmod +x …` remediations copy-pasteable for any path.
179
+ *
180
+ * @param {string} s
181
+ * @returns {string}
182
+ */
183
+ export function shellQuotePath(s) {
184
+ if (typeof s !== 'string' || s.length === 0) return "''"
185
+ if (/^[A-Za-z0-9_/.:@%+=-]+$/.test(s)) return s
186
+ return `'${s.replace(/'/g, "'\\''")}'`
187
+ }
188
+
189
+ /**
190
+ * Build a user-facing message + remediation for a non-OK {@link BinaryHealth}.
191
+ * Centralised so preflight errors, the spawn-time catch, and `chroxy doctor`
192
+ * all speak the same language about what is wrong and how to fix it. Paths in
193
+ * the copy-pasteable remediations are shell-quoted so spaces don't break them.
194
+ *
195
+ * @param {BinaryHealth} health
196
+ * @param {object} [ctx]
197
+ * @param {string} [ctx.binary] - binary name (e.g. 'codex')
198
+ * @param {string} [ctx.installHint] - how to (re)install, e.g. 'install Codex CLI'
199
+ * @returns {{ message: string, remediation: string }}
200
+ */
201
+ export function describeBinaryHealth(health, { binary, installHint } = {}) {
202
+ const name = binary || 'binary'
203
+ const path = health && health.path ? health.path : ''
204
+ const qPath = shellQuotePath(path)
205
+ switch (health && health.status) {
206
+ case BINARY_STATUS.QUARANTINED: {
207
+ const remediation = `verify its provenance, then run: xattr -d com.apple.quarantine ${qPath} (or approve it in System Settings → Privacy & Security), or re-download ${name}`
208
+ return {
209
+ message: `"${name}" at ${path} is quarantined/blocked by macOS Gatekeeper — ${remediation}`,
210
+ remediation,
211
+ }
212
+ }
213
+ case BINARY_STATUS.NOT_EXECUTABLE: {
214
+ const remediation = `run: chmod +x ${qPath}`
215
+ return {
216
+ message: `"${name}" at ${path} exists but is not executable — ${remediation}`,
217
+ remediation,
218
+ }
219
+ }
220
+ case BINARY_STATUS.NOT_FOUND:
221
+ default: {
222
+ const remediation = installHint || `install ${name}`
223
+ return {
224
+ message: `"${name}" not found — ${remediation}`,
225
+ remediation,
226
+ }
227
+ }
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Spawn-time backstop: given a spawn failure, produce a labeled message naming a
233
+ * quarantine / not-found / not-executable root cause + fix when the provider
234
+ * binary changed out from under a running daemon — the between-preflight-and-
235
+ * spawn / mid-session-respawn window that motivated #6708 (XProtect removed the
236
+ * binary while the daemon was live). Returns `null` when the binary still looks
237
+ * healthy, so the caller keeps its own error text (the failure was something
238
+ * else).
239
+ *
240
+ * Shared by every provider spawn site so the labeling lives in one place:
241
+ * jsonl-subprocess (codex-exec + gemini), cli-session (claude), claude-tui, and
242
+ * codex-app-server.
243
+ *
244
+ * `attemptedPath` is the EXACT path the spawn tried to exec — take it from the
245
+ * spawn error's `err.path`, or the command captured at the spawn call site. It
246
+ * is deliberately NOT re-resolved here: a fresh `resolveBinary()` can land on a
247
+ * DIFFERENT path than the one that actually failed (PATH/candidate order can
248
+ * shift, or a since-repaired binary now resolves), so the backstop would then
249
+ * describe the wrong file. Verifying the attempted path describes exactly what
250
+ * failed.
251
+ *
252
+ * @param {object} opts
253
+ * @param {string} opts.attemptedPath - the exact path spawn tried to exec
254
+ * @param {string} opts.binary - provider/binary name for labeling (e.g. 'codex')
255
+ * @param {string} [opts.prefix] - message prefix (default `Failed to spawn <binary>`)
256
+ * @param {Function} [opts.verify=verifyBinary] - integrity checker (injected in tests)
257
+ * @returns {string|null} labeled message, or null when the binary looks healthy
258
+ */
259
+ export function labelBinarySpawnFailure({ attemptedPath, binary, prefix, verify = verifyBinary } = {}) {
260
+ if (typeof attemptedPath !== 'string' || attemptedPath.length === 0) return null
261
+ let health
262
+ try {
263
+ health = verify(attemptedPath)
264
+ } catch {
265
+ return null
266
+ }
267
+ if (health && (
268
+ health.status === BINARY_STATUS.QUARANTINED
269
+ || health.status === BINARY_STATUS.NOT_FOUND
270
+ || health.status === BINARY_STATUS.NOT_EXECUTABLE
271
+ )) {
272
+ const desc = describeBinaryHealth(health, { binary })
273
+ return `${prefix || `Failed to spawn ${binary}`}: ${desc.message}`
274
+ }
275
+ return null
276
+ }