@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
@@ -1,10 +1,33 @@
1
1
  import { EventEmitter } from 'events'
2
2
  import { randomUUID } from 'crypto'
3
+ import { resolve, relative, sep, isAbsolute } from 'node:path'
3
4
  import { createLogger } from './logger.js'
5
+ // #7004: the protected-path / secret-read FLOOR lives in permission-floor.js — a
6
+ // leaf module — because BOTH permission pipelines must apply the identical floor:
7
+ // this in-process path, and the HOOK-routed path (claude-tui/cli-session decide
8
+ // auto/acceptEdits in shell, so `POST /permission-floor` in ws-permissions.js
9
+ // calls the same isFlooredTarget). Never reimplement the floor at either call
10
+ // site; extend it there. Re-exported below for back-compat with existing
11
+ // importers/tests that took the predicates off this module.
12
+ import {
13
+ isFlooredTarget,
14
+ isProtectedPathTarget,
15
+ isSecretReadTarget,
16
+ PROTECTED_PATH_INPUT_FIELDS,
17
+ } from './permission-floor.js'
4
18
  // #6038: the SDK/TUI permission path broadcasts to clients too, so it must apply
5
19
  // the same redaction as the hook path. Shared sanitizer + value redactor live in
6
20
  // redaction.js (a leaf module — no import cycle / HTTP-handler weight).
7
21
  import { sanitizeToolInput, redactValue } from './redaction.js'
22
+ import { redactMcpUrl, resolveTrustAddress } from './byok-mcp-config.js'
23
+ // #6842 review (Copilot) — audit entries must carry the store's NORMALIZED
24
+ // project key, not the raw session cwd, or a relative / `..`-laden cwd
25
+ // produces entries that never correlate with the persisted rule they audit.
26
+ // Import is cycle-safe: permission-rule-store.js imports our ELIGIBLE_TOOLS /
27
+ // NEVER_AUTO_ALLOW consts, but both modules only touch each other's exports
28
+ // inside function bodies (call time), never at module evaluation, and
29
+ // normalizeProjectKey is a hoisted function declaration.
30
+ import { normalizeProjectKey } from './permission-rule-store.js'
8
31
 
9
32
  const _fallbackLog = createLogger('permission-manager')
10
33
 
@@ -19,7 +42,16 @@ export const ELIGIBLE_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit',
19
42
  // Tools that can never be auto-allowed by rules (too dangerous to whitelist).
20
43
  // `shell` is codex's command-execution approval — the codex analogue of Bash, so
21
44
  // arbitrary codex command execution can't be rule-whitelisted either (#6605).
22
- export const NEVER_AUTO_ALLOW = new Set(['Bash', 'Task', 'WebFetch', 'WebSearch', 'shell'])
45
+ // `request_permissions` is codex's sandbox-escalation approval (#6610) — broadening
46
+ // filesystem/network scope must always prompt, never be silently rule-whitelisted.
47
+ // `mcp_elicitation` is a codex MCP connector eliciting the user (#6635, e.g. a
48
+ // GitHub connector write approval) — a connector action must always prompt too.
49
+ export const NEVER_AUTO_ALLOW = new Set(['Bash', 'Task', 'WebFetch', 'WebSearch', 'shell', 'request_permissions', 'mcp_elicitation'])
50
+
51
+ // #7004 — back-compat re-exports. The floor moved to permission-floor.js (the
52
+ // single source both pipelines import); these names were exported from here since
53
+ // #6794/#6803, so keep them resolvable from this module for existing importers.
54
+ export { isProtectedPathTarget, isSecretReadTarget, PROTECTED_PATH_INPUT_FIELDS }
23
55
 
24
56
  // Default permission timeout (5 minutes)
25
57
  const DEFAULT_TIMEOUT_MS = 300_000
@@ -32,20 +64,43 @@ const MAX_SESSION_RULES = 100 // session-scoped auto-allow rules
32
64
  const MAX_RAW_DESCRIPTION_LEN = 8192 // raw tool field length fed to redactValue (far above the 200-char shown window)
33
65
 
