@chroxy/server 0.10.0 → 0.11.10
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 +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
|
@@ -1,17 +1,52 @@
|
|
|
1
1
|
import { EventEmitter } from 'events'
|
|
2
2
|
import { randomUUID } from 'crypto'
|
|
3
|
+
import { resolve, relative, sep, isAbsolute } from 'node:path'
|
|
4
|
+
import { realpathSync } from 'node:fs'
|
|
5
|
+
import { resolveTargetComponentwiseSync } from './utils/componentwise-resolver.js'
|
|
6
|
+
import { isPathWithin } from './utils/path-containment.js'
|
|
3
7
|
import { createLogger } from './logger.js'
|
|
8
|
+
import { globPatternEscapeReason } from './built-in-tools/tool-transforms.js'
|
|
9
|
+
// #7004: the protected-path / secret-read FLOOR lives in permission-floor.js — a
|
|
10
|
+
// leaf module — because BOTH permission pipelines must apply the identical floor:
|
|
11
|
+
// this in-process path, and the HOOK-routed path (claude-tui/cli-session decide
|
|
12
|
+
// auto/acceptEdits in shell, so `POST /permission-floor` in ws-permissions.js
|
|
13
|
+
// calls the same isFlooredTarget). Never reimplement the floor at either call
|
|
14
|
+
// site; extend it there. Re-exported below for back-compat with existing
|
|
15
|
+
// importers/tests that took the predicates off this module.
|
|
16
|
+
import {
|
|
17
|
+
isFlooredTarget,
|
|
18
|
+
isProtectedPathTarget,
|
|
19
|
+
isSecretReadTarget,
|
|
20
|
+
PROTECTED_PATH_INPUT_FIELDS,
|
|
21
|
+
collectChangeTargets,
|
|
22
|
+
effectiveSearchRoot,
|
|
23
|
+
} from './permission-floor.js'
|
|
4
24
|
// #6038: the SDK/TUI permission path broadcasts to clients too, so it must apply
|
|
5
25
|
// the same redaction as the hook path. Shared sanitizer + value redactor live in
|
|
6
26
|
// redaction.js (a leaf module — no import cycle / HTTP-handler weight).
|
|
7
|
-
import { sanitizeToolInput, redactValue } from './redaction.js'
|
|
27
|
+
import { sanitizeToolInput, redactValue, describeByNamedField, describeToolInput, describeComposedText } from './redaction.js'
|
|
28
|
+
import { redactMcpUrl, resolveTrustAddress, MCP_SERVER_SOURCE_VALUES } from './byok-mcp-config.js'
|
|
29
|
+
import { DROPPED_HUNKS_KEY, KEPT_HUNKS_KEY, EditedInputRefusedError, isHunkReviewedTool, narrowByDroppedHunks, assertClientTextAllowed } from './edited-input.js'
|
|
30
|
+
// #6842 review (Copilot) — audit entries must carry the store's NORMALIZED
|
|
31
|
+
// project key, not the raw session cwd, or a relative / `..`-laden cwd
|
|
32
|
+
// produces entries that never correlate with the persisted rule they audit.
|
|
33
|
+
// Import is cycle-safe: permission-rule-store.js imports our ELIGIBLE_TOOLS /
|
|
34
|
+
// NEVER_AUTO_ALLOW consts, but both modules only touch each other's exports
|
|
35
|
+
// inside function bodies (call time), never at module evaluation, and
|
|
36
|
+
// normalizeProjectKey is a hoisted function declaration.
|
|
37
|
+
import { normalizeProjectKey } from './permission-rule-store.js'
|
|
38
|
+
import { permissionScope } from './permission-scope.js'
|
|
8
39
|
|
|
9
40
|
const _fallbackLog = createLogger('permission-manager')
|
|
10
41
|
|
|
11
42
|
// Tools that acceptEdits mode auto-approves. `apply_patch` is codex's file-edit
|
|
12
43
|
// approval (item/fileChange/requestApproval, #6605) — the codex analogue of
|
|
13
44
|
// Write/Edit, so acceptEdits auto-approves codex edits too.
|
|
14
|
-
|
|
45
|
+
// Exported so the classification can be PINNED by tests: it is the strongest of
|
|
46
|
+
// the three read-only premises behind #7295 (ELIGIBLE_TOOLS needs a user to
|
|
47
|
+
// create a rule; this one is automatic in acceptEdits mode), and it was the only
|
|
48
|
+
// one a test could not assert.
|
|
49
|
+
export const ACCEPT_EDITS_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep', 'apply_patch'])
|
|
15
50
|
|
|
16
51
|
// Tools eligible for session-scoped auto-allow rules (`apply_patch` = codex edits).
|
|
17
52
|
export const ELIGIBLE_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'Glob', 'Grep', 'apply_patch'])
|
|
@@ -19,7 +54,147 @@ export const ELIGIBLE_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit',
|
|
|
19
54
|
// Tools that can never be auto-allowed by rules (too dangerous to whitelist).
|
|
20
55
|
// `shell` is codex's command-execution approval — the codex analogue of Bash, so
|
|
21
56
|
// arbitrary codex command execution can't be rule-whitelisted either (#6605).
|
|
22
|
-
|
|
57
|
+
// `request_permissions` is codex's sandbox-escalation approval (#6610) — broadening
|
|
58
|
+
// filesystem/network scope must always prompt, never be silently rule-whitelisted.
|
|
59
|
+
// `mcp_elicitation` is a codex MCP connector eliciting the user (#6635, e.g. a
|
|
60
|
+
// GitHub connector write approval) — a connector action must always prompt too.
|
|
61
|
+
// `Agent` is what Claude Code calls the sub-delegation tool today; `Task` is the
|
|
62
|
+
// older spelling and both are live, because chroxy runs against whatever
|
|
63
|
+
// `claude` the user has installed (#7340). Not exploitable on its own — a rule
|
|
64
|
+
// also has to clear `ELIGIBLE_TOOLS`, which neither name is in — but a denylist
|
|
65
|
+
// that names only the retired spelling is a guard whose comment describes a
|
|
66
|
+
// stronger check than its code performs.
|
|
67
|
+
export const NEVER_AUTO_ALLOW = new Set(['Bash', 'Task', 'Agent', 'WebFetch', 'WebSearch', 'shell', 'request_permissions', 'mcp_elicitation'])
|
|
68
|
+
|
|
69
|
+
// #7973 — tools an EXTERNAL PLANNER (agent-control's `chroxy_respond_permission`,
|
|
70
|
+
// packages/server/src/agent-control/client.js) may never approve with `allow`,
|
|
71
|
+
// WHATEVER the protected-path floor's `floored` verdict says about the request
|
|
72
|
+
// — these are high-authority independent of any path field:
|
|
73
|
+
// - `mcp_spawn` (#4462): an `allow` PERSISTS a permanent "trust this binary"
|
|
74
|
+
// grant to disk (byok-mcp-fleet's recordTrust). `autoAllowPending()` below
|
|
75
|
+
// already refuses to fold this into a bypass-mode sweep, via the
|
|
76
|
+
// `pending.mcpTrust` flag it sets on the pending entry — a per-REQUEST
|
|
77
|
+
// runtime marker, not a tool-name membership check. `mcp_spawn` was never
|
|
78
|
+
// added to NEVER_AUTO_ALLOW above because that set gates PERSISTED
|
|
79
|
+
// permission RULES, a mechanism `requestMcpTrust` never consults in the
|
|
80
|
+
// first place (it skips `_matchesRule` entirely).
|
|
81
|
+
// - `request_permissions` (codex's sandbox-scope escalation prompt) is
|
|
82
|
+
// already in NEVER_AUTO_ALLOW, so a persisted "always allow" RULE for it
|
|
83
|
+
// is rejected. This set additionally covers the ONE-SHOT external-planner
|
|
84
|
+
// `allow` path in agent-control, which NEVER_AUTO_ALLOW does not govern.
|
|
85
|
+
//
|
|
86
|
+
// FIXED (#7975, was FINDING #7973): `autoAllowPending()` below now consults
|
|
87
|
+
// this EXACT set (by tool name, via `_lastPermissionData`) so a pending
|
|
88
|
+
// `request_permissions` prompt — which carries neither `protectedTarget` nor
|
|
89
|
+
// `mcpTrust` — is left genuinely pending for a human rather than silently
|
|
90
|
+
// folded into a bypass-mode sweep. `mcp_spawn`'s own `pending.mcpTrust`
|
|
91
|
+
// handling (explicit deny, never silently allowed) is unchanged; the new
|
|
92
|
+
// check only ever widens which tools autoAllowPending refuses to auto-allow,
|
|
93
|
+
// checked after the mcpTrust branch so it never intercepts mcp_spawn's
|
|
94
|
+
// existing behavior.
|
|
95
|
+
//
|
|
96
|
+
// Exported so agent-control/client.js AND autoAllowPending() below both
|
|
97
|
+
// consult this EXACT Set (identity, not an equal-valued copy) rather than
|
|
98
|
+
// hand-rolling independent, driftable copies of "which tools are too
|
|
99
|
+
// high-authority for an unattended approver to ever say yes to."
|
|
100
|
+
export const NOT_DELEGABLE_TOOLS = new Set(['mcp_spawn', 'request_permissions', 'dev_preview'])
|
|
101
|
+
|
|
102
|
+
// #7973 — tools that execute an arbitrary, caller-supplied command/shell
|
|
103
|
+
// string. The protected-path floor (`isFlooredTarget`, permission-floor.js)
|
|
104
|
+
// inspects PATH-carrying input fields only — it is fundamentally unable to
|
|
105
|
+
// see a command string, so `floored: false` on one of these tools means "no
|
|
106
|
+
// path field looked protected," not "this command is safe" (`cat .env` is an
|
|
107
|
+
// ordinary, unfloored Bash invocation). Names are sourced from what each
|
|
108
|
+
// provider actually hands `handlePermission` or `POST /permission` — never
|
|
109
|
+
// guessed:
|
|
110
|
+
// - `Bash` — Claude Code (the Agent SDK's bundled binary for sdk-session.js,
|
|
111
|
+
// and the installed CLI behind the hook-routed claude-cli / claude-tui /
|
|
112
|
+
// claude-channel providers) and BYOK's built-in tool executor
|
|
113
|
+
// (byok-tool-executor.js, which dispatches by exact, case-sensitive name).
|
|
114
|
+
// - `PowerShell` — Claude Code's Windows shell tool, and the ONLY shell tool
|
|
115
|
+
// on a Windows host without Git Bash. Permission-checked with Bash's rules.
|
|
116
|
+
// - `Monitor` — Claude Code's background-script tool: its input is a bash
|
|
117
|
+
// `command`, permission-checked by the same function as Bash.
|
|
118
|
+
// - `shell` — codex's app-server driver (codex-app-server-session.js).
|
|
119
|
+
// Gemini sessions (gemini-session.js) declare `permissions: false` and never
|
|
120
|
+
// call `handlePermission` at all; ACP-backed providers (acp-session.js) deny
|
|
121
|
+
// every permission request outright without reaching this module either.
|
|
122
|
+
// This is a DENYLIST beside a tool roster that grows with every Claude Code
|
|
123
|
+
// release (PowerShell and Monitor were missed when it was first written) — a
|
|
124
|
+
// new command-executing tool is approvable until its name is added here.
|
|
125
|
+
//
|
|
126
|
+
// Exported for the same reason as NOT_DELEGABLE_TOOLS above — one shared Set,
|
|
127
|
+
// imported (not copied) by agent-control/client.js.
|
|
128
|
+
export const COMMAND_TOOLS = new Set(['Bash', 'shell', 'PowerShell', 'Monitor'])
|
|
129
|
+
|
|
130
|
+
// #7975 (S3, final security review of #7854) — the ALLOWLIST of tools an
|
|
131
|
+
// EXTERNAL PLANNER's `chroxy_respond_permission` may ever send `allow` for
|
|
132
|
+
// (before the #7973 command-tool opt-in on top): exactly the tools whose
|
|
133
|
+
// inputs the protected-path floor (`isFlooredTarget`, permission-floor.js)
|
|
134
|
+
// FULLY inspects — meaning every field of that tool's real input which
|
|
135
|
+
// selects the file(s) it reads or writes is one of PROTECTED_PATH_INPUT_FIELDS
|
|
136
|
+
// (`file_path`/`path`/`notebook_path`) or, for codex `apply_patch`, its
|
|
137
|
+
// `changes[]` member paths. `floored: false` is only a MEANINGFUL "nothing
|
|
138
|
+
// protected here" signal when that condition holds for EVERY field — not
|
|
139
|
+
// merely when the floor recognizes *some* field on the tool.
|
|
140
|
+
//
|
|
141
|
+
// Read/Write/Edit/NotebookEdit/apply_patch satisfy it: the one field the
|
|
142
|
+
// floor inspects (`file_path`/`notebook_path`/`changes[].path`) is exactly the
|
|
143
|
+
// field that determines what gets read or written.
|
|
144
|
+
//
|
|
145
|
+
// #7975-followup (adversarial review of 71e78ba38) — `Grep` and `Glob` do
|
|
146
|
+
// NOT satisfy it and are deliberately EXCLUDED, even though both are in
|
|
147
|
+
// {@link ACCEPT_EDITS_TOOLS} and both DO carry a `path` field the floor
|
|
148
|
+
// inspects. Each also carries a SECOND, file-selecting field the floor never
|
|
149
|
+
// looks at: `Grep`'s `glob` (byok-tools.js) and `Glob`'s `pattern`. A caller
|
|
150
|
+
// can leave `path` pointed at a wholly benign directory and use that second
|
|
151
|
+
// field to select a secret file directly — `isFlooredTarget` sees only the
|
|
152
|
+
// benign `path` and reports `floored: false`, exactly the vacuous-`false`
|
|
153
|
+
// failure mode #7975 was written to close, just moved one field over. Grep is
|
|
154
|
+
// the sharper case because it returns the matched file's CONTENT: measured
|
|
155
|
+
// against ripgrep 15.2.0, `rg --glob=.env -e <pattern> -- <benign-dir>`
|
|
156
|
+
// matches `.env` even WITHOUT `--hidden` — an explicit `--glob` overrides the
|
|
157
|
+
// default hidden-file/`.gitignore` skip that would otherwise protect a
|
|
158
|
+
// dotfile. So `Grep({ path: '<cwd>', glob: '.env', pattern: '.' })` returned
|
|
159
|
+
// live secret bytes while `floored` read `false`.
|
|
160
|
+
//
|
|
161
|
+
// #7978 closed that one shape: the floor now inspects Grep's `glob` and floors
|
|
162
|
+
// a glob that can select a secret (permission-floor.js, "Grep's FILE-SELECTING
|
|
163
|
+
// `glob` field"). Grep STAYS excluded, because the floor still cannot see the
|
|
164
|
+
// other half: a Grep with NO glob reads every file under `path` that the ignore
|
|
165
|
+
// rules let through, and a committed (non-gitignored) secret is one of them.
|
|
166
|
+
// `floored: false` on a Grep therefore still means "the path is not a secret",
|
|
167
|
+
// never "nothing this call reads is a secret". `Glob` shares the same
|
|
168
|
+
// blind field but can only ever return a matched PATH NAME (see its
|
|
169
|
+
// `input_schema` and description in byok-tools.js — "Returns sorted file
|
|
170
|
+
// paths"), never file bytes, so it cannot leak secret VALUES; it is excluded
|
|
171
|
+
// anyway for consistency with "meaningful for every allowlisted tool" and
|
|
172
|
+
// because listing files (unlike reading their content) is already the
|
|
173
|
+
// existing, deliberate design of the read floor itself (`isSecretReadTarget`
|
|
174
|
+
// floors a config-dir READ only when the target is a specific secret FILE,
|
|
175
|
+
// not merely because a directory containing one is being enumerated). See
|
|
176
|
+
// `tests/agent-control/permission-policy.test.js` for the bypass proof
|
|
177
|
+
// (a real `path`-benign / `glob`-malicious Grep input against
|
|
178
|
+
// `isFlooredTarget`) and `tests/built-in-tools/tool-transforms.js`'s own doc
|
|
179
|
+
// comment on `buildGrepCommand`, which already flagged this exact tension for
|
|
180
|
+
// the acceptEdits/rule-engine surface before agent-control existed.
|
|
181
|
+
//
|
|
182
|
+
// Deliberately NOT the same object as {@link ACCEPT_EDITS_TOOLS} (no more
|
|
183
|
+
// identity reuse): aliasing the planner's allowlist to the acceptEdits set
|
|
184
|
+
// meant any FUTURE widening of acceptEdits (adding a tool there because it is
|
|
185
|
+
// fine for a human clicking "accept edits" to auto-approve) would silently
|
|
186
|
+
// widen what an unattended external planner may also approve — a different,
|
|
187
|
+
// stronger bar. This Set is its own literal, a strict SUBSET of
|
|
188
|
+
// ACCEPT_EDITS_TOOLS, pinned by a behavioral test against permission-floor.js
|
|
189
|
+
// (not by comparing two hand-authored lists) that fails if a tool whose real
|
|
190
|
+
// input schema carries an uninspected file-selecting field (`glob`/`pattern`)
|
|
191
|
+
// is ever added back.
|
|
192
|
+
export const FLOOR_ALLOWLISTED_TOOLS = new Set(['Read', 'Write', 'Edit', 'NotebookEdit', 'apply_patch'])
|
|
193
|
+
|
|
194
|
+
// #7004 — back-compat re-exports. The floor moved to permission-floor.js (the
|
|
195
|
+
// single source both pipelines import); these names were exported from here since
|
|
196
|
+
// #6794/#6803, so keep them resolvable from this module for existing importers.
|
|
197
|
+
export { isProtectedPathTarget, isSecretReadTarget, PROTECTED_PATH_INPUT_FIELDS }
|
|
23
198
|
|
|
24
199
|
// Default permission timeout (5 minutes)
|
|
25
200
|
const DEFAULT_TIMEOUT_MS = 300_000
|
|
@@ -29,23 +204,45 @@ const DEFAULT_TIMEOUT_MS = 300_000
|
|
|
29
204
|
// input, where the alternative is unbounded memory/CPU growth.
|
|
30
205
|
const MAX_PENDING_PERMISSIONS = 1000 // concurrent pending requests (each holds map entries + a timer)
|
|
31
206
|
const MAX_SESSION_RULES = 100 // session-scoped auto-allow rules
|
|
32
|
-
const MAX_RAW_DESCRIPTION_LEN = 8192 // raw tool field length fed to redactValue (far above the 200-char shown window)
|
|
33
207
|
|
|
34
208
|
/**
|
|
35
|
-
* #6543 (IDE P3 feature B) — per-tool whitelist of the
|
|
36
|
-
* may substitute via `editedInput` on an `allow` (the
|
|
37
|
-
* ONLY these
|
|
38
|
-
* (`file_path`, `old_string`,
|
|
39
|
-
*
|
|
40
|
-
* where
|
|
41
|
-
*
|
|
42
|
-
*
|
|
209
|
+
* #6543 (IDE P3 feature B) / #6773 — per-tool whitelist of the field(s) a client
|
|
210
|
+
* may substitute via `editedInput` on an `allow` (the pre-approve review/edit).
|
|
211
|
+
* ONLY these fields can come from the client; the path/anchor fields
|
|
212
|
+
* (`file_path`, `old_string`, …) are always taken from the ORIGINAL input, so an
|
|
213
|
+
* operator can narrow/edit the shown content or the command but can NEVER
|
|
214
|
+
* redirect where a write lands. A tool absent from this map ignores `editedInput`
|
|
215
|
+
* entirely (accept/reject-the-whole-tool). `old_string` is deliberately NOT
|
|
216
|
+
* editable — it is the Edit's match anchor, not shown content.
|
|
217
|
+
*
|
|
218
|
+
* #6773 — `Bash: ['command']` makes the shell command text editable before
|
|
219
|
+
* approve. For Bash the WHOLE command IS the reviewed content (there is no
|
|
220
|
+
* separate path field to redirect), and Bash carries none of
|
|
221
|
+
* {@link PROTECTED_PATH_INPUT_FIELDS}, so the protected-path floor never applied
|
|
222
|
+
* to it — editing `command` therefore cannot "edit around" the floor (the floor
|
|
223
|
+
* only ever guards a path-carrying tool's path fields, and no path field is ever
|
|
224
|
+
* whitelisted here — asserted by the editedInput-whitelist guard test). The
|
|
225
|
+
* merged command still flows to the SDK/BYOK tool executor as `updatedInput`,
|
|
226
|
+
* which runs the operator-approved text.
|
|
227
|
+
*
|
|
228
|
+
* Codex's `shell` is deliberately ABSENT: the codex app-server owns and runs its
|
|
229
|
+
* own already-parsed command and ignores `updatedInput` (see
|
|
230
|
+
* codex-app-server-session.js `_routeApproval`, which reads only allow/deny), so
|
|
231
|
+
* a `shell` edit would silently not take effect — surfacing an editable field
|
|
232
|
+
* there would mislead the operator. Deferred to a codex follow-up.
|
|
43
233
|
*/
|
|
44
|
-
const EDITABLE_INPUT_FIELDS = {
|
|
234
|
+
export const EDITABLE_INPUT_FIELDS = {
|
|
45
235
|
Write: ['content'],
|
|
46
236
|
Edit: ['new_string'],
|
|
237
|
+
Bash: ['command'],
|
|
47
238
|
}
|
|
48
239
|
|
|
240
|
+
// #6773 — hard cap on the operator-supplied DENY REASON before it becomes the
|
|
241
|
+
// agent-facing tool-result message. Far above any reasonable one-liner; it only
|
|
242
|
+
// bites a pathological paste. The wire schema (PermissionResponseSchema) caps at
|
|
243
|
+
// the same ceiling — this is the server-authoritative re-cap.
|
|
244
|
+
const MAX_DENY_REASON_LEN = 2000
|
|
245
|
+
|
|
49
246
|
/**
|
|
50
247
|
* Merge a client's `editedInput` into the agent's original tool input under the
|
|
51
248
|
* strict {@link EDITABLE_INPUT_FIELDS} whitelist. Returns the original REFERENCE
|
|
@@ -55,22 +252,279 @@ const EDITABLE_INPUT_FIELDS = {
|
|
|
55
252
|
* the original by value). Never mutates the inputs. This is the load-bearing
|
|
56
253
|
* "narrow-only, no path redirect" control for feature B — keep it dumb + auditable.
|
|
57
254
|
*
|
|
255
|
+
* #8446 — what reaches the tool executor is built from `originalInput`, the RAW
|
|
256
|
+
* input held here, never from content the client saw. The client reviewed a
|
|
257
|
+
* REDACTED copy, so text it builds carries `[REDACTED]` where a secret was:
|
|
258
|
+
* - a Write/Edit whose `editedInput` has a `droppedHunks` key (an empty list
|
|
259
|
+
* included) is rebuilt here from the raw input and those ranges (see
|
|
260
|
+
* edited-input.js); any text the client also sent for that field is ignored;
|
|
261
|
+
* - any other whitelisted text (an older client's content, a Bash command) is
|
|
262
|
+
* refused when redaction changed the copy it was drawn from, whatever the text
|
|
263
|
+
* contains.
|
|
264
|
+
* Anything that goes wrong while doing this is a refusal, never a throw of another
|
|
265
|
+
* kind: the caller answers a refusal by denying the request.
|
|
266
|
+
*
|
|
58
267
|
* @param {object} originalInput the agent's proposed tool input
|
|
59
268
|
* @param {*} editedInput the client-supplied override (untrusted)
|
|
60
269
|
* @param {string} toolName the tool the permission is for
|
|
61
270
|
* @returns {object}
|
|
271
|
+
* @throws {EditedInputRefusedError} the edit cannot be applied safely; nothing has
|
|
272
|
+
* been changed
|
|
62
273
|
*/
|
|
63
274
|
export function mergeEditedInput(originalInput, editedInput, toolName) {
|
|
64
275
|
if (!editedInput || typeof editedInput !== 'object' || Array.isArray(editedInput)) return originalInput
|
|
65
276
|
const allowed = EDITABLE_INPUT_FIELDS[toolName]
|
|
66
277
|
if (!allowed) return originalInput
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
278
|
+
try {
|
|
279
|
+
const merged = { ...originalInput }
|
|
280
|
+
// The key being present puts the field in hunk mode, an empty list included.
|
|
281
|
+
const hunkMode = isHunkReviewedTool(toolName)
|
|
282
|
+
&& Object.prototype.hasOwnProperty.call(editedInput, DROPPED_HUNKS_KEY)
|
|
283
|
+
if (hunkMode) merged[allowed[0]] = narrowByDroppedHunks(originalInput, toolName, editedInput[DROPPED_HUNKS_KEY], editedInput[KEPT_HUNKS_KEY])
|
|
284
|
+
for (const field of allowed) {
|
|
285
|
+
if (hunkMode && field === allowed[0]) continue
|
|
286
|
+
if (Object.prototype.hasOwnProperty.call(editedInput, field) && typeof editedInput[field] === 'string') {
|
|
287
|
+
assertClientTextAllowed(originalInput, toolName, field)
|
|
288
|
+
merged[field] = editedInput[field]
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return merged
|
|
292
|
+
} catch (err) {
|
|
293
|
+
if (err instanceof EditedInputRefusedError) throw err
|
|
294
|
+
throw new EditedInputRefusedError('This edit could not be applied, so the request was denied.')
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* #6773 — build the agent-facing DENY message from an optional operator reason.
|
|
300
|
+
* A deny used to always resolve as the fixed `'User denied'` string, so nothing
|
|
301
|
+
* the operator typed reached the agent. When a non-empty reason is supplied it
|
|
302
|
+
* REPLACES that string (verbatim, so the model reads the operator's intent as
|
|
303
|
+
* the refusal reason and can adjust its next attempt — desktop-app "tell Claude
|
|
304
|
+
* what to do differently" parity). Bounded ({@link MAX_DENY_REASON_LEN}) and
|
|
305
|
+
* redacted (same {@link redactValue} pass every other freeform field entering
|
|
306
|
+
* the broadcast/agent stream gets, so an operator can't accidentally leak a
|
|
307
|
+
* secret into the streamed tool result). Falls back to `'User denied'` for a
|
|
308
|
+
* missing / non-string / blank reason.
|
|
309
|
+
* @param {*} reason the operator-supplied deny reason (untrusted)
|
|
310
|
+
* @returns {string}
|
|
311
|
+
*/
|
|
312
|
+
export function buildDenyMessage(reason) {
|
|
313
|
+
if (typeof reason !== 'string') return 'User denied'
|
|
314
|
+
const trimmed = reason.trim()
|
|
315
|
+
if (trimmed.length === 0) return 'User denied'
|
|
316
|
+
return redactValue(trimmed.slice(0, MAX_DENY_REASON_LEN))
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Tools whose single path-carrying input field a scoped rule reads. Glob and
|
|
322
|
+
* Grep are handled separately: they search from an effective root.
|
|
323
|
+
*/
|
|
324
|
+
const SCOPED_RULE_PATH_FIELD = {
|
|
325
|
+
Read: 'file_path',
|
|
326
|
+
Write: 'file_path',
|
|
327
|
+
Edit: 'file_path',
|
|
328
|
+
MultiEdit: 'file_path',
|
|
329
|
+
NotebookEdit: 'notebook_path',
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** Does a Glob pattern select files outside its search root? */
|
|
333
|
+
function _globPatternLeavesRoot(pattern) {
|
|
334
|
+
if (typeof pattern !== 'string') return false
|
|
335
|
+
// The whitespace rule only concerns how a container splits a pattern; a space
|
|
336
|
+
// does not make a pattern leave its root. An unquoted space starts a new word,
|
|
337
|
+
// so judge each word by turning whitespace into a comma: that is both a
|
|
338
|
+
// word-start anchor and a segment delimiter for the other rules.
|
|
339
|
+
const reason = globPatternEscapeReason(pattern.replace(/\s/g, ','))
|
|
340
|
+
return reason !== null || isAbsolute(pattern) || /^[/\\]/.test(pattern)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** A path starting with `~` may be expanded to a home directory, so it names no fixed target. */
|
|
344
|
+
function _startsWithHomeMarker(value) {
|
|
345
|
+
return /^~/.test(value)
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* #6803 — collect every concrete target path a tool call names, for the
|
|
350
|
+
* rule-scope test. Tool-aware: Read/Write/Edit use `file_path`, NotebookEdit uses
|
|
351
|
+
* `notebook_path`, Glob/Grep search from their effective root (`path`, else the
|
|
352
|
+
* session cwd; a Glob pattern that is absolute, climbs with `..` or expands
|
|
353
|
+
* through `~` or braces to such a path selects files outside it), and
|
|
354
|
+
* `apply_patch` uses every `changes` path and rename destination plus the
|
|
355
|
+
* approval's top-level `file_path` (the root the approval grants writes under),
|
|
356
|
+
* requiring a complete change list. Other fields are ignored.
|
|
357
|
+
*
|
|
358
|
+
* Returns null when the call names no usable target set: a command-shaped tool,
|
|
359
|
+
* a malformed or incomplete patch, a missing path, a `~`-prefixed path, or a
|
|
360
|
+
* Glob pattern that leaves its root. A rule that grants (allow) does not match
|
|
361
|
+
* such a call; a rule that refuses (deny) does.
|
|
362
|
+
* @param {string} toolName
|
|
363
|
+
* @param {object} input
|
|
364
|
+
* @returns {string[]|null}
|
|
365
|
+
*/
|
|
366
|
+
function collectTargetPaths(toolName, input) {
|
|
367
|
+
const targets = _collectTargets(toolName, input)
|
|
368
|
+
if (targets === null || targets.length === 0) return null
|
|
369
|
+
return targets.some(_startsWithHomeMarker) ? null : targets
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function _collectTargets(toolName, input) {
|
|
373
|
+
if (!input || typeof input !== 'object') return null
|
|
374
|
+
if (toolName === 'apply_patch') {
|
|
375
|
+
const { complete, paths } = collectChangeTargets(input.changes)
|
|
376
|
+
if (!complete) return null
|
|
377
|
+
const root = input.file_path
|
|
378
|
+
if (root !== undefined && root !== null) {
|
|
379
|
+
if (typeof root !== 'string') return null
|
|
380
|
+
if (root.length > 0) paths.push(root)
|
|
381
|
+
}
|
|
382
|
+
return paths
|
|
383
|
+
}
|
|
384
|
+
if (toolName === 'Glob' || toolName === 'Grep') {
|
|
385
|
+
if (toolName === 'Glob' && _globPatternLeavesRoot(input.pattern)) return null
|
|
386
|
+
const root = effectiveSearchRoot(input)
|
|
387
|
+
return root === null ? null : [root]
|
|
388
|
+
}
|
|
389
|
+
const field = SCOPED_RULE_PATH_FIELD[toolName]
|
|
390
|
+
if (field === undefined) return null
|
|
391
|
+
const value = input[field]
|
|
392
|
+
return typeof value === 'string' && value.length > 0 ? [value] : null
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// #6803 — a scope string is a GLOB (vs a plain directory prefix) when it carries
|
|
396
|
+
// a wildcard metachar (`*` or `?`). Globs match path-shaped; prefixes match "at
|
|
397
|
+
// or under this directory". Only `*` / `**` / `?` are supported — NOT character
|
|
398
|
+
// classes, so a scope containing `[`/`]` is a literal directory prefix, not a
|
|
399
|
+
// class (globToRegExp would escape the brackets anyway).
|
|
400
|
+
function _scopeHasGlobMagic(scope) {
|
|
401
|
+
return /[*?]/.test(scope)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* #6803 — compile a rule-scope GLOB to an anchored RegExp. Dependency-free
|
|
406
|
+
* (the existing floor is pure string ops; a scope glob shouldn't drag in
|
|
407
|
+
* minimatch). Semantics, POSIX `/`-separated:
|
|
408
|
+
* - `**` → any run of characters INCLUDING separators (crosses directories)
|
|
409
|
+
* - `**` + `/` → the same, with the trailing `/` optional so `**/x` also
|
|
410
|
+
* matches a bare `x`
|
|
411
|
+
* - `*` → any run of NON-separator characters (one path segment)
|
|
412
|
+
* - `?` → a single non-separator character
|
|
413
|
+
* Only these wildcards are supported — NOT character classes: `[`/`]` (and every
|
|
414
|
+
* other regex metachar) are ESCAPED and matched literally.
|
|
415
|
+
* @param {string} glob
|
|
416
|
+
* @returns {RegExp}
|
|
417
|
+
*/
|
|
418
|
+
function globToRegExp(glob) {
|
|
419
|
+
let re = ''
|
|
420
|
+
for (let i = 0; i < glob.length; i++) {
|
|
421
|
+
const c = glob[i]
|
|
422
|
+
if (c === '*' && glob[i + 1] === '*') {
|
|
423
|
+
if (glob[i + 2] === '/') { re += '(?:.*/)?'; i += 2 } // `**/` → optional dir prefix
|
|
424
|
+
else { re += '.*'; i += 1 } // bare `**`
|
|
425
|
+
continue
|
|
426
|
+
}
|
|
427
|
+
if (c === '*') { re += '[^/]*'; continue }
|
|
428
|
+
if (c === '?') { re += '[^/]'; continue }
|
|
429
|
+
re += c.replace(/[.+^${}()|[\]\\/]/g, '\\$&')
|
|
430
|
+
}
|
|
431
|
+
return new RegExp('^' + re + '$')
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* #6803 — is `target` inside the rule `scope`, both resolved against `base`
|
|
436
|
+
* (the session cwd)? A GLOB scope is matched against the target's cwd-relative,
|
|
437
|
+
* POSIX-normalized path; a plain scope is a DIRECTORY PREFIX (target is at or
|
|
438
|
+
* under the resolved scope dir). Used by _ruleScopeMatches — a scoped rule only
|
|
439
|
+
* auto-decides a tool call whose targets all fall within scope.
|
|
440
|
+
* @param {string} target a tool-input path value
|
|
441
|
+
* @param {string} scope the rule's `path` scope
|
|
442
|
+
* @param {string} base the session cwd
|
|
443
|
+
* @returns {boolean}
|
|
444
|
+
*/
|
|
445
|
+
function pathWithinScope(target, scope, base) {
|
|
446
|
+
return lexicallyWithinScope(target, scope, base) && realLocationWithinScope(target, scope, base)
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** The path-text half of {@link pathWithinScope}: resolve()/relative() only. */
|
|
450
|
+
function lexicallyWithinScope(target, scope, base) {
|
|
451
|
+
const resolvedTarget = resolve(base, target)
|
|
452
|
+
if (_scopeHasGlobMagic(scope)) {
|
|
453
|
+
// PR #6873 review — a glob scope must NEVER reach ABOVE the session cwd:
|
|
454
|
+
// `**/*.js` must not match `../evil.js`, `**` must not match `/etc/passwd`.
|
|
455
|
+
// Reject an escaping target FIRST (same under-base guard the prefix branch
|
|
456
|
+
// uses), THEN glob-match the under-base relative path. Without this the glob
|
|
457
|
+
// ran against `relative(base, target)` unchecked, so `..`/absolute targets
|
|
458
|
+
// supplied via set_permission_rules could be auto-approved out of scope.
|
|
459
|
+
const rel = relative(base, resolvedTarget)
|
|
460
|
+
if (isAbsolute(rel) || rel === '..' || rel.startsWith('..' + sep)) return false
|
|
461
|
+
return globToRegExp(scope).test(rel.split(sep).join('/'))
|
|
462
|
+
}
|
|
463
|
+
const resolvedScope = resolve(base, scope)
|
|
464
|
+
const rel = relative(resolvedScope, resolvedTarget)
|
|
465
|
+
// At the scope dir itself (rel === '') or under it (not `..`, not absolute).
|
|
466
|
+
return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + sep))
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* The filesystem half of {@link pathWithinScope}: a path-scoped rule matches
|
|
471
|
+
* only when the target's real location is inside the scope, as the permission
|
|
472
|
+
* floor already does. The base is resolved with realpath, the target and a
|
|
473
|
+
* plain scope are walked component by component (symlinks followed, a missing
|
|
474
|
+
* tail applied lexically), then compared. A glob scope also requires the real
|
|
475
|
+
* location to be under the real base and to satisfy the glob on its path
|
|
476
|
+
* relative to the real base. Any resolution error means no match.
|
|
477
|
+
*/
|
|
478
|
+
function realLocationWithinScope(target, scope, base, onError = false) {
|
|
479
|
+
try {
|
|
480
|
+
const realBase = realpathSync(base)
|
|
481
|
+
const realTarget = resolveTargetComponentwiseSync(realBase, target)
|
|
482
|
+
if (_scopeHasGlobMagic(scope)) {
|
|
483
|
+
if (!isPathWithin(realTarget, realBase)) return false
|
|
484
|
+
// The directory named before the first wildcard may itself be a link, so
|
|
485
|
+
// resolve it and match the glob against the target's path below it, as
|
|
486
|
+
// if the target were reached through the prefix's written spelling.
|
|
487
|
+
const head = scope.slice(0, scope.search(/[*?]/))
|
|
488
|
+
const prefix = head.slice(0, Math.max(head.lastIndexOf('/'), 0))
|
|
489
|
+
const written = relative(base, resolve(base, prefix)).split(sep).join('/')
|
|
490
|
+
const realPrefix = resolveTargetComponentwiseSync(realBase, prefix === '' ? '.' : prefix)
|
|
491
|
+
if (!isPathWithin(realTarget, realPrefix)) return false
|
|
492
|
+
const below = relative(realPrefix, realTarget).split(sep).join('/')
|
|
493
|
+
const through = written === '' ? below : below === '' ? written : `${written}/${below}`
|
|
494
|
+
return globToRegExp(scope).test(through)
|
|
71
495
|
}
|
|
496
|
+
const realScope = resolveTargetComponentwiseSync(realBase, scope)
|
|
497
|
+
return isPathWithin(realTarget, realScope)
|
|
498
|
+
} catch {
|
|
499
|
+
return onError
|
|
72
500
|
}
|
|
73
|
-
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* #6803 — normalize a rule to the stored shape `{ tool, decision }`, carrying an
|
|
505
|
+
* optional `path` scope ONLY when it is a non-empty string. Keeping `path` off
|
|
506
|
+
* the object entirely when unscoped means unscoped rules stay deepEqual to a
|
|
507
|
+
* plain `{ tool, decision }` (the shape every existing test/consumer asserts).
|
|
508
|
+
* @param {{tool: string, decision: string, path?: string}} rule
|
|
509
|
+
* @returns {{tool: string, decision: string, path?: string}}
|
|
510
|
+
*/
|
|
511
|
+
function normalizeStoredRule(rule) {
|
|
512
|
+
const out = { tool: rule.tool, decision: rule.decision }
|
|
513
|
+
if (typeof rule.path === 'string' && rule.path.length > 0) out.path = rule.path
|
|
514
|
+
return out
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* #8430: a prompt or question the user's Stop resolved carries the provider's id
|
|
519
|
+
* for the tool call, so the session can mark that tool row stopped. Only for a
|
|
520
|
+
* `stopped` resolution: a Deny, a timeout or a rule decision made in the same
|
|
521
|
+
* window must keep its own row. The event normalizer picks its wire fields, so this never
|
|
522
|
+
* reaches a client.
|
|
523
|
+
*/
|
|
524
|
+
function stoppedToolUseField(reason, toolUseId) {
|
|
525
|
+
return reason === 'stopped' && typeof toolUseId === 'string' && toolUseId.length > 0
|
|
526
|
+
? { sourceToolUseId: toolUseId }
|
|
527
|
+
: {}
|
|
74
528
|
}
|
|
75
529
|
|
|
76
530
|
/**
|
|
@@ -89,17 +543,45 @@ export function mergeEditedInput(originalInput, editedInput, toolName) {
|
|
|
89
543
|
* user_question { toolUseId, questions }
|
|
90
544
|
*/
|
|
91
545
|
export class PermissionManager extends EventEmitter {
|
|
92
|
-
constructor({ timeoutMs, log, maxPendingPermissions } = {}) {
|
|
546
|
+
constructor({ timeoutMs, log, maxPendingPermissions, cwd, ruleStore, mcpTrustLookup } = {}) {
|
|
93
547
|
super()
|
|
94
548
|
this._timeoutMs = timeoutMs || DEFAULT_TIMEOUT_MS
|
|
95
549
|
this._log = log || console
|
|
550
|
+
// #6834 — injectable DNS resolver for the MCP-trust prompt's resolved-address
|
|
551
|
+
// display. Defaults to node:dns/promises lookup (via resolveTrustAddress)
|
|
552
|
+
// when unset; tests pass a fake so they never touch real DNS.
|
|
553
|
+
this._mcpTrustLookup = typeof mcpTrustLookup === 'function' ? mcpTrustLookup : null
|
|
96
554
|
// #6448 — bound on concurrent pending permissions; injectable so the cap is
|
|
97
555
|
// testable without minting 1000 real requests.
|
|
98
556
|
this._maxPendingPermissions = maxPendingPermissions || MAX_PENDING_PERMISSIONS
|
|
557
|
+
// #6794 — session cwd anchors the protected-path floor (see
|
|
558
|
+
// isProtectedPathTarget). Optional: when unset the floor resolves targets
|
|
559
|
+
// against process.cwd(), which still catches relative protected paths.
|
|
560
|
+
this._cwd = (typeof cwd === 'string' && cwd.length > 0) ? cwd : null
|
|
561
|
+
// #6771 — durable per-project rule store (PermissionRuleStore). Optional:
|
|
562
|
+
// when present, an `allowAlways` decision persists a rule keyed by this
|
|
563
|
+
// session's cwd, and this session seeds its persistent rules from the store
|
|
564
|
+
// on construction (below) so a prior grant takes effect without re-prompting
|
|
565
|
+
// after a daemon restart.
|
|
566
|
+
this._ruleStore = ruleStore || null
|
|
567
|
+
// #6830 (PR #6842 review) — direct audit callback for persisted-rule
|
|
568
|
+
// auto-approves. Deliberately NOT an EventEmitter event: emitting
|
|
569
|
+
// `permission_resolved` here would ride wirePermissionManager →
|
|
570
|
+
// SessionManager → ws-forwarding → broadcastToSession, spamming every
|
|
571
|
+
// subscribed client with a wire message per rule-matched tool call. The
|
|
572
|
+
// sink is a plain function the WsServer wires straight into its
|
|
573
|
+
// PermissionAuditLog (see ws-server.js _attachPermissionAuditSink), so
|
|
574
|
+
// the signal stays in the audit lane only. Null until wired.
|
|
575
|
+
this._auditSink = null
|
|
99
576
|
|
|
100
577
|
this._pendingPermissions = new Map() // requestId -> { resolve, input }
|
|
101
578
|
this._permissionTimers = new Map() // requestId -> timer
|
|
102
579
|
this._permissionCounter = 0
|
|
580
|
+
// #8430: the user pressed Stop on the turn that is running. Turn-scoped, set
|
|
581
|
+
// by `markUserStopInFlight()` and cleared by `clearUserStopInFlight()` at turn
|
|
582
|
+
// end. The abort listener reads it, so a prompt raised AFTER the Stop but
|
|
583
|
+
// before the provider's abort lands is a Stop's too.
|
|
584
|
+
this._userStopInFlight = false
|
|
103
585
|
// Per-instance (per-session) nonce so requestIds are globally unique
|
|
104
586
|
// across sessions. Without it the id was `perm-${counter}-${ms}` with a
|
|
105
587
|
// counter that restarts at 0 every session — two sessions could mint the
|
|
@@ -114,7 +596,16 @@ export class PermissionManager extends EventEmitter {
|
|
|
114
596
|
this._lastPermissionData = new Map() // requestId -> emitted permission_request payload
|
|
115
597
|
|
|
116
598
|
// Session-scoped permission rules
|
|
117
|
-
this._sessionRules = [] // [{ tool, decision }]
|
|
599
|
+
this._sessionRules = [] // [{ tool, decision, path? }] — path = #6803 optional scope
|
|
600
|
+
|
|
601
|
+
// #6771 — durable per-project rules seeded from the store for THIS
|
|
602
|
+
// session's cwd. Kept SEPARATE from `_sessionRules` so `setRules`/
|
|
603
|
+
// `clearRules` (the session-scoped `set_permission_rules` path, and the
|
|
604
|
+
// clearRules() on a permission-mode switch) never wipe a project-level
|
|
605
|
+
// "always allow", and vice-versa. `_matchesRule` consults both.
|
|
606
|
+
this._persistentRules = (this._ruleStore && this._cwd)
|
|
607
|
+
? this._ruleStore.getRules(this._cwd)
|
|
608
|
+
: []
|
|
118
609
|
|
|
119
610
|
// AskUserQuestion handling
|
|
120
611
|
this._pendingUserAnswer = null // { resolve, input, toolUseId } when waiting for user answer
|
|
@@ -125,9 +616,12 @@ export class PermissionManager extends EventEmitter {
|
|
|
125
616
|
/**
|
|
126
617
|
* Set session-scoped permission rules.
|
|
127
618
|
* 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.
|
|
619
|
+
* Rules for NEVER_AUTO_ALLOW tools are rejected with an error. #6803 — a rule
|
|
620
|
+
* may carry an optional `path` SCOPE (a non-empty string); the stored rule
|
|
621
|
+
* preserves it and {@link _matchesRule} only matches a scoped rule when the
|
|
622
|
+
* tool's target paths fall within it.
|
|
129
623
|
*
|
|
130
|
-
* @param {Array<{tool: string, decision: string}>} rules
|
|
624
|
+
* @param {Array<{tool: string, decision: string, path?: string}>} rules
|
|
131
625
|
* @throws {Error} if any rule is invalid
|
|
132
626
|
*/
|
|
133
627
|
setRules(rules) {
|
|
@@ -151,41 +645,185 @@ export class PermissionManager extends EventEmitter {
|
|
|
151
645
|
if (!ELIGIBLE_TOOLS.has(rule.tool)) {
|
|
152
646
|
throw new Error(`${rule.tool} is not in ELIGIBLE_TOOLS`)
|
|
153
647
|
}
|
|
648
|
+
if (rule.path !== undefined && (typeof rule.path !== 'string' || rule.path.length === 0)) {
|
|
649
|
+
throw new Error('rule path scope must be a non-empty string')
|
|
650
|
+
}
|
|
154
651
|
}
|
|
155
|
-
|
|
652
|
+
// #6803 — normalize to the stored shape, carrying `path` only when present so
|
|
653
|
+
// an unscoped rule stays a plain { tool, decision } (deepEqual-friendly).
|
|
654
|
+
this._sessionRules = rules.map(normalizeStoredRule)
|
|
156
655
|
}
|
|
157
656
|
|
|
158
657
|
/**
|
|
159
|
-
* Return a copy of the current session rules
|
|
658
|
+
* Return a copy of the current session rules (each rule object cloned so a
|
|
659
|
+
* caller can't mutate the internal set; #6803 — carries `path` when scoped).
|
|
160
660
|
*
|
|
161
|
-
* @returns {Array<{tool: string, decision: string}>}
|
|
661
|
+
* @returns {Array<{tool: string, decision: string, path?: string}>}
|
|
162
662
|
*/
|
|
163
663
|
getRules() {
|
|
164
|
-
return this._sessionRules.
|
|
664
|
+
return this._sessionRules.map(normalizeStoredRule)
|
|
165
665
|
}
|
|
166
666
|
|
|
167
667
|
/**
|
|
168
|
-
* Clear all session-scoped permission rules.
|
|
668
|
+
* Clear all session-scoped permission rules. Persistent (project-scoped)
|
|
669
|
+
* rules are UNTOUCHED — a mode switch or a `set_permission_rules []` must not
|
|
670
|
+
* silently revoke a durable "always allow" (#6771).
|
|
169
671
|
*/
|
|
170
672
|
clearRules() {
|
|
171
673
|
this._sessionRules = []
|
|
172
674
|
}
|
|
173
675
|
|
|
174
676
|
/**
|
|
175
|
-
*
|
|
677
|
+
* Return a copy of the durable (project-scoped) rules currently applied to
|
|
678
|
+
* this session, each tagged `persist: 'project'` so a client can render them
|
|
679
|
+
* distinctly from session rules (#6771).
|
|
680
|
+
*
|
|
681
|
+
* @returns {Array<{tool: string, decision: string, persist: 'project'}>}
|
|
682
|
+
*/
|
|
683
|
+
getPersistentRules() {
|
|
684
|
+
return this._persistentRules.map((r) => {
|
|
685
|
+
const out = { tool: r.tool, decision: r.decision, persist: 'project' }
|
|
686
|
+
if (typeof r.path === 'string' && r.path.length > 0) out.path = r.path
|
|
687
|
+
return out
|
|
688
|
+
})
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Replace this session's durable rule set in memory (does NOT persist —
|
|
693
|
+
* callers that own the store persist separately). Used to re-seed after the
|
|
694
|
+
* store changes out-of-band (e.g. a client edited the project's rules).
|
|
695
|
+
*
|
|
696
|
+
* @param {Array<{tool: string, decision: string}>} rules
|
|
697
|
+
*/
|
|
698
|
+
setPersistentRules(rules) {
|
|
699
|
+
this._persistentRules = Array.isArray(rules)
|
|
700
|
+
? rules
|
|
701
|
+
.filter((r) => r && typeof r.tool === 'string' && (r.decision === 'allow' || r.decision === 'deny'))
|
|
702
|
+
.map(normalizeStoredRule) // #6803 — preserve an optional `path` scope
|
|
703
|
+
: []
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/**
|
|
707
|
+
* #6803 — does this rule's optional `path` SCOPE admit `input`? An UNSCOPED
|
|
708
|
+
* rule (no `path`) matches every input, exactly as before. For a SCOPED rule:
|
|
709
|
+
* an allow rule matches only when the input names at least one target and
|
|
710
|
+
* EVERY target is within the scope (resolved against the session cwd); a deny
|
|
711
|
+
* rule matches when ANY target is within the scope, or when the targets cannot
|
|
712
|
+
* be determined. So a scoped `allow` never auto-approves an out-of-scope
|
|
713
|
+
* target, and an input with no path never matches a scoped allow and falls
|
|
714
|
+
* through to a prompt.
|
|
715
|
+
* @param {{tool: string, decision: string, path?: string}} rule
|
|
716
|
+
* @param {object} [input]
|
|
717
|
+
* @returns {boolean}
|
|
718
|
+
*/
|
|
719
|
+
_ruleScopeMatches(rule, input) {
|
|
720
|
+
if (typeof rule.path !== 'string' || rule.path.length === 0) return true
|
|
721
|
+
const targets = collectTargetPaths(rule.tool, input)
|
|
722
|
+
const base = this._cwd || process.cwd()
|
|
723
|
+
if (rule.decision === 'deny') {
|
|
724
|
+
// A refusal matches when ANY target is inside the scope by its path text or
|
|
725
|
+
// by its real location, and when the targets cannot be determined.
|
|
726
|
+
if (targets === null) return true
|
|
727
|
+
return targets.some((t) => lexicallyWithinScope(t, rule.path, base) || realLocationWithinScope(t, rule.path, base, true))
|
|
728
|
+
}
|
|
729
|
+
if (targets === null) return false
|
|
730
|
+
return targets.every((t) => pathWithinScope(t, rule.path, base))
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Check whether a tool call matches a session or persistent rule. Session
|
|
735
|
+
* rules are consulted FIRST (a live, intentional session decision wins over a
|
|
736
|
+
* standing project grant), then the durable project rules (#6771). #6803 — a
|
|
737
|
+
* rule with a `path` scope only matches when the tool's target paths fall
|
|
738
|
+
* within it (see {@link _ruleScopeMatches}); `input` is optional, so a bare
|
|
739
|
+
* `_matchesRule(tool)` still resolves unscoped rules unchanged.
|
|
176
740
|
*
|
|
177
741
|
* @param {string} toolName
|
|
742
|
+
* @param {object} [input] the tool input (for path-scope matching)
|
|
178
743
|
* @returns {'allow'|'deny'|null} null if no rule matches
|
|
179
744
|
*/
|
|
180
|
-
_matchesRule(toolName) {
|
|
745
|
+
_matchesRule(toolName, input) {
|
|
181
746
|
for (const rule of this._sessionRules) {
|
|
182
|
-
if (rule.tool === toolName) {
|
|
747
|
+
if (rule.tool === toolName && this._ruleScopeMatches(rule, input)) {
|
|
748
|
+
return rule.decision
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
for (const rule of this._persistentRules) {
|
|
752
|
+
if (rule.tool === toolName && this._ruleScopeMatches(rule, input)) {
|
|
183
753
|
return rule.decision
|
|
184
754
|
}
|
|
185
755
|
}
|
|
186
756
|
return null
|
|
187
757
|
}
|
|
188
758
|
|
|
759
|
+
/**
|
|
760
|
+
* #6830 — was the 'allow' decision _matchesRule just returned for `toolName`
|
|
761
|
+
* SOURCED from a durable project-scoped rule (as opposed to a session rule)?
|
|
762
|
+
* Mirrors _matchesRule's own precedence (session rules are checked first and
|
|
763
|
+
* shadow a persistent rule for the same tool) WITHOUT changing _matchesRule's
|
|
764
|
+
* tested return contract (a plain 'allow'|'deny'|null string, asserted
|
|
765
|
+
* directly in permission-manager.test.js). Used only to decide whether a
|
|
766
|
+
* silent auto-approve needs an audit-only signal (see
|
|
767
|
+
* _auditPersistedRuleAutoApprove) — a session-rule-sourced allow is an
|
|
768
|
+
* explicit, non-durable decision the user already made this session and
|
|
769
|
+
* needs no extra trail beyond what's already logged for it.
|
|
770
|
+
* #6803 — mirrors _matchesRule's scope filter too: a session rule only shadows
|
|
771
|
+
* when it actually MATCHES this input (scope included), and the persistent
|
|
772
|
+
* source must be a scope-matching allow.
|
|
773
|
+
* @param {string} toolName
|
|
774
|
+
* @param {object} [input]
|
|
775
|
+
* @returns {boolean}
|
|
776
|
+
*/
|
|
777
|
+
_persistentRuleSourced(toolName, input) {
|
|
778
|
+
if (this._sessionRules.some((r) => r.tool === toolName && this._ruleScopeMatches(r, input))) return false
|
|
779
|
+
return this._persistentRules.some((r) => r.tool === toolName && r.decision === 'allow' && this._ruleScopeMatches(r, input))
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/**
|
|
783
|
+
* #6830 (PR #6842 review) — install the direct audit callback for
|
|
784
|
+
* persisted-rule auto-approves. Single-slot (last writer wins — one
|
|
785
|
+
* WsServer audits at a time); pass null/non-function to detach.
|
|
786
|
+
* `projectKey` arrives pre-NORMALIZED (normalizeProjectKey — the
|
|
787
|
+
* PermissionRuleStore key), or null for an unkeyable cwd.
|
|
788
|
+
* @param {null|((info: {tool: string, projectKey: string|null}) => void)} sink
|
|
789
|
+
*/
|
|
790
|
+
setAuditSink(sink) {
|
|
791
|
+
this._auditSink = typeof sink === 'function' ? sink : null
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* #6830 — audit-only signal for a persisted (project-scoped) rule silently
|
|
796
|
+
* auto-approving `toolName` with NO visible prompt: handlePermission
|
|
797
|
+
* short-circuits BEFORE minting a requestId or emitting permission_request,
|
|
798
|
+
* so without this the audit log has ZERO trace of the tool call — an
|
|
799
|
+
* auditor querying permission history can't answer "why did tool X
|
|
800
|
+
* auto-approve after a restart?" from the log alone.
|
|
801
|
+
*
|
|
802
|
+
* PR #6842 review — this must NOT emit `permission_resolved` (or any other
|
|
803
|
+
* session event): permission_resolved is a broadcast-lane event
|
|
804
|
+
* (session-manager.js builtinTransient → ws-forwarding →
|
|
805
|
+
* broadcastToSession), so an emission here would send a wire message to
|
|
806
|
+
* every subscribed client on EVERY rule-matched tool call, at machine
|
|
807
|
+
* speed. Instead it calls the WsServer-wired `_auditSink` directly — the
|
|
808
|
+
* audit lane only, coalesced ring-side by
|
|
809
|
+
* PermissionAuditLog.logPersistedRuleApproval. Guarded so a sink bug can
|
|
810
|
+
* never break tool approval; a no-op when no server has wired a sink.
|
|
811
|
+
* @param {string} toolName
|
|
812
|
+
*/
|
|
813
|
+
_auditPersistedRuleAutoApprove(toolName) {
|
|
814
|
+
if (!this._auditSink) return
|
|
815
|
+
try {
|
|
816
|
+
// #6842 review (Copilot) — projectKey is the store's NORMALIZED key
|
|
817
|
+
// (normalizeProjectKey, the same helper every PermissionRuleStore
|
|
818
|
+
// read/write path uses), NOT the raw session cwd: a relative or
|
|
819
|
+
// `..`-laden cwd would otherwise stamp entries an auditor can never
|
|
820
|
+
// match against the persisted rule's key in permission-rules.json.
|
|
821
|
+
this._auditSink({ tool: toolName, projectKey: normalizeProjectKey(this._cwd) })
|
|
822
|
+
} catch (err) {
|
|
823
|
+
this._logWarn(`Permission audit sink threw: ${err?.message || err}`)
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
189
827
|
/**
|
|
190
828
|
* Handle a permission check from the SDK canUseTool callback.
|
|
191
829
|
*
|
|
@@ -203,36 +841,79 @@ export class PermissionManager extends EventEmitter {
|
|
|
203
841
|
* echo back via `updatedPermissions` when the user picks "allow
|
|
204
842
|
* always". Per the Agent SDK 'Always allow' flow, these are the
|
|
205
843
|
* correct shape of rule to persist for this tool in this session.
|
|
844
|
+
* @param {string} [sourceToolUseId] - #8336: the PROVIDER's id for this
|
|
845
|
+
* tool call (the SDK's `toolUseID`, BYOK's `block.id`) -- the id its
|
|
846
|
+
* `tool_start` is recorded under. Only AskUserQuestion reads it.
|
|
206
847
|
* @returns {Promise<{behavior: string, updatedInput?: Object, message?: string, updatedPermissions?: Array}>}
|
|
207
848
|
*/
|
|
208
|
-
handlePermission(toolName, input, signal, permissionMode, suggestions = undefined) {
|
|
849
|
+
handlePermission(toolName, input, signal, permissionMode, suggestions = undefined, sourceToolUseId = undefined) {
|
|
850
|
+
if (toolName === 'dev_preview') return Promise.resolve({ behavior: 'deny', message: 'Preview publication requires a client-bound explicit consent request' })
|
|
209
851
|
if (toolName === 'AskUserQuestion') {
|
|
210
|
-
return this._handleAskUserQuestion(input, signal)
|
|
852
|
+
return this._handleAskUserQuestion(input, signal, sourceToolUseId)
|
|
211
853
|
}
|
|
212
854
|
|
|
855
|
+
// #6794 — protected-path floor. A path-carrying tool aimed at a protected
|
|
856
|
+
// path (.git/.claude/.vscode/.config/git/.env*) must NOT be silently
|
|
857
|
+
// auto-approved by auto mode, a broad `allow` rule, or acceptEdits — mirror
|
|
858
|
+
// Claude Code's "always ask" floor and let it fall through to the prompt.
|
|
859
|
+
// This is a FLOOR, not a hard deny: a lenient mode simply stops
|
|
860
|
+
// short-circuiting for these paths. A `deny` rule still denies (the floor
|
|
861
|
+
// never widens access), and if the prompt path then auto-denies on
|
|
862
|
+
// no-client/timeout, that is the existing fail-closed behavior.
|
|
863
|
+
//
|
|
864
|
+
// #6803 — the floor is TOOL-AWARE. A non-mutating read (Read/Glob/Grep) is
|
|
865
|
+
// floored ONLY on secret files (env + key material) via isSecretReadTarget —
|
|
866
|
+
// reading a config dir is benign and must stay un-prompted. Every other
|
|
867
|
+
// (mutating / unknown) tool gets the full config-dir + secret write floor.
|
|
868
|
+
//
|
|
869
|
+
// #7004 — that tool-aware choice IS isFlooredTarget (permission-floor.js),
|
|
870
|
+
// the one predicate the HOOK path (`POST /permission-floor`) calls too, so
|
|
871
|
+
// both pipelines cannot drift on which tool gets which floor.
|
|
872
|
+
const protectedTarget = isFlooredTarget(toolName, input, this._cwd)
|
|
873
|
+
|
|
213
874
|
// 'auto' (= SDK bypassPermissions) short-circuit: approve every tool
|
|
214
875
|
// call without consulting rules or emitting a prompt. SdkSession also
|
|
215
876
|
// skips canUseTool registration when starting a turn in auto mode, but
|
|
216
877
|
// a turn that started in another mode keeps its callback alive for the
|
|
217
878
|
// whole turn — without this guard, flipping to auto mid-turn (#3729)
|
|
218
879
|
// still emits prompts because session rules and the prompt path run
|
|
219
|
-
// before any mode check.
|
|
220
|
-
|
|
880
|
+
// before any mode check. #6794: the floor takes precedence — a protected
|
|
881
|
+
// target still prompts even under auto.
|
|
882
|
+
//
|
|
883
|
+
// #8619: so does NOT_DELEGABLE_TOOLS — the one list of tools an unattended
|
|
884
|
+
// approver may never say yes to (#7975). A codex sandbox-scope escalation
|
|
885
|
+
// (`request_permissions`) carries no path field, so the floor cannot see
|
|
886
|
+
// it, yet a turn-scoped grant would switch off the only floor codex has
|
|
887
|
+
// (`apply_patch` → `changes[].path`) for the rest of the turn. Now that
|
|
888
|
+
// codex Auto keeps `approvalPolicy: 'on-request'`, this is the first path
|
|
889
|
+
// on which such a request can reach the short-circuit; it falls through to
|
|
890
|
+
// the prompt, exactly as `autoAllowPending` leaves a pending one pending.
|
|
891
|
+
if (permissionMode === 'auto' && !protectedTarget && !NOT_DELEGABLE_TOOLS.has(toolName)) {
|
|
221
892
|
return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
|
|
222
893
|
}
|
|
223
894
|
|
|
224
|
-
// Session rules: check before acceptEdits and the prompt path
|
|
225
|
-
|
|
226
|
-
|
|
895
|
+
// Session rules: check before acceptEdits and the prompt path. #6794: a
|
|
896
|
+
// protected target skips the `allow` branch (fall through to the prompt);
|
|
897
|
+
// a `deny` rule still denies.
|
|
898
|
+
const ruleDecision = this._matchesRule(toolName, input)
|
|
899
|
+
if (ruleDecision !== null && !(protectedTarget && ruleDecision === 'allow')) {
|
|
227
900
|
this._logInfo(`Permission rule matched for ${toolName}: ${ruleDecision}`)
|
|
228
901
|
if (ruleDecision === 'allow') {
|
|
902
|
+
// #6830 — a durable project rule (not a session rule) just silently
|
|
903
|
+
// auto-approved this tool call. Record it via the direct audit sink
|
|
904
|
+
// (NOT an event — see _auditPersistedRuleAutoApprove) so the
|
|
905
|
+
// permission audit log has a trace even though no prompt was shown.
|
|
906
|
+
if (this._persistentRuleSourced(toolName, input)) {
|
|
907
|
+
this._auditPersistedRuleAutoApprove(toolName)
|
|
908
|
+
}
|
|
229
909
|
return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
|
|
230
910
|
}
|
|
231
911
|
return Promise.resolve({ behavior: 'deny', message: 'Denied by session rule' })
|
|
232
912
|
}
|
|
233
913
|
|
|
234
|
-
// acceptEdits: auto-approve file operations, prompt for everything else
|
|
235
|
-
|
|
914
|
+
// acceptEdits: auto-approve file operations, prompt for everything else.
|
|
915
|
+
// #6794: the floor takes precedence — a protected target still prompts.
|
|
916
|
+
if (permissionMode === 'acceptEdits' && ACCEPT_EDITS_TOOLS.has(toolName) && !protectedTarget) {
|
|
236
917
|
return Promise.resolve({ behavior: 'allow', updatedInput: input || {} })
|
|
237
918
|
}
|
|
238
919
|
|
|
@@ -251,7 +932,14 @@ export class PermissionManager extends EventEmitter {
|
|
|
251
932
|
}
|
|
252
933
|
this._pendingPermissions.set(requestId, {
|
|
253
934
|
resolve,
|
|
935
|
+
// #8363: the provider's id for this tool call, so `hasPendingForToolUse`
|
|
936
|
+
// can say whether its prompt is STILL waiting (not merely was asked).
|
|
937
|
+
toolUseId: sourceToolUseId,
|
|
254
938
|
input: input || {},
|
|
939
|
+
// Preserve the single floor verdict made above. A later mode switch
|
|
940
|
+
// may drain ordinary prompts, but it must not turn an already pending
|
|
941
|
+
// protected-path prompt into an implicit approval.
|
|
942
|
+
protectedTarget,
|
|
255
943
|
// Stashed for the allowAlways branch of respondToPermission so
|
|
256
944
|
// we can echo them back as updatedPermissions per the SDK
|
|
257
945
|
// 'Always allow' flow.
|
|
@@ -259,23 +947,12 @@ export class PermissionManager extends EventEmitter {
|
|
|
259
947
|
})
|
|
260
948
|
|
|
261
949
|
const toolInput = input || {}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
// #6038/#6048/#6049: build the broadcast description by REDACTING the full
|
|
269
|
-
// string first, THEN truncating — truncating first (the old order) could
|
|
270
|
-
// leave a secret straddling the cap as a sub-floor partial prefix that the
|
|
271
|
-
// pattern scan misses. String() coerces a non-string field so a malformed
|
|
272
|
-
// tool input can't crash the emit path (.replace on a non-string throws).
|
|
273
|
-
// #6448 — cap the raw string BEFORE redaction so a malicious multi-MB tool
|
|
274
|
-
// field can't make redactValue scan the whole thing (CPU DoS). The 8KB cap
|
|
275
|
-
// is far above the 200-char shown window below, so it can never split a
|
|
276
|
-
// SHOWN secret — the #6038 redact-then-truncate guarantee holds for
|
|
277
|
-
// everything the client sees (anything past 8KB is sliced away regardless).
|
|
278
|
-
const description = redactValue(String(rawDescription).slice(0, MAX_RAW_DESCRIPTION_LEN)).slice(0, 200)
|
|
950
|
+
// #6038/#6048/#6049/#8384: the broadcast description is built by
|
|
951
|
+
// `describeToolInput`, the one place a description is derived from a tool
|
|
952
|
+
// input: redaction (of the identifying field, or of the SANITIZED input
|
|
953
|
+
// when none exists) always runs before the 200-char clip. The raw input is
|
|
954
|
+
// never serialized into it.
|
|
955
|
+
const description = describeToolInput(toolInput, toolName).slice(0, 200)
|
|
279
956
|
|
|
280
957
|
this._logInfo(`Permission request ${requestId}: ${toolName}`)
|
|
281
958
|
|
|
@@ -283,6 +960,12 @@ export class PermissionManager extends EventEmitter {
|
|
|
283
960
|
// execution via the _pendingPermissions entry above; this payload is
|
|
284
961
|
// broadcast/display only, so a secret in a value (or the stringified
|
|
285
962
|
// fallback description) must not reach subscribed clients.
|
|
963
|
+
// #7968: carry the floor verdict computed above so an external consumer
|
|
964
|
+
// of permission_request (e.g. the agent-control MCP, #7854) can tell a
|
|
965
|
+
// floored prompt apart from an ordinary one. Stashed on _lastPermissionData
|
|
966
|
+
// too, so both the resend path (resendPendingPermissions) and this
|
|
967
|
+
// broadcast agree — one computation, replayed verbatim.
|
|
968
|
+
const recordDescription = describeByNamedField(toolInput)
|
|
286
969
|
const permPayload = {
|
|
287
970
|
requestId,
|
|
288
971
|
tool: toolName,
|
|
@@ -290,19 +973,40 @@ export class PermissionManager extends EventEmitter {
|
|
|
290
973
|
input: sanitizeToolInput(toolInput),
|
|
291
974
|
remainingMs: this._timeoutMs,
|
|
292
975
|
createdAt: Date.now(),
|
|
976
|
+
floored: protectedTarget,
|
|
977
|
+
explicitConsent: false,
|
|
978
|
+
nonDelegable: NOT_DELEGABLE_TOOLS.has(toolName),
|
|
979
|
+
// #8348: the identifying field of the RAW input, redacted, for the
|
|
980
|
+
// session's permission transcript. Not on the wire (the request builder
|
|
981
|
+
// picks its fields), and read from the raw input because the broadcast
|
|
982
|
+
// copy of a large input no longer has the field.
|
|
983
|
+
...(recordDescription !== undefined ? { recordDescription } : {}),
|
|
293
984
|
}
|
|
294
985
|
this._lastPermissionData.set(requestId, permPayload)
|
|
295
986
|
this.emit('permission_request', permPayload)
|
|
296
987
|
|
|
297
|
-
// Auto-deny on abort signal
|
|
988
|
+
// Auto-deny on abort signal. WHY the signal aborted is not on the signal --
|
|
989
|
+
// a user Stop and a failed turn (a dead app-server, a stalled stream) abort
|
|
990
|
+
// the same controller -- so the user's Stop entry point sets the turn's
|
|
991
|
+
// "user Stop in flight" flag (`markUserStopInFlight`, #8374/#8430) and this
|
|
992
|
+
// reads it when the abort lands: `stopped` for a Stop, `aborted` for
|
|
993
|
+
// everything else. The flag, not a mark on each prompt, so a prompt raised
|
|
994
|
+
// in the window between the Stop and the abort is covered too.
|
|
298
995
|
if (signal) {
|
|
299
996
|
signal.addEventListener('abort', () => {
|
|
300
|
-
|
|
997
|
+
const pending = this._pendingPermissions.get(requestId)
|
|
998
|
+
if (pending) {
|
|
999
|
+
const reason = this._userStopInFlight ? 'stopped' : 'aborted'
|
|
301
1000
|
this._pendingPermissions.delete(requestId)
|
|
302
1001
|
this._lastPermissionData.delete(requestId)
|
|
303
1002
|
this._clearPermissionTimer(requestId)
|
|
304
1003
|
resolve({ behavior: 'deny', message: 'Request cancelled' })
|
|
305
|
-
this.emit('permission_resolved', {
|
|
1004
|
+
this.emit('permission_resolved', {
|
|
1005
|
+
requestId,
|
|
1006
|
+
decision: 'deny',
|
|
1007
|
+
reason,
|
|
1008
|
+
...stoppedToolUseField(reason, pending.toolUseId),
|
|
1009
|
+
})
|
|
306
1010
|
}
|
|
307
1011
|
}, { once: true })
|
|
308
1012
|
}
|
|
@@ -322,14 +1026,71 @@ export class PermissionManager extends EventEmitter {
|
|
|
322
1026
|
})
|
|
323
1027
|
}
|
|
324
1028
|
|
|
1029
|
+
/**
|
|
1030
|
+
* #8374/#8430: the user pressed Stop. Record that for the rest of the turn, so
|
|
1031
|
+
* the abort that follows resolves every open prompt -- including one raised
|
|
1032
|
+
* between this call and the abort -- with `reason: 'stopped'` instead of
|
|
1033
|
+
* `'aborted'`.
|
|
1034
|
+
*
|
|
1035
|
+
* Called only from the user's Stop entry point (the `interrupt` message
|
|
1036
|
+
* handler), never from `interrupt()` itself: the scheduler and teardown call
|
|
1037
|
+
* that too, and a turn failed by a stalled stream or a dead app-server aborts
|
|
1038
|
+
* the same controller. Those are not Stops.
|
|
1039
|
+
*
|
|
1040
|
+
* Ends with the turn (`clearUserStopInFlight`, called from the session's turn
|
|
1041
|
+
* teardown), so a later turn's failure is not mislabelled.
|
|
1042
|
+
*/
|
|
1043
|
+
markUserStopInFlight() {
|
|
1044
|
+
this._userStopInFlight = true
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/** #8430: the turn is over; a Stop pressed during it must not label the next. */
|
|
1048
|
+
clearUserStopInFlight() {
|
|
1049
|
+
this._userStopInFlight = false
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
/** #8430: has the user pressed Stop on the turn that is running? */
|
|
1053
|
+
isUserStopInFlight() {
|
|
1054
|
+
return this._userStopInFlight
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/** #8430: is any permission prompt or question waiting for a decision right now? */
|
|
1058
|
+
hasPendingPrompt() {
|
|
1059
|
+
return this._pendingPermissions.size > 0 || this._pendingUserAnswer != null
|
|
1060
|
+
}
|
|
1061
|
+
|
|
325
1062
|
/**
|
|
326
1063
|
* Handle AskUserQuestion via canUseTool.
|
|
327
1064
|
* Emits user_question and waits for respondToQuestion() to deliver the
|
|
328
1065
|
* user's answer, then resolves with structured updatedInput.
|
|
329
1066
|
*/
|
|
330
|
-
|
|
1067
|
+
/**
|
|
1068
|
+
* #8363: is a permission prompt (or AskUserQuestion) for this PROVIDER tool-use
|
|
1069
|
+
* id still waiting for a decision? Reads the live pending state, which a
|
|
1070
|
+
* response clears synchronously -- unlike a promise continuation, which runs a
|
|
1071
|
+
* microtask later.
|
|
1072
|
+
* @param {string} toolUseId
|
|
1073
|
+
* @returns {boolean}
|
|
1074
|
+
*/
|
|
1075
|
+
hasPendingForToolUse(toolUseId) {
|
|
1076
|
+
if (typeof toolUseId !== 'string' || toolUseId.length === 0) return false
|
|
1077
|
+
if (this._pendingUserAnswer?.sourceToolUseId === toolUseId) return true
|
|
1078
|
+
for (const entry of this._pendingPermissions.values()) {
|
|
1079
|
+
if (entry.toolUseId === toolUseId) return true
|
|
1080
|
+
}
|
|
1081
|
+
return false
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
_handleAskUserQuestion(input, signal, sourceToolUseId = undefined) {
|
|
331
1085
|
return new Promise((resolve) => {
|
|
332
1086
|
const questionInput = input || {}
|
|
1087
|
+
// #8470: this manager holds ONE pending question. A second one arriving
|
|
1088
|
+
// while the first is still open used to overwrite the slot, so the first
|
|
1089
|
+
// `canUseTool` promise never settled (the tool call hung until the turn
|
|
1090
|
+
// ended), its timer kept running against the NEW question, and its card
|
|
1091
|
+
// read pending on every client. End it as a deny, tell the clients, and
|
|
1092
|
+
// only then take the slot.
|
|
1093
|
+
this._supersedePendingQuestion()
|
|
333
1094
|
this._waitingForAnswer = true
|
|
334
1095
|
const toolUseId = `ask-${this._idNonce}-${++this._permissionCounter}-${Date.now()}`
|
|
335
1096
|
// #3975: stash toolUseId on the pending entry so clearAll() can
|
|
@@ -339,23 +1100,48 @@ export class PermissionManager extends EventEmitter {
|
|
|
339
1100
|
// questionSessionMap entry — small leak (~80 bytes) per
|
|
340
1101
|
// message-completion-while-question-pending event, bounded only by
|
|
341
1102
|
// session_destroyed cleanup.
|
|
342
|
-
|
|
1103
|
+
const entry = { resolve, input: questionInput, toolUseId, sourceToolUseId }
|
|
1104
|
+
this._pendingUserAnswer = entry
|
|
343
1105
|
this._logInfo(`AskUserQuestion detected (${toolUseId})`)
|
|
1106
|
+
// #8336: without the provider's id, the restore-time sweep cannot tell
|
|
1107
|
+
// which `tool_start` this question belongs to, so a restart mid-question
|
|
1108
|
+
// will leave it looking like any other replayed question ("(resolved)").
|
|
1109
|
+
// Both providers that reach here (SDK, BYOK) are meant to supply it. Say so
|
|
1110
|
+
// once, with the id the question WAS recorded under, and carry on.
|
|
1111
|
+
if (typeof sourceToolUseId !== 'string' || sourceToolUseId.length === 0) {
|
|
1112
|
+
this._logWarn(
|
|
1113
|
+
`AskUserQuestion ${toolUseId} has no provider tool-use id; a restart while it is pending cannot mark it interrupted (#8336)`,
|
|
1114
|
+
)
|
|
1115
|
+
}
|
|
344
1116
|
|
|
1117
|
+
// #8336: `toolUseId` here is chroxy's own `ask-...` id (what the answer
|
|
1118
|
+
// routes on), which is NOT the id the provider recorded the
|
|
1119
|
+
// AskUserQuestion `tool_start` under. Carry the provider's id alongside
|
|
1120
|
+
// it so the restore-time sweep can tell which question a swept tool start
|
|
1121
|
+
// belongs to. Never on the live wire: the event normalizer picks
|
|
1122
|
+
// `toolUseId` and `questions` only.
|
|
345
1123
|
this.emit('user_question', {
|
|
346
1124
|
toolUseId,
|
|
347
1125
|
questions: questionInput.questions,
|
|
1126
|
+
...(typeof sourceToolUseId === 'string' && sourceToolUseId.length > 0
|
|
1127
|
+
? { sourceToolUseId }
|
|
1128
|
+
: {}),
|
|
348
1129
|
})
|
|
349
1130
|
|
|
350
1131
|
// Auto-deny on abort signal
|
|
351
1132
|
if (signal) {
|
|
352
1133
|
signal.addEventListener('abort', () => {
|
|
353
|
-
|
|
1134
|
+
// #8470: identity, not "something is pending". A superseded question's
|
|
1135
|
+
// listener stays on the (shared) turn signal; without this it would
|
|
1136
|
+
// cancel the question that replaced it.
|
|
1137
|
+
if (this._pendingUserAnswer === entry) {
|
|
1138
|
+
// #8430: same cause attribution as a permission prompt's abort.
|
|
1139
|
+
const reason = this._userStopInFlight ? 'stopped' : 'aborted'
|
|
354
1140
|
this._clearQuestionTimer()
|
|
355
1141
|
this._pendingUserAnswer = null
|
|
356
1142
|
this._waitingForAnswer = false
|
|
357
1143
|
resolve({ behavior: 'deny', message: 'Cancelled' })
|
|
358
|
-
this.emit('permission_resolved', { toolUseId, reason
|
|
1144
|
+
this.emit('permission_resolved', { toolUseId, reason, ...stoppedToolUseField(reason, sourceToolUseId) })
|
|
359
1145
|
}
|
|
360
1146
|
}, { once: true })
|
|
361
1147
|
}
|
|
@@ -374,23 +1160,58 @@ export class PermissionManager extends EventEmitter {
|
|
|
374
1160
|
})
|
|
375
1161
|
}
|
|
376
1162
|
|
|
1163
|
+
/**
|
|
1164
|
+
* #8470: end the pending AskUserQuestion, if any, because a newer one is about
|
|
1165
|
+
* to replace it. Resolves its `canUseTool` promise as a deny (the tool call
|
|
1166
|
+
* ends and the agent hears why), stops its timer, and emits the question
|
|
1167
|
+
* variant of `permission_resolved` with `reason: 'superseded'` so the clients
|
|
1168
|
+
* stop showing it as waiting. Not an answer: nothing is recorded as answered.
|
|
1169
|
+
*/
|
|
1170
|
+
_supersedePendingQuestion() {
|
|
1171
|
+
const superseded = this._pendingUserAnswer
|
|
1172
|
+
if (!superseded) return
|
|
1173
|
+
this._clearQuestionTimer()
|
|
1174
|
+
this._pendingUserAnswer = null
|
|
1175
|
+
this._waitingForAnswer = false
|
|
1176
|
+
this._logInfo(`Question ${superseded.toolUseId} superseded by a newer question`)
|
|
1177
|
+
superseded.resolve({ behavior: 'deny', message: 'Superseded by a newer question' })
|
|
1178
|
+
this.emit('permission_resolved', { toolUseId: superseded.toolUseId, decision: 'deny', reason: 'superseded' })
|
|
1179
|
+
}
|
|
1180
|
+
|
|
377
1181
|
/**
|
|
378
1182
|
* Resolve a pending permission request.
|
|
379
1183
|
*
|
|
380
1184
|
* @param {string} requestId - The permission request ID
|
|
381
1185
|
* @param {string} decision - 'allow', 'deny', or 'allowAlways'
|
|
1186
|
+
* @param {*} [editedInput] - #6543/#6773 client edits merged under the
|
|
1187
|
+
* {@link EDITABLE_INPUT_FIELDS} whitelist on an approve (ignored on deny).
|
|
1188
|
+
* @param {string} [reason] - #6773 operator-supplied free-text deny reason;
|
|
1189
|
+
* used only on a `deny` to replace the fixed 'User denied' agent message.
|
|
1190
|
+
* @param {string} [scope] - #8517 `session` when the user chose "Allow for
|
|
1191
|
+
* Session" (the decision is then `allow`). A LABEL for the permission_resolved
|
|
1192
|
+
* event and the journal: it changes nothing about how the request is resolved,
|
|
1193
|
+
* and is dropped unless it rides beside `allow` (permission-scope.js).
|
|
382
1194
|
* @returns {boolean} true if a pending permission was found and resolved,
|
|
383
1195
|
* false if the requestId was unknown (already resolved or expired).
|
|
384
1196
|
*/
|
|
385
|
-
respondToPermission(requestId, decision, editedInput) {
|
|
1197
|
+
respondToPermission(requestId, decision, editedInput, reason, scope) {
|
|
386
1198
|
const pending = this._pendingPermissions.get(requestId)
|
|
387
1199
|
if (!pending) {
|
|
388
1200
|
this._logWarn(`No pending permission for ${requestId}`)
|
|
389
1201
|
return false
|
|
390
1202
|
}
|
|
1203
|
+
// Explicit consent has its own client-bound response route. Generic
|
|
1204
|
+
// responders, durable grants and edited inputs cannot approve it.
|
|
1205
|
+
if (pending.explicitConsent === true && decision !== 'deny') return false
|
|
391
1206
|
// #6543: capture the tool name BEFORE deleting the last-permission data, so
|
|
392
1207
|
// the editedInput whitelist knows which content field(s) are substitutable.
|
|
393
1208
|
const toolName = this._lastPermissionData.get(requestId)?.tool
|
|
1209
|
+
// #8446: build the approved input BEFORE touching any state. A refused edit
|
|
1210
|
+
// throws EditedInputRefusedError with the request still pending, so the caller
|
|
1211
|
+
// (permission-resolver.js) can answer it; ignored on a deny.
|
|
1212
|
+
const approvedInput = (decision === 'allow' || decision === 'allowAlways')
|
|
1213
|
+
? mergeEditedInput(pending.input, editedInput, toolName)
|
|
1214
|
+
: pending.input
|
|
394
1215
|
this._pendingPermissions.delete(requestId)
|
|
395
1216
|
this._lastPermissionData.delete(requestId)
|
|
396
1217
|
this._clearPermissionTimer(requestId)
|
|
@@ -399,13 +1220,14 @@ export class PermissionManager extends EventEmitter {
|
|
|
399
1220
|
|
|
400
1221
|
// Emit before resolve() so listeners see the pending-count drop
|
|
401
1222
|
// before any follow-on work runs synchronously.
|
|
402
|
-
|
|
1223
|
+
const resolvedScope = permissionScope(decision, scope)
|
|
1224
|
+
this.emit('permission_resolved', { requestId, decision, reason: 'user', ...(resolvedScope ? { scope: resolvedScope } : {}) })
|
|
403
1225
|
|
|
404
1226
|
// #6543 (feature B): on an approve, an operator who reviewed the proposed
|
|
405
|
-
// Write/Edit per-hunk may
|
|
406
|
-
// mergeEditedInput
|
|
407
|
-
// tool executor as `updatedInput`, which still
|
|
408
|
-
|
|
1227
|
+
// Write/Edit per-hunk may narrow the CONTENT (never the path — see
|
|
1228
|
+
// mergeEditedInput, built above from the RAW input, #8446). The merged input
|
|
1229
|
+
// flows to the agent's tool executor as `updatedInput`, which still
|
|
1230
|
+
// path-confines the write.
|
|
409
1231
|
|
|
410
1232
|
if (decision === 'allow') {
|
|
411
1233
|
pending.resolve({ behavior: 'allow', updatedInput: approvedInput })
|
|
@@ -431,9 +1253,28 @@ export class PermissionManager extends EventEmitter {
|
|
|
431
1253
|
if (pending.suggestions && pending.suggestions.length > 0) {
|
|
432
1254
|
result.updatedPermissions = pending.suggestions
|
|
433
1255
|
}
|
|
1256
|
+
// #6771 — persist a DURABLE project-scoped rule so this grant survives a
|
|
1257
|
+
// daemon restart (the SDK `updatedPermissions` above only persists within
|
|
1258
|
+
// the SDK's own session). Only for rule-eligible tools: the store rejects
|
|
1259
|
+
// NEVER_AUTO_ALLOW / non-ELIGIBLE tools, so an `allowAlways` on Bash (or a
|
|
1260
|
+
// codex `shell`) degrades to a one-shot allow and is NEVER durably
|
|
1261
|
+
// whitelisted. Seed the in-memory persistent set too so the very next tool
|
|
1262
|
+
// call in THIS session auto-allows without re-prompting.
|
|
1263
|
+
if (toolName && this._ruleStore && this._cwd) {
|
|
1264
|
+
const persisted = this._ruleStore.addRule(this._cwd, { tool: toolName, decision: 'allow' })
|
|
1265
|
+
if (persisted) {
|
|
1266
|
+
// Re-seed the in-memory set so the very next tool call in THIS session
|
|
1267
|
+
// auto-allows. The client-facing `permission_rules_updated` broadcast
|
|
1268
|
+
// is emitted by the WS response handler (settings-handlers.js) after
|
|
1269
|
+
// this resolves — getPersistentRules() reflects the update synchronously.
|
|
1270
|
+
this.setPersistentRules(this._ruleStore.getRules(this._cwd))
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
434
1273
|
pending.resolve(result)
|
|
435
1274
|
} else {
|
|
436
|
-
|
|
1275
|
+
// #6773 — carry the operator's free-text reason (bounded + redacted) back
|
|
1276
|
+
// to the agent as the denial message, instead of the fixed 'User denied'.
|
|
1277
|
+
pending.resolve({ behavior: 'deny', message: buildDenyMessage(reason) })
|
|
437
1278
|
}
|
|
438
1279
|
return true
|
|
439
1280
|
}
|
|
@@ -443,9 +1284,26 @@ export class PermissionManager extends EventEmitter {
|
|
|
443
1284
|
*
|
|
444
1285
|
* @param {string} text - The user's text answer
|
|
445
1286
|
* @param {Object} [answersMap] - Per-question answers map
|
|
1287
|
+
* @param {string} [toolUseId] - #8460: the chroxy question id the answer was
|
|
1288
|
+
* given for (the `ask-...` id on the `user_question` frame). When supplied and
|
|
1289
|
+
* it is not the pending question's, the answer is for a different question
|
|
1290
|
+
* (a retry, a second client, a reconnect re-send landing after the first
|
|
1291
|
+
* question was answered or timed out), so it is dropped rather than resolved
|
|
1292
|
+
* against whichever question happens to be pending now. Absent, the answer
|
|
1293
|
+
* goes to the pending question as before. `typeof === 'string'`, not
|
|
1294
|
+
* truthiness: an empty id is still an id, and still not this question's.
|
|
1295
|
+
* @returns {boolean|undefined} `false` only when the answer was refused for a
|
|
1296
|
+
* mismatching `toolUseId` (the pending question is untouched, nothing reached
|
|
1297
|
+
* the agent). `undefined` otherwise, including "nothing was pending".
|
|
446
1298
|
*/
|
|
447
|
-
respondToQuestion(text, answersMap) {
|
|
1299
|
+
respondToQuestion(text, answersMap, toolUseId = undefined) {
|
|
448
1300
|
if (!this._pendingUserAnswer) return
|
|
1301
|
+
if (typeof toolUseId === 'string' && toolUseId !== this._pendingUserAnswer.toolUseId) {
|
|
1302
|
+
this._logWarn(
|
|
1303
|
+
`Question response dropped: answer is for ${JSON.stringify(toolUseId)} but the pending question is ${JSON.stringify(this._pendingUserAnswer.toolUseId)}`,
|
|
1304
|
+
)
|
|
1305
|
+
return false
|
|
1306
|
+
}
|
|
449
1307
|
this._clearQuestionTimer()
|
|
450
1308
|
// #3988: include toolUseId on the answered emit for symmetry with the
|
|
451
1309
|
// other 3 question-variant emit sites (aborted/timeout/cleared). The
|
|
@@ -461,7 +1319,7 @@ export class PermissionManager extends EventEmitter {
|
|
|
461
1319
|
// (or refactor that drops the eager delete) would silently leak. Read
|
|
462
1320
|
// toolUseId BEFORE the null-out below, mirroring the clearAll #3975
|
|
463
1321
|
// pattern.
|
|
464
|
-
const { resolve, input, toolUseId } = this._pendingUserAnswer
|
|
1322
|
+
const { resolve, input, toolUseId: pendingToolUseId } = this._pendingUserAnswer
|
|
465
1323
|
this._pendingUserAnswer = null
|
|
466
1324
|
this._waitingForAnswer = false
|
|
467
1325
|
|
|
@@ -470,7 +1328,7 @@ export class PermissionManager extends EventEmitter {
|
|
|
470
1328
|
// Emit before resolve() so listeners (e.g. the SdkSession
|
|
471
1329
|
// inactivity-timer resumer, #2831) see the state flip before any
|
|
472
1330
|
// downstream synchronous work runs.
|
|
473
|
-
this.emit('permission_resolved', { toolUseId, reason: 'answered' })
|
|
1331
|
+
this.emit('permission_resolved', { toolUseId: pendingToolUseId, reason: 'answered' })
|
|
474
1332
|
|
|
475
1333
|
// Build structured answers map: SDK expects { [questionText]: selectedLabel }.
|
|
476
1334
|
// Per @anthropic-ai/claude-agent-sdk sdk-tools.d.ts (AskUserQuestionOutput.answers,
|
|
@@ -507,6 +1365,31 @@ export class PermissionManager extends EventEmitter {
|
|
|
507
1365
|
})
|
|
508
1366
|
}
|
|
509
1367
|
|
|
1368
|
+
/**
|
|
1369
|
+
* #7457 -- the AskUserQuestion this manager is still blocked on, if any.
|
|
1370
|
+
*
|
|
1371
|
+
* A read-through of `_pendingUserAnswer`, which IS the blocked `canUseTool`
|
|
1372
|
+
* resolver: every path that resolves the promise nulls it in the same
|
|
1373
|
+
* statement block (`respondToQuestion`, the abort listener, the question
|
|
1374
|
+
* timer, `clearAll`), so this can never report a question the turn is no
|
|
1375
|
+
* longer waiting on. There is no second record to leak.
|
|
1376
|
+
*
|
|
1377
|
+
* `autoAllowPending()` is deliberately NOT one of those paths (#3729/#4462):
|
|
1378
|
+
* solicited user input is not a permission gate, so a mode switch to
|
|
1379
|
+
* auto/bypass leaves the resolver blocked -- and therefore leaves the
|
|
1380
|
+
* question correctly pending here.
|
|
1381
|
+
*
|
|
1382
|
+
* Shaped as an array because the other two providers hold a MAP of them, and
|
|
1383
|
+
* `ws-history.resendPendingQuestions` reads one shape from every provider.
|
|
1384
|
+
*
|
|
1385
|
+
* @returns {{ toolUseId: string, questions: object[] }[]}
|
|
1386
|
+
*/
|
|
1387
|
+
getPendingQuestions() {
|
|
1388
|
+
const pending = this._pendingUserAnswer
|
|
1389
|
+
if (!pending) return []
|
|
1390
|
+
return [{ toolUseId: pending.toolUseId, questions: pending.input?.questions ?? [] }]
|
|
1391
|
+
}
|
|
1392
|
+
|
|
510
1393
|
/**
|
|
511
1394
|
* Clear a permission timeout timer by request ID.
|
|
512
1395
|
*/
|
|
@@ -529,12 +1412,13 @@ export class PermissionManager extends EventEmitter {
|
|
|
529
1412
|
}
|
|
530
1413
|
|
|
531
1414
|
/**
|
|
532
|
-
* Auto-allow every outstanding permission request. Called when the
|
|
1415
|
+
* Auto-allow every ordinary outstanding permission request. Called when the
|
|
533
1416
|
* session switches into auto/bypass mode (#3729) — the user has just
|
|
534
|
-
*
|
|
1417
|
+
* enabled broad auto-approval, so an ordinary prompt still on screen should
|
|
535
1418
|
* resolve as if they had clicked Allow rather than sit there until
|
|
536
1419
|
* timeout. Pending AskUserQuestion prompts are NOT touched: those are
|
|
537
|
-
* solicited user input, not permission gates.
|
|
1420
|
+
* solicited user input, not permission gates. Protected-path prompts also
|
|
1421
|
+
* remain pending because Auto is still subject to the permission floor.
|
|
538
1422
|
*
|
|
539
1423
|
* #4462: MCP trust prompts (requestMcpTrust) are also exempt — their
|
|
540
1424
|
* allow path PERSISTS the binary to ~/.chroxy/mcp-trust.json forever
|
|
@@ -543,19 +1427,51 @@ export class PermissionManager extends EventEmitter {
|
|
|
543
1427
|
* binary forever." Treating mcp_spawn under auto as deny re-prompts
|
|
544
1428
|
* the user next start — they can explicitly approve then, when the
|
|
545
1429
|
* decision is in front of them.
|
|
1430
|
+
*
|
|
1431
|
+
* #7975: a pending `request_permissions` prompt (codex's sandbox-scope
|
|
1432
|
+
* escalation) carries neither `protectedTarget` nor `mcpTrust` — before
|
|
1433
|
+
* this fix it fell straight through to the default allow branch below, so
|
|
1434
|
+
* a session that flipped into auto/bypass mode mid-turn silently granted a
|
|
1435
|
+
* sandbox-scope escalation the user never explicitly approved. This is now
|
|
1436
|
+
* checked by TOOL NAME against {@link NOT_DELEGABLE_TOOLS} — the exact same
|
|
1437
|
+
* Set agent-control's `respondPermission` gate uses, so the daemon's "never
|
|
1438
|
+
* approve without a human" list has one source of truth, not two that can
|
|
1439
|
+
* drift — via the tool name stashed on `_lastPermissionData` (the pending
|
|
1440
|
+
* entry itself carries no tool field). It is left GENUINELY PENDING, the
|
|
1441
|
+
* same treatment as a protected-path prompt: the original `permission_request`
|
|
1442
|
+
* broadcast already reached any connected client when the prompt was first
|
|
1443
|
+
* emitted, and `resendPendingPermissions` (ws-permissions.js) replays it to
|
|
1444
|
+
* a reconnecting client for as long as it stays in `_pendingPermissions` —
|
|
1445
|
+
* nothing here removes it from either map, so it is neither silently
|
|
1446
|
+
* granted nor silently dropped. `mcp_spawn` is ALSO in NOT_DELEGABLE_TOOLS,
|
|
1447
|
+
* but this check is placed AFTER the `mcpTrust` branch below (which fires
|
|
1448
|
+
* for every mcp_spawn entry) so mcp_spawn's existing explicit-deny handling
|
|
1449
|
+
* is unchanged — this only widens what happens to `request_permissions`.
|
|
1450
|
+
*
|
|
1451
|
+
* #7975-followup: the tool-name lookup FAILS CLOSED — a pending entry with
|
|
1452
|
+
* no recoverable `_lastPermissionData` (which every current call site sets
|
|
1453
|
+
* in lockstep with `_pendingPermissions`, so this is a belt-and-braces
|
|
1454
|
+
* default, not a reachable path today) is preserved genuinely pending, same
|
|
1455
|
+
* as a known not-delegable tool, rather than silently allowed.
|
|
546
1456
|
*/
|
|
547
1457
|
autoAllowPending() {
|
|
548
1458
|
if (this._pendingPermissions.size === 0) return
|
|
549
1459
|
const pendingIds = Array.from(this._pendingPermissions.keys())
|
|
550
1460
|
let allowed = 0
|
|
551
1461
|
let deniedMcpTrust = 0
|
|
1462
|
+
let preservedProtected = 0
|
|
1463
|
+
let preservedNotDelegable = 0
|
|
552
1464
|
for (const requestId of pendingIds) {
|
|
553
1465
|
const pending = this._pendingPermissions.get(requestId)
|
|
554
1466
|
if (!pending) continue
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
1467
|
+
if (pending.protectedTarget === true) {
|
|
1468
|
+
preservedProtected += 1
|
|
1469
|
+
continue
|
|
1470
|
+
}
|
|
558
1471
|
if (pending.mcpTrust === true) {
|
|
1472
|
+
this._pendingPermissions.delete(requestId)
|
|
1473
|
+
this._lastPermissionData.delete(requestId)
|
|
1474
|
+
this._clearPermissionTimer(requestId)
|
|
559
1475
|
// Don't silently persist trust on bypass. Deny — the MCP server
|
|
560
1476
|
// won't spawn for this session, but no on-disk trust entry is
|
|
561
1477
|
// written, and the user re-prompts next start.
|
|
@@ -567,13 +1483,37 @@ export class PermissionManager extends EventEmitter {
|
|
|
567
1483
|
deniedMcpTrust += 1
|
|
568
1484
|
continue
|
|
569
1485
|
}
|
|
1486
|
+
// #7975 — same NOT_DELEGABLE_TOOLS set agent-control's respondPermission
|
|
1487
|
+
// gate consults, checked by the tool name stashed alongside this
|
|
1488
|
+
// requestId (the pending entry itself has no tool field). Left pending,
|
|
1489
|
+
// never deleted — see the doc comment above.
|
|
1490
|
+
//
|
|
1491
|
+
// #7975-followup — every current call site sets `_lastPermissionData`
|
|
1492
|
+
// in the SAME synchronous step as `_pendingPermissions` (handlePermission
|
|
1493
|
+
// and requestMcpTrust both do this, and nothing else in this module ever
|
|
1494
|
+
// mutates either map), so `lastData` below is not expected to be missing
|
|
1495
|
+
// in practice. But `NOT_DELEGABLE_TOOLS.has(undefined)` is `false` — if
|
|
1496
|
+
// that invariant were ever violated by a future change, an entry with no
|
|
1497
|
+
// recoverable tool name would silently fall through to the ALLOW branch
|
|
1498
|
+
// below, which is exactly the bug this fix exists to close, just for an
|
|
1499
|
+
// unknown tool instead of a known one. Fail closed instead: treat a
|
|
1500
|
+
// missing lookup the same as a not-delegable tool (leave it genuinely
|
|
1501
|
+
// pending for a human) rather than assume it is safe to allow.
|
|
1502
|
+
const lastData = this._lastPermissionData.get(requestId)
|
|
1503
|
+
if (pending.explicitConsent === true || !lastData || NOT_DELEGABLE_TOOLS.has(lastData.tool)) {
|
|
1504
|
+
preservedNotDelegable += 1
|
|
1505
|
+
continue
|
|
1506
|
+
}
|
|
1507
|
+
this._pendingPermissions.delete(requestId)
|
|
1508
|
+
this._lastPermissionData.delete(requestId)
|
|
1509
|
+
this._clearPermissionTimer(requestId)
|
|
570
1510
|
pending.resolve({ behavior: 'allow', updatedInput: pending.input })
|
|
571
1511
|
this.emit('permission_resolved', { requestId, decision: 'allow', reason: 'auto_mode' })
|
|
572
1512
|
allowed += 1
|
|
573
1513
|
}
|
|
574
|
-
if (deniedMcpTrust > 0) {
|
|
1514
|
+
if (deniedMcpTrust > 0 || preservedProtected > 0 || preservedNotDelegable > 0) {
|
|
575
1515
|
this._logInfo(
|
|
576
|
-
`Auto-allowed ${allowed} pending permission(s)
|
|
1516
|
+
`Auto-allowed ${allowed} pending permission(s), denied ${deniedMcpTrust} MCP trust prompt(s), preserved ${preservedProtected} protected-path prompt(s), and preserved ${preservedNotDelegable} not-delegable prompt(s) on auto mode switch`,
|
|
577
1517
|
)
|
|
578
1518
|
} else {
|
|
579
1519
|
this._logInfo(`Auto-allowed ${allowed} pending permission(s) on auto mode switch`)
|
|
@@ -584,11 +1524,20 @@ export class PermissionManager extends EventEmitter {
|
|
|
584
1524
|
* Auto-deny all pending permissions and questions. Called on message
|
|
585
1525
|
* completion or session destruction.
|
|
586
1526
|
*/
|
|
587
|
-
clearAll() {
|
|
1527
|
+
clearAll({ userStop = this._userStopInFlight } = {}) {
|
|
1528
|
+
// #8430: why the prompts are being drained. On a live claude-sdk Stop this is
|
|
1529
|
+
// the path that resolves them (the generator throws AbortError and the turn
|
|
1530
|
+
// ends through the session's teardown; the abort listener never ran first), so
|
|
1531
|
+
// a user Stop in flight must be read HERE. `userStop` lets a caller that has
|
|
1532
|
+
// already cleared the flag in its own teardown pass the value it captured.
|
|
1533
|
+
const requestReason = userStop === true ? 'stopped' : 'cleared'
|
|
588
1534
|
// Collect requestIds first so we can emit permission_resolved AFTER
|
|
589
1535
|
// the maps are cleared — the SdkSession timeout-pause listener decrements
|
|
590
1536
|
// its counter on each event and should see a consistent final state.
|
|
591
1537
|
const pendingIds = Array.from(this._pendingPermissions.keys())
|
|
1538
|
+
// #8430: the provider's tool-use id of each, for a `stopped` resolution.
|
|
1539
|
+
const pendingToolUseIds = new Map()
|
|
1540
|
+
for (const [requestId, pending] of this._pendingPermissions) pendingToolUseIds.set(requestId, pending.toolUseId)
|
|
592
1541
|
// #3975: capture the pending-answer entry (not just a boolean) so we
|
|
593
1542
|
// can include its toolUseId on the cleared emit. Without toolUseId the
|
|
594
1543
|
// sdk-session re-emit gate drops the event and questionSessionMap
|
|
@@ -621,17 +1570,69 @@ export class PermissionManager extends EventEmitter {
|
|
|
621
1570
|
|
|
622
1571
|
// Emit resolved events so listeners reset any paused state (#2831).
|
|
623
1572
|
for (const requestId of pendingIds) {
|
|
624
|
-
this.emit('permission_resolved', {
|
|
1573
|
+
this.emit('permission_resolved', {
|
|
1574
|
+
requestId,
|
|
1575
|
+
decision: 'deny',
|
|
1576
|
+
reason: requestReason,
|
|
1577
|
+
...stoppedToolUseField(requestReason, pendingToolUseIds.get(requestId)),
|
|
1578
|
+
})
|
|
625
1579
|
}
|
|
626
1580
|
if (clearedUserAnswer) {
|
|
627
1581
|
// #3975: toolUseId is required for the EventNormalizer to prune
|
|
628
1582
|
// questionSessionMap on the cleared path. The SdkSession
|
|
629
1583
|
// timeout-pause listener (#2831) ignores fields it doesn't know
|
|
630
1584
|
// about, so the extra toolUseId is harmless there.
|
|
631
|
-
this.emit('permission_resolved', {
|
|
1585
|
+
this.emit('permission_resolved', {
|
|
1586
|
+
toolUseId: clearedUserAnswer.toolUseId,
|
|
1587
|
+
reason: requestReason,
|
|
1588
|
+
...stoppedToolUseField(requestReason, clearedUserAnswer.sourceToolUseId),
|
|
1589
|
+
})
|
|
632
1590
|
}
|
|
633
1591
|
}
|
|
634
1592
|
|
|
1593
|
+
/** Request one-time human consent without mode, rule or durable-grant shortcuts. */
|
|
1594
|
+
requestExplicitConsent({ requestId, clientId, tool, input, description, signal }) {
|
|
1595
|
+
if (!requestId || !clientId || !NOT_DELEGABLE_TOOLS.has(tool)) throw new Error('Invalid explicit consent request')
|
|
1596
|
+
if (signal?.aborted || this._pendingPermissions.has(requestId)) return Promise.resolve(false)
|
|
1597
|
+
return new Promise((resolve) => {
|
|
1598
|
+
const finish = (allowed, reason) => {
|
|
1599
|
+
if (!this._pendingPermissions.has(requestId)) return
|
|
1600
|
+
this._pendingPermissions.delete(requestId)
|
|
1601
|
+
this._lastPermissionData.delete(requestId)
|
|
1602
|
+
this._clearPermissionTimer(requestId)
|
|
1603
|
+
signal?.removeEventListener('abort', abort)
|
|
1604
|
+
this.emit('permission_resolved', { requestId, decision: allowed ? 'allow' : 'deny', reason })
|
|
1605
|
+
resolve(allowed)
|
|
1606
|
+
}
|
|
1607
|
+
const abort = () => finish(false, 'cancelled')
|
|
1608
|
+
const payload = {
|
|
1609
|
+
requestId, tool, input: sanitizeToolInput(input), description: describeComposedText(description),
|
|
1610
|
+
remainingMs: this._timeoutMs, createdAt: Date.now(), floored: true,
|
|
1611
|
+
explicitConsent: true, nonDelegable: true,
|
|
1612
|
+
}
|
|
1613
|
+
this._pendingPermissions.set(requestId, {
|
|
1614
|
+
input, suggestions: [], explicitConsent: true, clientId,
|
|
1615
|
+
finish,
|
|
1616
|
+
resolve: result => {
|
|
1617
|
+
signal?.removeEventListener('abort', abort)
|
|
1618
|
+
resolve(result?.behavior === 'allow')
|
|
1619
|
+
},
|
|
1620
|
+
})
|
|
1621
|
+
this._lastPermissionData.set(requestId, payload)
|
|
1622
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
1623
|
+
this._permissionTimers.set(requestId, setTimeout(() => finish(false, 'timeout'), this._timeoutMs))
|
|
1624
|
+
this.emit('permission_request', payload)
|
|
1625
|
+
})
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
respondToExplicitConsent(requestId, decision, { clientId, editedInput, scope } = {}) {
|
|
1629
|
+
const pending = this._pendingPermissions.get(requestId)
|
|
1630
|
+
if (pending?.explicitConsent !== true || pending.clientId !== clientId) return false
|
|
1631
|
+
if (!['allow', 'deny'].includes(decision) || editedInput !== undefined || scope !== undefined) return false
|
|
1632
|
+
pending.finish(decision === 'allow', 'user')
|
|
1633
|
+
return true
|
|
1634
|
+
}
|
|
1635
|
+
|
|
635
1636
|
/**
|
|
636
1637
|
* #4457: trust gate for spawning an MCP server child. Reuses the
|
|
637
1638
|
* existing _pendingPermissions machinery so the dashboard / mobile
|
|
@@ -644,22 +1645,79 @@ export class PermissionManager extends EventEmitter {
|
|
|
644
1645
|
* - On deny: resolves to false; caller marks the client DEAD.
|
|
645
1646
|
* - On timeout (default permissionTimeout): treated as deny.
|
|
646
1647
|
*
|
|
647
|
-
*
|
|
1648
|
+
* #6821: also handles REMOTE (streamable-HTTP / SSE) servers, which carry a
|
|
1649
|
+
* `url` + `headerKeys` instead of `command`/`args`/`envKeys`. The url is
|
|
1650
|
+
* credential-stripped (via redactMcpUrl) before it reaches the description
|
|
1651
|
+
* or the broadcast input; header VALUES are never passed in.
|
|
1652
|
+
*
|
|
1653
|
+
* #7939: `server.source` (an `MCP_SERVER_SOURCE` value — see
|
|
1654
|
+
* byok-mcp-config.js) names WHICH config scope this spawn config came from.
|
|
1655
|
+
* It is validated against the closed `MCP_SERVER_SOURCE_VALUES` roster and
|
|
1656
|
+
* only forwarded into the prompt payload when it matches — an absent or
|
|
1657
|
+
* unrecognized value is silently DROPPED (never passed through as-is),
|
|
1658
|
+
* consistent with never sending free-form text where a closed enum belongs.
|
|
1659
|
+
* A caller that predates #7939 (or a cfg built without going through
|
|
1660
|
+
* discovery/add) simply omits it, and the prompt shows no source, which is
|
|
1661
|
+
* the same "no source" the client already has to handle for every other
|
|
1662
|
+
* field it treats as optional.
|
|
1663
|
+
*
|
|
1664
|
+
* @param {{ name: string, command?: string, args?: string[], envKeys?: string[], url?: string, headerKeys?: string[], source?: string }} server
|
|
648
1665
|
* @returns {Promise<boolean>}
|
|
649
1666
|
*/
|
|
650
|
-
requestMcpTrust(server) {
|
|
1667
|
+
async requestMcpTrust(server) {
|
|
1668
|
+
const isRemote = typeof server.url === 'string' && server.url.length > 0
|
|
1669
|
+
const safeUrl = isRemote ? redactMcpUrl(server.url) : ''
|
|
1670
|
+
const source = MCP_SERVER_SOURCE_VALUES.includes(server.source) ? server.source : undefined
|
|
1671
|
+
// #6834 — for a REMOTE server, best-effort-resolve the host BEFORE we build
|
|
1672
|
+
// the prompt so the consent string can show when a "remote" URL actually
|
|
1673
|
+
// points at a loopback / private / internal address (owner decision:
|
|
1674
|
+
// display, never block beyond the existing cloud-metadata hard-block).
|
|
1675
|
+
// Resolution is non-fatal — resolveTrustAddress returns a 'could not
|
|
1676
|
+
// resolve host' record on any failure and never throws. Only the hostname
|
|
1677
|
+
// is read (from the already-redacted url); only IPs come back. The stdio
|
|
1678
|
+
// path has no url, so no await runs and its prompt still emits synchronously
|
|
1679
|
+
// (autoAllowPending / pending-size assertions depend on that).
|
|
1680
|
+
const resolved = isRemote
|
|
1681
|
+
? await resolveTrustAddress(safeUrl, { lookup: this._mcpTrustLookup || undefined })
|
|
1682
|
+
: null
|
|
651
1683
|
return new Promise((resolve) => {
|
|
652
1684
|
const requestId = `mcp-trust-${this._idNonce}-${++this._permissionCounter}-${Date.now()}`
|
|
653
1685
|
const argv0 = Array.isArray(server.args) && server.args.length > 0 ? server.args[0] : ''
|
|
654
1686
|
const input = {
|
|
655
|
-
mcpServer:
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
1687
|
+
mcpServer: isRemote
|
|
1688
|
+
? {
|
|
1689
|
+
name: server.name,
|
|
1690
|
+
url: safeUrl,
|
|
1691
|
+
headerKeys: Array.isArray(server.headerKeys) ? [...server.headerKeys] : [],
|
|
1692
|
+
// Structured mirror of the resolved-address marker embedded in
|
|
1693
|
+
// `description`. Plain strings/arrays/bools — survives
|
|
1694
|
+
// sanitizeToolInput untouched — so a client that renders MCP-trust
|
|
1695
|
+
// input structurally can surface it without re-parsing the string.
|
|
1696
|
+
resolvedAddress: resolved
|
|
1697
|
+
? {
|
|
1698
|
+
resolved: resolved.resolved,
|
|
1699
|
+
addresses: resolved.addresses,
|
|
1700
|
+
classification: resolved.classification,
|
|
1701
|
+
display: resolved.display,
|
|
1702
|
+
}
|
|
1703
|
+
: null,
|
|
1704
|
+
// #7939: OMITTED (not null) when absent/unrecognized, matching
|
|
1705
|
+
// every other optional field on this payload — a client that
|
|
1706
|
+
// doesn't know the field yet just doesn't see the key.
|
|
1707
|
+
...(source ? { source } : {}),
|
|
1708
|
+
}
|
|
1709
|
+
: {
|
|
1710
|
+
name: server.name,
|
|
1711
|
+
command: server.command,
|
|
1712
|
+
args: Array.isArray(server.args) ? [...server.args] : [],
|
|
1713
|
+
envKeys: Array.isArray(server.envKeys) ? [...server.envKeys] : [],
|
|
1714
|
+
// #7939: see the remote branch's comment above.
|
|
1715
|
+
...(source ? { source } : {}),
|
|
1716
|
+
},
|
|
661
1717
|
}
|
|
662
|
-
const description =
|
|
1718
|
+
const description = isRemote
|
|
1719
|
+
? `Connect to MCP server "${server.name}" at ${safeUrl}${resolved ? ` — ${resolved.display}` : ''}`
|
|
1720
|
+
: `Spawn MCP server "${server.name}" running ${server.command}${argv0 ? ' ' + argv0 : ''}`
|
|
663
1721
|
|
|
664
1722
|
// Wrap pending entry so respondToPermission's standard mapping
|
|
665
1723
|
// ({behavior:'allow'} or {behavior:'deny'}) translates to a boolean
|
|
@@ -686,13 +1744,24 @@ export class PermissionManager extends EventEmitter {
|
|
|
686
1744
|
// #6038: redact before broadcast (description embeds server.command/argv0;
|
|
687
1745
|
// input carries args/envKeys). Raw values for execution live on the
|
|
688
1746
|
// _pendingPermissions entry above.
|
|
1747
|
+
// #7968: mcp_spawn carries no PROTECTED_PATH_INPUT_FIELDS (its input is
|
|
1748
|
+
// `{ mcpServer: {...} }`, not a bare file_path/path/notebook_path), so
|
|
1749
|
+
// isFlooredTarget is always false here — computed rather than hardcoded
|
|
1750
|
+
// so this stays correct if that ever changes.
|
|
1751
|
+
const shownDescription = describeComposedText(description)
|
|
689
1752
|
const permPayload = {
|
|
690
1753
|
requestId,
|
|
691
1754
|
tool: 'mcp_spawn',
|
|
692
|
-
description:
|
|
1755
|
+
description: shownDescription,
|
|
693
1756
|
input: sanitizeToolInput(input),
|
|
694
1757
|
remainingMs: this._timeoutMs,
|
|
695
1758
|
createdAt: Date.now(),
|
|
1759
|
+
floored: isFlooredTarget('mcp_spawn', input, this._cwd),
|
|
1760
|
+
explicitConsent: false,
|
|
1761
|
+
nonDelegable: true,
|
|
1762
|
+
// #8348: for the permission transcript (see handlePermission). The
|
|
1763
|
+
// shown description is already redacted and clipped.
|
|
1764
|
+
recordDescription: shownDescription,
|
|
696
1765
|
}
|
|
697
1766
|
this._lastPermissionData.set(requestId, permPayload)
|
|
698
1767
|
this.emit('permission_request', permPayload)
|
|
@@ -826,4 +1895,16 @@ export function wirePermissionManager(session, permissions, { onRequest, onResol
|
|
|
826
1895
|
// Backward-compatible accessors used by ws-permissions.js + settings-handlers.js.
|
|
827
1896
|
session._pendingPermissions = permissions._pendingPermissions
|
|
828
1897
|
session._lastPermissionData = permissions._lastPermissionData
|
|
1898
|
+
// #7457 -- delegate the still-blocked AskUserQuestion set, read after every
|
|
1899
|
+
// history replay by `ws-history.resendPendingQuestions`. Installed HERE, once,
|
|
1900
|
+
// rather than as three identical overrides on SdkSession / ByokSession /
|
|
1901
|
+
// CodexAppServerSession: those are exactly the hand-copied parallel wirings
|
|
1902
|
+
// audit P2-9 folded into this function, and the third copy is always the one
|
|
1903
|
+
// that gets forgotten. Shadows BaseSession's empty default as an own property.
|
|
1904
|
+
session.getPendingQuestions = () => permissions.getPendingQuestions()
|
|
1905
|
+
// #6830 (PR #6842 review) — public delegate so the WsServer can wire its
|
|
1906
|
+
// PermissionAuditLog straight into this manager's persisted-rule audit path
|
|
1907
|
+
// (ws-server.js _attachPermissionAuditSink) without reaching into privates.
|
|
1908
|
+
// Installed for every wirePermissionManager provider (sdk / byok / codex).
|
|
1909
|
+
session.setPermissionAuditSink = (sink) => permissions.setAuditSink(sink)
|
|
829
1910
|
}
|