34
66
  /**
35
- * #6543 (IDE P3 feature B) — per-tool whitelist of the CONTENT field(s) a client
36
- * may substitute via `editedInput` on an `allow` (the per-hunk pre-write review).
37
- * ONLY these content fields can come from the client; the path/anchor fields
38
- * (`file_path`, `old_string`, `command`, …) are always taken from the ORIGINAL
39
- * input. So an operator can narrow/edit the shown content but can NEVER redirect
40
- * where the write lands or what runs. A tool absent from this map ignores
41
- * `editedInput` entirely (accept/reject-the-whole-tool). `old_string` is
42
- * deliberately NOT editable — it is the Edit's match anchor, not shown content.
67
+ * #6543 (IDE P3 feature B) / #6773 — per-tool whitelist of the field(s) a client
68
+ * may substitute via `editedInput` on an `allow` (the pre-approve review/edit).
69
+ * ONLY these fields can come from the client; the path/anchor fields
70
+ * (`file_path`, `old_string`, …) are always taken from the ORIGINAL input, so an
71
+ * operator can narrow/edit the shown content or the command but can NEVER
72
+ * redirect where a write lands. A tool absent from this map ignores `editedInput`
73
+ * entirely (accept/reject-the-whole-tool). `old_string` is deliberately NOT
74
+ * editable — it is the Edit's match anchor, not shown content.
75
+ *
76
+ * #6773 — `Bash: ['command']` makes the shell command text editable before
77
+ * approve. For Bash the WHOLE command IS the reviewed content (there is no
78
+ * separate path field to redirect), and Bash carries none of
79
+ * {@link PROTECTED_PATH_INPUT_FIELDS}, so the protected-path floor never applied
80
+ * to it — editing `command` therefore cannot "edit around" the floor (the floor
81
+ * only ever guards a path-carrying tool's path fields, and no path field is ever
82
+ * whitelisted here — asserted by the editedInput-whitelist guard test). The
83
+ * merged command still flows to the SDK/BYOK tool executor as `updatedInput`,
84
+ * which runs the operator-approved text.
85
+ *
86
+ * Codex's `shell` is deliberately ABSENT: the codex app-server owns and runs its
87
+ * own already-parsed command and ignores `updatedInput` (see
88
+ * codex-app-server-session.js `_routeApproval`, which reads only allow/deny), so
89
+ * a `shell` edit would silently not take effect — surfacing an editable field
90
+ * there would mislead the operator. Deferred to a codex follow-up.
43
91
  */
44
- const EDITABLE_INPUT_FIELDS = {
92
+ export const EDITABLE_INPUT_FIELDS = {
45
93
  Write: ['content'],
46
94
  Edit: ['new_string'],
95
+ Bash: ['command'],
47
96
  }
48
97
 
98
+ // #6773 — hard cap on the operator-supplied DENY REASON before it becomes the
99
+ // agent-facing tool-result message. Far above any reasonable one-liner; it only
100
+ // bites a pathological paste. The wire schema (PermissionResponseSchema) caps at
101
+ // the same ceiling — this is the server-authoritative re-cap.
102
+ const MAX_DENY_REASON_LEN = 2000
103
+
49
104
  /**
50
105
  * Merge a client's `editedInput` into the agent's original tool input under the
51
106
  * strict {@link EDITABLE_INPUT_FIELDS} whitelist. Returns the original REFERENCE
@@ -73,6 +128,134 @@ export function mergeEditedInput(originalInput, editedInput, toolName) {
73
128
  return merged
74
129
  }
75
130
 
131
+ /**
132
+ * #6773 — build the agent-facing DENY message from an optional operator reason.
133
+ * A deny used to always resolve as the fixed `'User denied'` string, so nothing
134
+ * the operator typed reached the agent. When a non-empty reason is supplied it
135
+ * REPLACES that string (verbatim, so the model reads the operator's intent as
136
+ * the refusal reason and can adjust its next attempt — desktop-app "tell Claude
137
+ * what to do differently" parity). Bounded ({@link MAX_DENY_REASON_LEN}) and
138
+ * redacted (same {@link redactValue} pass every other freeform field entering
139
+ * the broadcast/agent stream gets, so an operator can't accidentally leak a
140
+ * secret into the streamed tool result). Falls back to `'User denied'` for a
141
+ * missing / non-string / blank reason.
142
+ * @param {*} reason the operator-supplied deny reason (untrusted)
143
+ * @returns {string}
144
+ */
145
+ export function buildDenyMessage(reason) {
146
+ if (typeof reason !== 'string') return 'User denied'
147
+ const trimmed = reason.trim()
148
+ if (trimmed.length === 0) return 'User denied'
149
+ return redactValue(trimmed.slice(0, MAX_DENY_REASON_LEN))
150
+ }
151
+
152
+
153
+ /**
154
+ * #6803 — collect every concrete target path a tool input names: the flat
155
+ * {@link PROTECTED_PATH_INPUT_FIELDS} plus `changes[]` member paths (codex
156
+ * apply_patch). Used by the rule-scope test so a path-scoped rule can confirm
157
+ * ALL of a tool call's targets fall inside its scope. Returns [] for a
158
+ * command-shaped / path-less input.
159
+ * @param {object} input
160
+ * @returns {string[]}
161
+ */
162
+ function collectTargetPaths(input) {
163
+ if (!input || typeof input !== 'object') return []
164
+ const out = []
165
+ for (const field of PROTECTED_PATH_INPUT_FIELDS) {
166
+ if (typeof input[field] === 'string' && input[field].length > 0) out.push(input[field])
167
+ }
168
+ if (Array.isArray(input.changes)) {
169
+ for (const change of input.changes) {
170
+ if (change && typeof change.path === 'string' && change.path.length > 0) out.push(change.path)
171
+ }
172
+ }
173
+ return out
174
+ }
175
+
176
+ // #6803 — a scope string is a GLOB (vs a plain directory prefix) when it carries
177
+ // a wildcard metachar (`*` or `?`). Globs match path-shaped; prefixes match "at
178
+ // or under this directory". Only `*` / `**` / `?` are supported — NOT character
179
+ // classes, so a scope containing `[`/`]` is a literal directory prefix, not a
180
+ // class (globToRegExp would escape the brackets anyway).
181
+ function _scopeHasGlobMagic(scope) {
182
+ return /[*?]/.test(scope)
183
+ }
184
+
185
+ /**
186
+ * #6803 — compile a rule-scope GLOB to an anchored RegExp. Dependency-free
187
+ * (the existing floor is pure string ops; a scope glob shouldn't drag in
188
+ * minimatch). Semantics, POSIX `/`-separated:
189
+ * - `**` → any run of characters INCLUDING separators (crosses directories)
190
+ * - `**` + `/` → the same, with the trailing `/` optional so `**​/x` also
191
+ * matches a bare `x`
192
+ * - `*` → any run of NON-separator characters (one path segment)
193
+ * - `?` → a single non-separator character
194
+ * Only these wildcards are supported — NOT character classes: `[`/`]` (and every
195
+ * other regex metachar) are ESCAPED and matched literally.
196
+ * @param {string} glob
197
+ * @returns {RegExp}
198
+ */
199
+ function globToRegExp(glob) {
200
+ let re = ''
201
+ for (let i = 0; i < glob.length; i++) {
202
+ const c = glob[i]
203
+ if (c === '*' && glob[i + 1] === '*') {
204
+ if (glob[i + 2] === '/') { re += '(?:.*/)?'; i += 2 } // `**/` → optional dir prefix
205
+ else { re += '.*'; i += 1 } // bare `**`
206
+ continue
207
+ }
208
+ if (c === '*') { re += '[^/]*'; continue }
209
+ if (c === '?') { re += '[^/]'; continue }
210
+ re += c.replace(/[.+^${}()|[\]\\/]/g, '\\$&')
211
+ }
212
+ return new RegExp('^' + re + '$')
213
+ }
214
+
215
+ /**
216
+ * #6803 — is `target` inside the rule `scope`, both resolved against `base`
217
+ * (the session cwd)? A GLOB scope is matched against the target's cwd-relative,
218
+ * POSIX-normalized path; a plain scope is a DIRECTORY PREFIX (target is at or
219
+ * under the resolved scope dir). Used by _ruleScopeMatches — a scoped rule only
220
+ * auto-decides a tool call whose targets all fall within scope.
221
+ * @param {string} target a tool-input path value
222
+ * @param {string} scope the rule's `path` scope
223
+ * @param {string} base the session cwd
224
+ * @returns {boolean}
225
+ */
226
+ function pathWithinScope(target, scope, base) {
227
+ const resolvedTarget = resolve(base, target)
228
+ if (_scopeHasGlobMagic(scope)) {
229
+ // PR #6873 review — a glob scope must NEVER reach ABOVE the session cwd:
230
+ // `**/*.js` must not match `../evil.js`, `**` must not match `/etc/passwd`.
231
+ // Reject an escaping target FIRST (same under-base guard the prefix branch
232
+ // uses), THEN glob-match the under-base relative path. Without this the glob
233
+ // ran against `relative(base, target)` unchecked, so `..`/absolute targets
234
+ // supplied via set_permission_rules could be auto-approved out of scope.
235
+ const rel = relative(base, resolvedTarget)
236
+ if (isAbsolute(rel) || rel === '..' || rel.startsWith('..' + sep)) return false
237
+ return globToRegExp(scope).test(rel.split(sep).join('/'))
238
+ }
239
+ const resolvedScope = resolve(base, scope)
240
+ const rel = relative(resolvedScope, resolvedTarget)
241
+ // At the scope dir itself (rel === '') or under it (not `..`, not absolute).
242
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + sep))
243
+ }
244
+
245
+ /**
246
+ * #6803 — normalize a rule to the stored shape `{ tool, decision }`, carrying an
247
+ * optional `path` scope ONLY when it is a non-empty string. Keeping `path` off
248
+ * the object entirely when unscoped means unscoped rules stay deepEqual to a
249
+ * plain `{ tool, decision }` (the shape every existing test/consumer asserts).
250
+ * @param {{tool: string, decision: string, path?: string}} rule
251
+ * @returns {{tool: string, decision: string, path?: string}}
252
+ */
253
+ function normalizeStoredRule(rule) {
254
+ const out = { tool: rule.tool, decision: rule.decision }
255
+ if (typeof rule.path === 'string' && rule.path.length > 0) out.path = rule.path
256
+ return out
257
+ }
258
+
76
259
  /**
77
260
  * Manages in-process permission requests for SDK-style sessions.
78
261
  *
@@ -89,13 +272,36 @@ export function mergeEditedInput(originalInput, editedInput, toolName) {
89
272
  * user_question { toolUseId, questions }
90
273
  */
91
274
  export class PermissionManager extends EventEmitter {
92
- constructor({ timeoutMs, log, maxPendingPermissions } = {}) {
275
+ constructor({ timeoutMs, log, maxPendingPermissions, cwd, ruleStore, mcpTrustLookup } = {}) {
93
276
  super()
94
277
  this._timeoutMs = timeoutMs || DEFAULT_TIMEOUT_MS
95
278
  this._log = log || console
279
+ // #6834 — injectable DNS resolver for the MCP-trust prompt's resolved-address
280
+ // display. Defaults to node:dns/promises lookup (via resolveTrustAddress)
281
+ // when unset; tests pass a fake so they never touch real DNS.
282
+ this._mcpTrustLookup = typeof mcpTrustLookup === 'function' ? mcpTrustLookup : null
96
283
  // #6448 — bound on concurrent pending permissions; injectable so the cap is
97
284
  // testable without minting 1000 real requests.
98
285
  this._maxPendingPermissions = maxPendingPermissions || MAX_PENDING_PERMISSIONS
286
+ // #6794 — session cwd anchors the protected-path floor (see
287
+ // isProtectedPathTarget). Optional: when unset the floor resolves targets
288
+ // against process.cwd(), which still catches relative protected paths.
289
+ this._cwd = (typeof cwd === 'string' && cwd.length > 0) ? cwd : null
290
+ // #6771 — durable per-project rule store (PermissionRuleStore). Optional:
291
+ // when present, an `allowAlways` decision persists a rule keyed by this
292
+ // session's cwd, and this session seeds its persistent rules from the store
293
+ // on construction (below) so a prior grant takes effect without re-prompting
294
+ // after a daemon restart.
295
+ this._ruleStore = ruleStore || null
296
+ // #6830 (PR #6842 review) — direct audit callback for persisted-rule
297
+ // auto-approves. Deliberately NOT an EventEmitter event: emitting
298
+ // `permission_resolved` here would ride wirePermissionManager →
299
+ // SessionManager → ws-forwarding → broadcastToSession, spamming every
300
+ // subscribed client with a wire message per rule-matched tool call. The
301
+ // sink is a plain function the WsServer wires straight into its
302
+ // PermissionAuditLog (see ws-server.js _attachPermissionAuditSink), so
303
+ // the signal stays in the audit lane only. Null until wired.
304
+ this._auditSink = null
99
305
 
100
306
  this._pendingPermissions = new Map() // requestId -> { resolve, input }
101
307
  this._permissionTimers = new Map() // requestId -> timer
@@ -114,7 +320,16 @@ export class PermissionManager extends EventEmitter {
114
320
  this._lastPermissionData = new Map() // requestId -> emitted permission_request payload
115
321
 
116
322
  // Session-scoped permission rules
117
- this._sessionRules = [] // [{ tool, decision }]
323
+ this._sessionRules = [] // [{ tool, decision, path? }] — path = #6803 optional scope
324
+
325
+ // #6771 — durable per-project rules seeded from the store for THIS
326
+ // session's cwd. Kept SEPARATE from `_sessionRules` so `setRules`/
327
+ // `clearRules` (the session-scoped `set_permission_rules` path, and the
328
+ // clearRules() on a permission-mode switch) never wipe a project-level
329
+ // "always allow", and vice-versa. `_matchesRule` consults both.
330
+ this._persistentRules = (this._ruleStore && this._cwd)
331
+ ? this._ruleStore.getRules(this._cwd)
332
+ : []
118
333
 
119
334
  // AskUserQuestion handling
120
335
  this._pendingUserAnswer = null // { resolve, input, toolUseId } when waiting for user answer
@@ -125,9 +340,12 @@ export class PermissionManager extends EventEmitter {
125
340
  /**
126
341
  * Set session-scoped permission rules.
127
342
  * Each rule must have a `tool` in ELIGIBLE_TOOLS and a `decision` of 'allow' or 'deny'.
128
- * Rules for NEVER_AUTO_ALLOW tools are rejected with an error.
343
+ * Rules for NEVER_AUTO_ALLOW tools are rejected with an error. #6803 — a rule
344
+ * may carry an optional `path` SCOPE (a non-empty string); the stored rule
345
+ * preserves it and {@link _matchesRule} only matches a scoped rule when the
346
+ * tool's target paths fall within it.
129
347
  *
130
- * @param {Array<{tool: string, decision: string}>} rules
348
+ * @param {Array<{tool: string, decision: string, path?: string}>} rules
131
349
  * @throws {Error} if any rule is invalid
132
350
  */
133
351
  setRules(rules) {
@@ -151,41 +369,178 @@ export class PermissionManager extends EventEmitter {
151
369
  if (!ELIGIBLE_TOOLS.has(rule.tool)) {
152
370
  throw new Error(`${rule.tool} is not in ELIGIBLE_TOOLS`)
153
371
  }
372
+ if (rule.path !== undefined && (typeof rule.path !== 'string' || rule.path.length === 0)) {
373
+ throw new Error('rule path scope must be a non-empty string')
374
+ }
154
375
  }
155
- this._sessionRules = rules.slice()
376
+ // #6803 — normalize to the stored shape, carrying `path` only when present so
377
+ // an unscoped rule stays a plain { tool, decision } (deepEqual-friendly).
378
+ this._sessionRules = rules.map(normalizeStoredRule)
156
379
  }
157
380
 
158
381
  /**
159
- * Return a copy of the current session rules.
382
+ * Return a copy of the current session rules (each rule object cloned so a
383
+ * caller can't mutate the internal set; #6803 — carries `path` when scoped).
160
384
  *
161
- * @returns {Array<{tool: string, decision: string}>}
385
+ * @returns {Array<{tool: string, decision: string, path?: string}>}
162
386
  */
163
387
  getRules() {
164
- return this._sessionRules.slice()
388
+ return this._sessionRules.map(normalizeStoredRule)
165
389
  }
166
390
 
167
391
  /**
168
- * Clear all session-scoped permission rules.
392
+ * Clear all session-scoped permission rules. Persistent (project-scoped)
393
+ * rules are UNTOUCHED — a mode switch or a `set_permission_rules []` must not
394
+ * silently revoke a durable "always allow" (#6771).
169
395
  */
170
396
  clearRules() {
171
397
  this._sessionRules = []
172
398
  }
173
399
 
174
400
  /**
175
- * Check whether a toolName matches a session rule.
401
+ * Return a copy of the durable (project-scoped) rules currently applied to
402
+ * this session, each tagged `persist: 'project'` so a client can render them
403
+ * distinctly from session rules (#6771).
404
+ *
405
+ * @returns {Array<{tool: string, decision: string, persist: 'project'}>}
406
+ */
407
+ getPersistentRules() {
408
+ return this._persistentRules.map((r) => {
409
+ const out = { tool: r.tool, decision: r.decision, persist: 'project' }
410
+ if (typeof r.path === 'string' && r.path.length > 0) out.path = r.path
411
+ return out
412
+ })
413
+ }
414
+
415
+ /**
416
+ * Replace this session's durable rule set in memory (does NOT persist —
417
+ * callers that own the store persist separately). Used to re-seed after the
418
+ * store changes out-of-band (e.g. a client edited the project's rules).
419
+ *
420
+ * @param {Array<{tool: string, decision: string}>} rules
421
+ */
422
+ setPersistentRules(rules) {
423
+ this._persistentRules = Array.isArray(rules)
424
+ ? rules
425
+ .filter((r) => r && typeof r.tool === 'string' && (r.decision === 'allow' || r.decision === 'deny'))
426
+ .map(normalizeStoredRule) // #6803 — preserve an optional `path` scope
427
+ : []
428
+ }
429
+
430
+ /**
431
+ * #6803 — does this rule's optional `path` SCOPE admit `input`? An UNSCOPED
432
+ * rule (no `path`) matches every input, exactly as before. A SCOPED rule
433
+ * matches only when the input names at least one concrete target path AND
434
+ * EVERY target falls within the scope (resolved against the session cwd) — so
435
+ * a scoped `allow` never auto-approves an out-of-scope target, and an input
436
+ * with no path (a command-shaped tool, or a bare `Read` with no file) never
437
+ * matches a scoped rule and falls through to a prompt.
438
+ * @param {{tool: string, decision: string, path?: string}} rule
439
+ * @param {object} [input]
440
+ * @returns {boolean}
441
+ */
442
+ _ruleScopeMatches(rule, input) {
443
+ if (typeof rule.path !== 'string' || rule.path.length === 0) return true
444
+ const targets = collectTargetPaths(input)
445
+ if (targets.length === 0) return false
446
+ const base = this._cwd || process.cwd()
447
+ return targets.every((t) => pathWithinScope(t, rule.path, base))
448
+ }
449
+
450
+ /**
451
+ * Check whether a tool call matches a session or persistent rule. Session
452
+ * rules are consulted FIRST (a live, intentional session decision wins over a
453
+ * standing project grant), then the durable project rules (#6771). #6803 — a
454
+ * rule with a `path` scope only matches when the tool's target paths fall
455
+ * within it (see {@link _ruleScopeMatches}); `input` is optional, so a bare
456
+ * `_matchesRule(tool)` still resolves unscoped rules unchanged.
176
457
  *
177
458
  * @param {string} toolName
459
+ * @param {object} [input] the tool input (for path-scope matching)
178
460
  * @returns {'allow'|'deny'|null} null if no rule matches
179
461
  */
180
- _matchesRule(toolName) {
462
+ _matchesRule(toolName, input) {
181
463
  for (const rule of this._sessionRules) {
182
- if (rule.tool === toolName) {
464
+ if (rule.tool === toolName && this._ruleScopeMatches(rule, input)) {
465
+ return rule.decision
466
+ }
467
+ }
468
+ for (const rule of this._persistentRules) {
469
+ if (rule.tool === toolName && this._ruleScopeMatches(rule, input)) {
183
470
  return rule.decision
184
471
  }
185
472
  }
186
473
  return null
187
474
  }
188
475
 
476
+ /**
477
+ * #6830 — was the 'allow' decision _matchesRule just returned for `toolName`
478
+ * SOURCED from a durable project-scoped rule (as opposed to a session rule)?
479
+ * Mirrors _matchesRule's own precedence (session rules are checked first and
480
+ * shadow a persistent rule for the same tool) WITHOUT changing _matchesRule's
481
+ * tested return contract (a plain 'allow'|'deny'|null string, asserted
482
+ * directly in permission-manager.test.js). Used only to decide whether a
483
+ * silent auto-approve needs an audit-only signal (see
484
+ * _auditPersistedRuleAutoApprove) — a session-rule-sourced allow is an
485
+ * explicit, non-durable decision the user already made this session and
486
+ * needs no extra trail beyond what's already logged for it.
487
+ * #6803 — mirrors _matchesRule's scope filter too: a session rule only shadows
488
+ * when it actually MATCHES this input (scope included), and the persistent
489
+ * source must be a scope-matching allow.
490
+ * @param {string} toolName
491
+ * @param {object} [input]
492
+ * @returns {boolean}
493
+ */
494
+ _persistentRuleSourced(toolName, input) {
495
+ if (this._sessionRules.some((r) => r.tool === toolName && this._ruleScopeMatches(r, input))) return false
496
+ return this._persistentRules.some((r) => r.tool === toolName && r.decision === 'allow' && this._ruleScopeMatches(r, input))
497
+ }
498
+
499
+ /**
500
+ * #6830 (PR #6842 review) — install the direct audit callback for
501
+ * persisted-rule auto-approves. Single-slot (last writer wins — one
502
+ * WsServer audits at a time); pass null/non-function to detach.
503
+ * `projectKey` arrives pre-NORMALIZED (normalizeProjectKey — the
504
+ * PermissionRuleStore key), or null for an unkeyable cwd.
505
+ * @param {null|((info: {tool: string, projectKey: string|null}) => void)} sink
506
+ */
507
+ setAuditSink(sink) {
508
+ this._auditSink = typeof sink === 'function' ? sink : null
509
+ }
510
+
511
+ /**
512
+ * #6830 — audit-only signal for a persisted (project-scoped) rule silently
513
+ * auto-approving `toolName` with NO visible prompt: handlePermission
514
+ * short-circuits BEFORE minting a requestId or emitting permission_request,
515
+ * so without this the audit log has ZERO trace of the tool call — an
516
+ * auditor querying permission history can't answer "why did tool X
517
+ * auto-approve after a restart?" from the log alone.
518
+ *
519
+ * PR #6842 review — this must NOT emit `permission_resolved` (or any other
520
+ * session event): permission_resolved is a broadcast-lane event
521
+ * (session-manager.js builtinTransient → ws-forwarding →
522
+ * broadcastToSession), so an emission here would send a wire message to
523
+ * every subscribed client on EVERY rule-matched tool call, at machine
524
+ * speed. Instead it calls the WsServer-wired `_auditSink` directly — the
525
+ * audit lane only, coalesced ring-side by
526
+ * PermissionAuditLog.logPersistedRuleApproval. Guarded so a sink bug can
527
+ * never break tool approval; a no-op when no server has wired a sink.
528
+ * @param {string} toolName
529
+ */
530
+ _auditPersistedRuleAutoApprove(toolName) {
531
+ if (!this._auditSink) return
532
+ try {
533
+ // #6842 review (Copilot) — projectKey is the store's NORMALIZED key
534
+ // (normalizeProjectKey, the same helper every PermissionRuleStore
535
+ // read/write path uses), NOT the raw session cwd: a relative or
536
+ // `..`-laden cwd would otherwise stamp entries an auditor can never
537
+ // match against the persisted rule's key in permission-rules.json.
538
+ this._auditSink({ tool: toolName, projectKey: normalizeProjectKey(this._cwd) })
539
+ } catch (err) {
540
+ this._logWarn(`Permission audit sink threw: ${err?.message || err}`)
541
+ }
542
+ }
543
+
189
544
  /**
190
545
  * Handle a permission check from the SDK canUseTool callback.
191
546
  *
@@ -210,29 +565,59 @@ export class PermissionManager extends EventEmitter {
210
565
  return this._handleAskUserQuestion(input, signal)
211
566
  }
212
567
 
568
+ // #6794 — protected-path floor. A path-carrying tool aimed at a protected
569
+ // path (.git/.claude/.vscode/.config/git/.env*) must NOT be silently
570
+ // auto-approved by auto mode, a broad `allow` rule, or acceptEdits — mirror
571
+ // Claude Code's "always ask" floor and let it fall through to the prompt.
572
+ // This is a FLOOR, not a hard deny: a lenient mode simply stops
573
+ // short-circuiting for these paths. A `deny` rule still denies (the floor
574
+ // never widens access), and if the prompt path then auto-denies on
575
+ // no-client/timeout, that is the existing fail-closed behavior.
576
+ //
577
+ // #6803 — the floor is TOOL-AWARE. A non-mutating read (Read/Glob/Grep) is
578
+ // floored ONLY on secret files (env + key material) via isSecretReadTarget —
579
+ // reading a config dir is benign and must stay un-prompted. Every other
580
+ // (mutating / unknown) tool gets the full config-dir + secret write floor.
581
+ //
582
+ // #7004 — that tool-aware choice IS isFlooredTarget (permission-floor.js),
583
+ // the one predicate the HOOK path (`POST /permission-floor`) calls too, so
584
+ // both pipelines cannot drift on which tool gets which floor.
585
+ const protectedTarget = isFlooredTarget(toolName, input, this._cwd)
586
+
213
587
  // 'auto' (= SDK bypassPermissions) short-circuit: approve every tool
214
588
  // call without consulting rules or emitting a prompt. SdkSession also
215
589
  // skips canUseTool registration when starting a turn in auto mode, but
216
590
  // a turn that started in another mode keeps its callback alive for the
217
591
  // whole turn — without this guard, flipping to auto mid-turn (#3729)
218
592
  // still emits prompts because session rules and the prompt path run
219
- // before any mode check.
220
- if (permissionMode === 'auto') {
593
+ // before any mode check. #6794: the floor takes precedence — a protected
594
+ // target still prompts even under auto.
595
+ if (permissionMode === 'auto' && !protectedTarget) {
221
596
  return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
222
597
  }
223
598
 
224
- // Session rules: check before acceptEdits and the prompt path
225
- const ruleDecision = this._matchesRule(toolName)
226
- if (ruleDecision !== null) {
599
+ // Session rules: check before acceptEdits and the prompt path. #6794: a
600
+ // protected target skips the `allow` branch (fall through to the prompt);
601
+ // a `deny` rule still denies.
602
+ const ruleDecision = this._matchesRule(toolName, input)
603
+ if (ruleDecision !== null && !(protectedTarget && ruleDecision === 'allow')) {
227
604
  this._logInfo(`Permission rule matched for ${toolName}: ${ruleDecision}`)
228
605
  if (ruleDecision === 'allow') {
606
+ // #6830 — a durable project rule (not a session rule) just silently
607
+ // auto-approved this tool call. Record it via the direct audit sink
608
+ // (NOT an event — see _auditPersistedRuleAutoApprove) so the
609
+ // permission audit log has a trace even though no prompt was shown.
610
+ if (this._persistentRuleSourced(toolName, input)) {
611
+ this._auditPersistedRuleAutoApprove(toolName)
612
+ }
229
613
  return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
230
614
  }
231
615
  return Promise.resolve({ behavior: 'deny', message: 'Denied by session rule' })
232
616
  }
233
617
 
234
- // acceptEdits: auto-approve file operations, prompt for everything else
235
- if (permissionMode === 'acceptEdits' && ACCEPT_EDITS_TOOLS.has(toolName)) {
618
+ // acceptEdits: auto-approve file operations, prompt for everything else.
619
+ // #6794: the floor takes precedence — a protected target still prompts.
620
+ if (permissionMode === 'acceptEdits' && ACCEPT_EDITS_TOOLS.has(toolName) && !protectedTarget) {
236
621
  return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
237
622
  }
238
623
 
@@ -379,10 +764,14 @@ export class PermissionManager extends EventEmitter {
379
764
  *
380
765
  * @param {string} requestId - The permission request ID
381
766
  * @param {string} decision - 'allow', 'deny', or 'allowAlways'
767
+ * @param {*} [editedInput] - #6543/#6773 client edits merged under the
768
+ * {@link EDITABLE_INPUT_FIELDS} whitelist on an approve (ignored on deny).
769
+ * @param {string} [reason] - #6773 operator-supplied free-text deny reason;
770
+ * used only on a `deny` to replace the fixed 'User denied' agent message.
382
771
  * @returns {boolean} true if a pending permission was found and resolved,
383
772
  * false if the requestId was unknown (already resolved or expired).
384
773
  */
385
- respondToPermission(requestId, decision, editedInput) {
774
+ respondToPermission(requestId, decision, editedInput, reason) {
386
775
  const pending = this._pendingPermissions.get(requestId)
387
776
  if (!pending) {
388
777
  this._logWarn(`No pending permission for ${requestId}`)
@@ -431,9 +820,28 @@ export class PermissionManager extends EventEmitter {
431
820
  if (pending.suggestions && pending.suggestions.length > 0) {
432
821
  result.updatedPermissions = pending.suggestions
433
822
  }
823
+ // #6771 — persist a DURABLE project-scoped rule so this grant survives a
824
+ // daemon restart (the SDK `updatedPermissions` above only persists within
825
+ // the SDK's own session). Only for rule-eligible tools: the store rejects
826
+ // NEVER_AUTO_ALLOW / non-ELIGIBLE tools, so an `allowAlways` on Bash (or a
827
+ // codex `shell`) degrades to a one-shot allow and is NEVER durably
828
+ // whitelisted. Seed the in-memory persistent set too so the very next tool
829
+ // call in THIS session auto-allows without re-prompting.
830
+ if (toolName && this._ruleStore && this._cwd) {
831
+ const persisted = this._ruleStore.addRule(this._cwd, { tool: toolName, decision: 'allow' })
832
+ if (persisted) {
833
+ // Re-seed the in-memory set so the very next tool call in THIS session
834
+ // auto-allows. The client-facing `permission_rules_updated` broadcast
835
+ // is emitted by the WS response handler (settings-handlers.js) after
836
+ // this resolves — getPersistentRules() reflects the update synchronously.
837
+ this.setPersistentRules(this._ruleStore.getRules(this._cwd))
838
+ }
839
+ }
434
840
  pending.resolve(result)
435
841
  } else {
436
- pending.resolve({ behavior: 'deny', message: 'User denied' })
842
+ // #6773 — carry the operator's free-text reason (bounded + redacted) back
843
+ // to the agent as the denial message, instead of the fixed 'User denied'.
844
+ pending.resolve({ behavior: 'deny', message: buildDenyMessage(reason) })
437
845
  }
438
846
  return true
439
847
  }
@@ -644,22 +1052,61 @@ export class PermissionManager extends EventEmitter {
644
1052
  * - On deny: resolves to false; caller marks the client DEAD.
645
1053
  * - On timeout (default permissionTimeout): treated as deny.
646
1054
  *
647
- * @param {{ name: string, command: string, args?: string[], envKeys?: string[] }} server
1055
+ * #6821: also handles REMOTE (streamable-HTTP / SSE) servers, which carry a
1056
+ * `url` + `headerKeys` instead of `command`/`args`/`envKeys`. The url is
1057
+ * credential-stripped (via redactMcpUrl) before it reaches the description
1058
+ * or the broadcast input; header VALUES are never passed in.
1059
+ *
1060
+ * @param {{ name: string, command?: string, args?: string[], envKeys?: string[], url?: string, headerKeys?: string[] }} server
648
1061
  * @returns {Promise<boolean>}
649
1062
  */
650
- requestMcpTrust(server) {
1063
+ async requestMcpTrust(server) {
1064
+ const isRemote = typeof server.url === 'string' && server.url.length > 0
1065
+ const safeUrl = isRemote ? redactMcpUrl(server.url) : ''
1066
+ // #6834 — for a REMOTE server, best-effort-resolve the host BEFORE we build
1067
+ // the prompt so the consent string can show when a "remote" URL actually
1068
+ // points at a loopback / private / internal address (owner decision:
1069
+ // display, never block beyond the existing cloud-metadata hard-block).
1070
+ // Resolution is non-fatal — resolveTrustAddress returns a 'could not
1071
+ // resolve host' record on any failure and never throws. Only the hostname
1072
+ // is read (from the already-redacted url); only IPs come back. The stdio
1073
+ // path has no url, so no await runs and its prompt still emits synchronously
1074
+ // (autoAllowPending / pending-size assertions depend on that).
1075
+ const resolved = isRemote
1076
+ ? await resolveTrustAddress(safeUrl, { lookup: this._mcpTrustLookup || undefined })
1077
+ : null
651
1078
  return new Promise((resolve) => {
652
1079
  const requestId = `mcp-trust-${this._idNonce}-${++this._permissionCounter}-${Date.now()}`
653
1080
  const argv0 = Array.isArray(server.args) && server.args.length > 0 ? server.args[0] : ''
654
1081
  const input = {
655
- mcpServer: {
656
- name: server.name,
657
- command: server.command,
658
- args: Array.isArray(server.args) ? [...server.args] : [],
659
- envKeys: Array.isArray(server.envKeys) ? [...server.envKeys] : [],
660
- },
1082
+ mcpServer: isRemote
1083
+ ? {
1084
+ name: server.name,
1085
+ url: safeUrl,
1086
+ headerKeys: Array.isArray(server.headerKeys) ? [...server.headerKeys] : [],
1087
+ // Structured mirror of the resolved-address marker embedded in
1088
+ // `description`. Plain strings/arrays/bools — survives
1089
+ // sanitizeToolInput untouched — so a client that renders MCP-trust
1090
+ // input structurally can surface it without re-parsing the string.
1091
+ resolvedAddress: resolved
1092
+ ? {
1093
+ resolved: resolved.resolved,
1094
+ addresses: resolved.addresses,
1095
+ classification: resolved.classification,
1096
+ display: resolved.display,
1097
+ }
1098
+ : null,
1099
+ }
1100
+ : {
1101
+ name: server.name,
1102
+ command: server.command,
1103
+ args: Array.isArray(server.args) ? [...server.args] : [],
1104
+ envKeys: Array.isArray(server.envKeys) ? [...server.envKeys] : [],
1105
+ },
661
1106
  }
662
- const description = `Spawn MCP server "${server.name}" running ${server.command}${argv0 ? ' ' + argv0 : ''}`
1107
+ const description = isRemote
1108
+ ? `Connect to MCP server "${server.name}" at ${safeUrl}${resolved ? ` — ${resolved.display}` : ''}`
1109
+ : `Spawn MCP server "${server.name}" running ${server.command}${argv0 ? ' ' + argv0 : ''}`
663
1110
 
664
1111
  // Wrap pending entry so respondToPermission's standard mapping
665
1112
  // ({behavior:'allow'} or {behavior:'deny'}) translates to a boolean
@@ -826,4 +1273,9 @@ export function wirePermissionManager(session, permissions, { onRequest, onResol
826
1273
  // Backward-compatible accessors used by ws-permissions.js + settings-handlers.js.
827
1274
  session._pendingPermissions = permissions._pendingPermissions
828
1275
  session._lastPermissionData = permissions._lastPermissionData
1276
+ // #6830 (PR #6842 review) — public delegate so the WsServer can wire its
1277
+ // PermissionAuditLog straight into this manager's persisted-rule audit path
1278
+ // (ws-server.js _attachPermissionAuditSink) without reaching into privates.
1279
+ // Installed for every wirePermissionManager provider (sdk / byok / codex).
1280
+ session.setPermissionAuditSink = (sink) => permissions.setAuditSink(sink)
829
1281
  }