@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
package/src/ws-permissions.js
CHANGED
|
@@ -3,15 +3,99 @@ import { createLogger } from './logger.js'
|
|
|
3
3
|
import { RateLimiter, getRateLimitKey } from './rate-limiter.js'
|
|
4
4
|
import { buildSessionTokenMismatchPayload } from './handler-utils.js'
|
|
5
5
|
import { settlePush } from './push.js'
|
|
6
|
-
import { createPermissionResolver } from './permission-resolver.js'
|
|
6
|
+
import { createPermissionResolver, buildLegacyResolvedBroadcast } from './permission-resolver.js'
|
|
7
7
|
import { sendOversizeResponse } from './http-oversize.js'
|
|
8
|
-
import {
|
|
8
|
+
import { sanitizeToolInput, describeByNamedField, describeToolInput } from './redaction.js'
|
|
9
|
+
// #7004: the protected-path / secret-read FLOOR. Imported from permission-floor.js
|
|
10
|
+
// — the leaf module that is the SINGLE source of the floor — so the hook-routed
|
|
11
|
+
// path applies the byte-identical predicate the in-process path
|
|
12
|
+
// (permission-manager.js handlePermission) does. Never reimplement it here or in
|
|
13
|
+
// the shell hook.
|
|
14
|
+
import { isFlooredTarget } from './permission-floor.js'
|
|
9
15
|
import { buildPermissionRequestMessage } from '@chroxy/protocol'
|
|
16
|
+
import { isBoundClient } from './environments/authority.js'
|
|
17
|
+
import { NOT_DELEGABLE_TOOLS } from './permission-manager.js'
|
|
18
|
+
import { HOOK_PERMISSION_DECISION_WINDOW_MS } from './permission-deadlines.js'
|
|
10
19
|
|
|
11
20
|
const log = createLogger('ws')
|
|
12
21
|
|
|
13
22
|
// -- Permission TTL --
|
|
14
|
-
|
|
23
|
+
// The hook-routed prompt's decision window (5 minutes). One number for the
|
|
24
|
+
// daemon's auto-deny timer and for the countdown clients are told to show; the
|
|
25
|
+
// hook's transport timeout and the host's hook timeout are derived from it in
|
|
26
|
+
// permission-deadlines.js and must stay longer than it.
|
|
27
|
+
const PERMISSION_TTL_MS = HOOK_PERMISSION_DECISION_WINDOW_MS
|
|
28
|
+
|
|
29
|
+
// #7004 — body cap for POST /permission-floor. Deliberately MUCH larger than
|
|
30
|
+
// /permission's 64KB, for two reasons:
|
|
31
|
+
// 1. Nothing is retained. /permission's cap bounds a request that is HELD for up
|
|
32
|
+
// to 5 minutes with its payload stashed in `pendingPermissions`; the floor
|
|
33
|
+
// probe parses the body, answers a boolean, and drops it inside one tick.
|
|
34
|
+
// 2. Over-capping here would BREAK legitimate work rather than merely prompt for
|
|
35
|
+
// it. The hook POSTs the whole PreToolUse payload, and a `Write` carries its
|
|
36
|
+
// full `content` — a >64KB file write in auto/acceptEdits would 413, and the
|
|
37
|
+
// hook's fail-closed rule would then route it to a prompt whose own POST is
|
|
38
|
+
// likewise oversize (a deny). 1 MiB keeps every realistic write on the
|
|
39
|
+
// auto-allow path; a payload past it is pathological and still fails CLOSED.
|
|
40
|
+
const MAX_FLOOR_BODY = 1_048_576
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* #7004 — the hook path's floor decision for one PreToolUse payload.
|
|
44
|
+
*
|
|
45
|
+
* Pure, and exported for tests: the HTTP handler below is only auth + body
|
|
46
|
+
* plumbing around this. The floor VERDICT itself comes from
|
|
47
|
+
* {@link isFlooredTarget} (permission-floor.js), the same call
|
|
48
|
+
* `permission-manager.js` `handlePermission` makes — so the two pipelines cannot
|
|
49
|
+
* disagree about which tool gets which floor or how targets are extracted.
|
|
50
|
+
*
|
|
51
|
+
* FAILS CLOSED on an ambiguous payload — a floored verdict only ever forces the
|
|
52
|
+
* interactive PROMPT (never a deny), so "prompt when unsure" costs one prompt,
|
|
53
|
+
* whereas guessing `false` would silently auto-approve a target we could not
|
|
54
|
+
* inspect. Ambiguous means: a non-object payload, a missing/blank `tool_name`, a
|
|
55
|
+
* missing or non-object `tool_input` (a path-carrying tool call always has one),
|
|
56
|
+
* or no resolvable cwd to anchor the resolution on. This is deliberately STRICTER
|
|
57
|
+
* than the in-process path, which receives already-typed inputs from the SDK
|
|
58
|
+
* rather than parsing an HTTP body.
|
|
59
|
+
*
|
|
60
|
+
* The cwd basis is the OWNING SESSION's cwd (`session.cwd` — exactly what
|
|
61
|
+
* `PermissionManager` is constructed with, `cwd: this.cwd`) and NOTHING ELSE. It
|
|
62
|
+
* never falls back to the daemon's `process.cwd()`, and (#7020) never to the
|
|
63
|
+
* payload's own `cwd`: both are resolution bases the floor did not choose, and
|
|
64
|
+
* resolving a target against the wrong root UNDER-floors. The payload case is the
|
|
65
|
+
* sharper of the two because it is CALLER-chosen — naming the protected directory
|
|
66
|
+
* itself as the base makes the relative scan see nothing protected (target
|
|
67
|
+
* `/repo/.git/config` with `cwd: "/repo/.git"` scans just `config` → `floor:
|
|
68
|
+
* false`). `session.cwd` is always a real string (`BaseSession` sets
|
|
69
|
+
* `cwd || process.cwd()`), including in legacy single-session mode where
|
|
70
|
+
* `_findSessionByHookSecret` returns `{ session, sessionId: null }`, so the only
|
|
71
|
+
* shape this rejects is one where the owning session genuinely cannot be
|
|
72
|
+
* resolved — e.g. `_validateHookAuth` taking its primary-token fallback with no
|
|
73
|
+
* hook secrets registered. That answers `floor: true` (one prompt), not `false`.
|
|
74
|
+
*
|
|
75
|
+
* @param {*} hookData the parsed PreToolUse payload (untrusted)
|
|
76
|
+
* @param {string|null} sessionCwd the owning session's cwd, when resolvable
|
|
77
|
+
* @returns {{ floor: boolean, reason: string }}
|
|
78
|
+
*/
|
|
79
|
+
export function evaluateHookFloorRequest(hookData, sessionCwd) {
|
|
80
|
+
if (!hookData || typeof hookData !== 'object' || Array.isArray(hookData)) {
|
|
81
|
+
return { floor: true, reason: 'payload is not an object' }
|
|
82
|
+
}
|
|
83
|
+
const tool = hookData.tool_name
|
|
84
|
+
if (typeof tool !== 'string' || tool.length === 0) {
|
|
85
|
+
return { floor: true, reason: 'missing tool_name' }
|
|
86
|
+
}
|
|
87
|
+
const input = hookData.tool_input
|
|
88
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
|
89
|
+
return { floor: true, reason: 'missing or non-object tool_input' }
|
|
90
|
+
}
|
|
91
|
+
// #7020 — the OWNING SESSION's cwd is the only accepted resolution base. Never
|
|
92
|
+
// `hookData.cwd` (caller-chosen → under-floors), never `process.cwd()`.
|
|
93
|
+
const cwd = (typeof sessionCwd === 'string' && sessionCwd.length > 0) ? sessionCwd : null
|
|
94
|
+
if (!cwd) {
|
|
95
|
+
return { floor: true, reason: 'no resolvable session cwd' }
|
|
96
|
+
}
|
|
97
|
+
return { floor: isFlooredTarget(tool, input, cwd), reason: 'floor predicate' }
|
|
98
|
+
}
|
|
15
99
|
|
|
16
100
|
// -- Broadcast safety --
|
|
17
101
|
// `sanitizeToolInput` (key-name + recursive value-shape redaction) lives in
|
|
@@ -21,22 +105,16 @@ const PERMISSION_TTL_MS = 300_000 // 5 minutes
|
|
|
21
105
|
|
|
22
106
|
/**
|
|
23
107
|
* Build the human-readable `description` broadcast alongside a permission
|
|
24
|
-
* request.
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* the
|
|
108
|
+
* request. The description is derived from the RAW tool input and broadcast next
|
|
109
|
+
* to the sanitized `input`, so it is built by `describeToolInput` (redaction.js),
|
|
110
|
+
* the one place a description is derived: from the identifying field, or else
|
|
111
|
+
* from the SANITIZED input, so a masked field reads the same in both (#8384).
|
|
28
112
|
*
|
|
29
113
|
* @param {object} toolInput
|
|
30
114
|
* @returns {string}
|
|
31
115
|
*/
|
|
32
116
|
function buildPermissionDescription(toolInput) {
|
|
33
|
-
|
|
34
|
-
|| toolInput.command
|
|
35
|
-
|| toolInput.file_path
|
|
36
|
-
|| toolInput.pattern
|
|
37
|
-
|| toolInput.query
|
|
38
|
-
|| JSON.stringify(toolInput).slice(0, 200)
|
|
39
|
-
return redactValue(raw)
|
|
117
|
+
return describeToolInput(toolInput, '{}')
|
|
40
118
|
}
|
|
41
119
|
|
|
42
120
|
/**
|
|
@@ -58,13 +136,21 @@ function sendJson(res, status, body, extraHeaders) {
|
|
|
58
136
|
res.end(JSON.stringify(body))
|
|
59
137
|
}
|
|
60
138
|
|
|
139
|
+
/**
|
|
140
|
+
* Recipient filter for a permission frame that maps to no session: it carries
|
|
141
|
+
* no `sessionId`, so a session-bound client has no session it could belong to
|
|
142
|
+
* and does not receive it. Frames attributed to a session keep the unfiltered
|
|
143
|
+
* fan-out (the broadcaster's per-session delivery check applies to them).
|
|
144
|
+
*/
|
|
145
|
+
const unboundOnly = (client) => !isBoundClient(client)
|
|
146
|
+
|
|
61
147
|
/**
|
|
62
148
|
* Create a permission handler for the WsServer.
|
|
63
149
|
* Manages HTTP permission lifecycle (hook requests, responses, resend, resolve).
|
|
64
150
|
*
|
|
65
151
|
* @param {Object} opts
|
|
66
152
|
* @param {Function} opts.sendFn - (ws, message) => void
|
|
67
|
-
* @param {Function} opts.broadcastFn - (message) => void
|
|
153
|
+
* @param {Function} opts.broadcastFn - (message, filter?) => void
|
|
68
154
|
* @param {Function} opts.validateBearerAuth - (req, res) => boolean — validates main API token (used by /permission-response)
|
|
69
155
|
* @param {Function} opts.validateHookAuth - (req, res) => boolean — validates per-session hook secret (used by /permission)
|
|
70
156
|
* @param {Object|null} opts.pushManager - PushManager instance (nullable)
|
|
@@ -79,7 +165,12 @@ function sendJson(res, status, body, extraHeaders) {
|
|
|
79
165
|
* @param {Object} [opts.rateLimit] - Override RateLimiter config for POST /permission. Mainly for tests; production uses the 30+10 default below.
|
|
80
166
|
* @returns {Object} Permission handler methods
|
|
81
167
|
*/
|
|
82
|
-
|
|
168
|
+
// No re-check wired: refuse, like the hook validator default below. ws-server.js
|
|
169
|
+
// always passes the real pair (tests/bearer-recheck.test.js checks it).
|
|
170
|
+
const defaultCaptureBearer = () => null
|
|
171
|
+
const defaultBearerStillValid = () => false
|
|
172
|
+
|
|
173
|
+
export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAuth, validateHookAuth, captureBearer = defaultCaptureBearer, bearerStillValid = defaultBearerStillValid, pushManager, pendingPermissions, permissionSessionMap, registerPermissionRoute, unregisterPermissionRoute, getSessionManager, pairingManager, findSessionByHookSecret, getPermissionAudit, rateLimit }) {
|
|
83
174
|
let _permissionCounter = 0
|
|
84
175
|
|
|
85
176
|
// Rate limiter for HTTP permission requests (per source IP)
|
|
@@ -90,8 +181,25 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
90
181
|
// tag that operators rely on in eviction logs and /diagnostics.
|
|
91
182
|
const _httpPermissionLimiter = new RateLimiter({ ...(rateLimit || { windowMs: 60_000, maxMessages: 30, burst: 10 }), name: 'http-permission' })
|
|
92
183
|
|
|
93
|
-
//
|
|
94
|
-
|
|
184
|
+
// #7004 — separate, MUCH larger budget for POST /permission-floor. Unlike
|
|
185
|
+
// /permission (one request per HUMAN decision, so 30/min is generous), the floor
|
|
186
|
+
// probe fires once per TOOL CALL while a lenient mode is active — machine speed.
|
|
187
|
+
// A budget as low as /permission's would rate-limit the probe, and because the
|
|
188
|
+
// hook fails CLOSED on anything but an explicit `floor:false` that would turn a
|
|
189
|
+
// busy auto-mode session into a prompt storm (and then, with /permission itself
|
|
190
|
+
// limited, a deny storm). 600/min + 200 burst sits far above any real session's
|
|
191
|
+
// tool-call rate while still bounding an abusive caller; the work per request is
|
|
192
|
+
// a few lstat/realpath calls, so the ceiling is about bounding, not cost.
|
|
193
|
+
// Overridable via `rateLimit.floor` for tests.
|
|
194
|
+
const _httpFloorLimiter = new RateLimiter({ ...(rateLimit?.floor || { windowMs: 60_000, maxMessages: 600, burst: 200 }), name: 'http-permission-floor' })
|
|
195
|
+
|
|
196
|
+
// No hook validator supplied: refuse. Never fall back to the bearer check,
|
|
197
|
+
// which a scoped client may be allowed to pass.
|
|
198
|
+
const _validateHookAuth = validateHookAuth || ((req, res) => {
|
|
199
|
+
res.writeHead(403, { 'Content-Type': 'application/json' })
|
|
200
|
+
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
201
|
+
return false
|
|
202
|
+
})
|
|
95
203
|
|
|
96
204
|
// #5704: tear down a permission route's map entry AND its permission-induced
|
|
97
205
|
// subscription refcount together. Prefer the WsServer-provided hook (which
|
|
@@ -103,6 +211,25 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
103
211
|
else permissionSessionMap.delete(requestId)
|
|
104
212
|
}
|
|
105
213
|
|
|
214
|
+
// #8348: the permission transcript is journaled by the session manager (see
|
|
215
|
+
// SessionManager#recordPermissionOutcome). Both calls tolerate a manager that
|
|
216
|
+
// lacks the methods -- unit fixtures hand this factory a stub -- and a failure
|
|
217
|
+
// to journal must never disturb the permission response itself.
|
|
218
|
+
function recordPermissionRaised(sessionId, request) {
|
|
219
|
+
try {
|
|
220
|
+
getSessionManager?.()?.notePermissionRequest?.(sessionId, request)
|
|
221
|
+
} catch (err) {
|
|
222
|
+
log.warn(`Failed to note permission ${request?.requestId} for the transcript: ${err?.message || err}`)
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function recordPermissionEnded(requestId, outcome) {
|
|
226
|
+
try {
|
|
227
|
+
getSessionManager?.()?.recordPermissionOutcome?.(requestId, outcome)
|
|
228
|
+
} catch (err) {
|
|
229
|
+
log.warn(`Failed to record permission ${requestId} outcome for the transcript: ${err?.message || err}`)
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
106
233
|
// #5373: the session-binding check + SDK-vs-legacy dispatch + audit live in
|
|
107
234
|
// the shared permission-resolver (also used by the WS handler in
|
|
108
235
|
// settings-handlers.js), so the binding rule lives in ONE place. The HTTP
|
|
@@ -149,8 +276,10 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
149
276
|
let body = ''
|
|
150
277
|
let bodyBytes = 0
|
|
151
278
|
let oversized = false
|
|
279
|
+
let streamFailed = false
|
|
280
|
+
let ended = false
|
|
152
281
|
req.on('data', (chunk) => {
|
|
153
|
-
if (oversized) return
|
|
282
|
+
if (oversized || streamFailed) return
|
|
154
283
|
bodyBytes += Buffer.byteLength(chunk, 'utf8')
|
|
155
284
|
if (bodyBytes > MAX_BODY) {
|
|
156
285
|
oversized = true
|
|
@@ -164,7 +293,34 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
164
293
|
}
|
|
165
294
|
body += chunk
|
|
166
295
|
})
|
|
296
|
+
// #7020 — same omission the floor route had: an 'error' on a stream with no
|
|
297
|
+
// listener rethrows into uncaughtException. A mid-body abort answers a DENY,
|
|
298
|
+
// so this route's fail-closed contract holds on the torn-down path too.
|
|
299
|
+
//
|
|
300
|
+
// ONLY while the body is still being read. Unlike every other capped reader in
|
|
301
|
+
// this file, THIS route's 'end' handler does not respond — it registers a
|
|
302
|
+
// `pendingPermissions` entry and DEFERS the response for up to five minutes
|
|
303
|
+
// while the prompt sits on the user's phone. So a post-'end' 'error' must be a
|
|
304
|
+
// no-op on both counts: answering a 400 there would (a) send a second response
|
|
305
|
+
// on a socket the pending entry still owns — the later `resolve()` then throws
|
|
306
|
+
// ERR_HTTP_HEADERS_SENT on the #5313 tick that reaches uncaughtException — and
|
|
307
|
+
// (b) DENY, from a transient stream error, a request the user is still looking
|
|
308
|
+
// at, while leaving the pending entry alive. Teardown after 'end' belongs to
|
|
309
|
+
// the existing `req 'aborted'` / `res 'close'` → onClose path, which cleans the
|
|
310
|
+
// map up and leaves `closed` set so nothing responds twice.
|
|
311
|
+
req.on('error', (err) => {
|
|
312
|
+
streamFailed = true
|
|
313
|
+
log.warn(`POST /permission request stream error: ${err?.message || err}`)
|
|
314
|
+
if (ended) return
|
|
315
|
+
try {
|
|
316
|
+
if (!res.headersSent) sendJson(res, 400, { decision: 'deny' })
|
|
317
|
+
else res.end()
|
|
318
|
+
} catch { /* socket already torn down */ }
|
|
319
|
+
})
|
|
167
320
|
req.on('end', () => {
|
|
321
|
+
// Claim the response BEFORE anything below can defer it (see the 'error'
|
|
322
|
+
// listener above) — this must hold even on the paths that return early.
|
|
323
|
+
ended = true
|
|
168
324
|
// #5313 (WP-1.3): this callback fires on a later tick, after the HTTP
|
|
169
325
|
// dispatch that registered it has already returned — so a throw here is
|
|
170
326
|
// NOT caught by the route handler's wrapper and escapes to
|
|
@@ -172,9 +328,16 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
172
328
|
// JSON.parse is already guarded; this wraps the WHOLE body (res.writeHead
|
|
173
329
|
// on a torn-down socket, downstream session/broadcast calls) so any other
|
|
174
330
|
// throw is contained and returns a 500 to the client when possible.
|
|
331
|
+
// #8529: set once the owning session has been told a prompt is pending,
|
|
332
|
+
// cleared once cleanup() owns telling it the prompt ended. If anything in
|
|
333
|
+
// between throws, the catch below uses it, so the session is not left
|
|
334
|
+
// believing a prompt is outstanding (which pauses its inactivity timers)
|
|
335
|
+
// for a request that was answered 500 and never held.
|
|
336
|
+
let releaseOwnerPause = null
|
|
175
337
|
try {
|
|
176
338
|
// #5433: the 413 deny was already sent from the 'data' handler.
|
|
177
|
-
|
|
339
|
+
// #7020: ditto the 400 deny from the 'error' handler.
|
|
340
|
+
if (oversized || streamFailed) return
|
|
178
341
|
|
|
179
342
|
let hookData
|
|
180
343
|
try {
|
|
@@ -192,6 +355,20 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
192
355
|
const toolInput = hookData.tool_input || {}
|
|
193
356
|
const sanitizedInput = sanitizeToolInput(toolInput)
|
|
194
357
|
const description = buildPermissionDescription(toolInput)
|
|
358
|
+
// #8357: the provider's id for this tool call, as the hook payload names it.
|
|
359
|
+
// For an AskUserQuestion it is the very id `user_question` carries (the
|
|
360
|
+
// session reads the same payload field), which is how a client pairs the
|
|
361
|
+
// prompt with its question card. Absent when the payload omits it (older
|
|
362
|
+
// claude builds), in which case no pairing id is claimed.
|
|
363
|
+
const toolUseId = typeof hookData.tool_use_id === 'string'
|
|
364
|
+
&& hookData.tool_use_id.length > 0 && hookData.tool_use_id.length <= 200
|
|
365
|
+
? hookData.tool_use_id
|
|
366
|
+
: undefined
|
|
367
|
+
if (tool === 'AskUserQuestion' && !toolUseId) {
|
|
368
|
+
// #8357: without the id the question card cannot be paired with this
|
|
369
|
+
// prompt. Say so, so a Claude build that omits it is visible.
|
|
370
|
+
log.warn(`AskUserQuestion permission ${requestId} arrived with no usable tool_use_id; its question card is gated only while this prompt is pending`)
|
|
371
|
+
}
|
|
195
372
|
|
|
196
373
|
// #2831: find the CliSession this hook permission belongs to (via
|
|
197
374
|
// the per-session hook secret from the Authorization header) so we
|
|
@@ -210,6 +387,9 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
210
387
|
const ownerSessionId = ownerLookup?.sessionId ?? null
|
|
211
388
|
if (ownerSession && typeof ownerSession.notifyPermissionPending === 'function') {
|
|
212
389
|
ownerSession.notifyPermissionPending(requestId)
|
|
390
|
+
if (typeof ownerSession.notifyPermissionResolved === 'function') {
|
|
391
|
+
releaseOwnerPause = () => ownerSession.notifyPermissionResolved(requestId)
|
|
392
|
+
}
|
|
213
393
|
}
|
|
214
394
|
if (ownerSessionId) {
|
|
215
395
|
// #4798: prefer the WsServer-provided helper so dispatch also auto-
|
|
@@ -232,12 +412,25 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
232
412
|
// with `LOG_LEVEL=debug` when triangulating SESSION_TOKEN_MISMATCH.
|
|
233
413
|
log.debug(`[session-binding-create] permission ${requestId} created via HTTP (sessionId=${ownerSessionId ?? 'none'}, sourceIp=${clientIp})`)
|
|
234
414
|
|
|
415
|
+
// #7968 — the SAME floor verdict `POST /permission-floor` would answer
|
|
416
|
+
// for this exact tool call, via the SAME evaluateHookFloorRequest (which
|
|
417
|
+
// itself calls the single-source isFlooredTarget). The cwd basis is the
|
|
418
|
+
// OWNING SESSION's cwd (`ownerSession.cwd`, resolved above from the
|
|
419
|
+
// presented hook secret) — never the daemon's `process.cwd()` and never
|
|
420
|
+
// the payload's own `cwd` (#7020: a caller-chosen base can under-floor).
|
|
421
|
+
// An unresolvable session fails CLOSED (floored:true), matching
|
|
422
|
+
// handlePermissionFloorCheck's own fail-closed contract.
|
|
423
|
+
const floored = evaluateHookFloorRequest(hookData, ownerSession?.cwd ?? null).floor
|
|
424
|
+
|
|
235
425
|
broadcastFn(buildPermissionRequestMessage({
|
|
236
426
|
requestId,
|
|
237
427
|
tool,
|
|
238
428
|
description,
|
|
239
429
|
input: sanitizedInput,
|
|
240
|
-
remainingMs:
|
|
430
|
+
remainingMs: PERMISSION_TTL_MS,
|
|
431
|
+
floored,
|
|
432
|
+
explicitConsent: false,
|
|
433
|
+
nonDelegable: NOT_DELEGABLE_TOOLS.has(tool),
|
|
241
434
|
// #5667: carry the owning session so clients route the prompt to the
|
|
242
435
|
// session that actually asked, instead of falling back to whatever tab
|
|
243
436
|
// is focused. Matches the resend-on-reconnect (line ~485) and SDK
|
|
@@ -245,14 +438,32 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
245
438
|
// `sessionId` entirely (absent, not null) when undefined — the request
|
|
246
439
|
// maps to no chroxy session and clients fall back to the active one.
|
|
247
440
|
sessionId: ownerSessionId || undefined,
|
|
248
|
-
|
|
441
|
+
toolUseId,
|
|
442
|
+
}), ownerSessionId ? undefined : unboundOnly)
|
|
443
|
+
|
|
444
|
+
// #8348: a hook-routed prompt never passes through a session event, so
|
|
445
|
+
// tell the session manager what was just shown. It is what lets the
|
|
446
|
+
// prompt's outcome be recorded in the session's transcript when it ends,
|
|
447
|
+
// so a session switch or reload can still show it. An unattributable
|
|
448
|
+
// prompt (no owning session) has no transcript to be recorded in.
|
|
449
|
+
if (ownerSessionId) {
|
|
450
|
+
recordPermissionRaised(ownerSessionId, { requestId, tool, description, input: sanitizedInput, recordDescription: describeByNamedField(toolInput), toolUseId })
|
|
451
|
+
}
|
|
249
452
|
|
|
250
453
|
if (pushManager) {
|
|
251
454
|
// #5702 (8d): settle the fire-and-forget send so a failed phone
|
|
252
455
|
// notification is logged (named), not silently dropped while the
|
|
253
456
|
// dashboard card still appears.
|
|
457
|
+
// #6792: carry the owning sessionId in the push data payload (data-only,
|
|
458
|
+
// doesn't change the visible notification) so the app can route a
|
|
459
|
+
// notification tap straight to the session that asked, instead of the
|
|
460
|
+
// OS just opening the app to its default screen. Mirrors the
|
|
461
|
+
// sessionId already included in the broadcastFn call above (#5667)
|
|
462
|
+
// and in the activity_update/activity_waiting/inactivity_warning
|
|
463
|
+
// pushes (push-notification-handler.js). Omitted (not null) when the
|
|
464
|
+
// request maps to no chroxy session, matching the broadcast's convention.
|
|
254
465
|
settlePush(
|
|
255
|
-
pushManager.send('permission', 'Permission needed', `Claude wants to use: ${tool}`, { requestId, tool }, 'permission'),
|
|
466
|
+
pushManager.send('permission', 'Permission needed', `Claude wants to use: ${tool}`, { requestId, tool, sessionId: ownerSessionId || undefined }, 'permission'),
|
|
256
467
|
`permission requested: ${tool}`,
|
|
257
468
|
log,
|
|
258
469
|
)
|
|
@@ -280,6 +491,11 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
280
491
|
closed = true
|
|
281
492
|
log.info(`Permission ${requestId} connection closed by client`)
|
|
282
493
|
cleanup()
|
|
494
|
+
// #8348: the hook went away with no answer (its turn died or it was
|
|
495
|
+
// killed): the prompt ended undecided. A session that reported the turn's
|
|
496
|
+
// death has already recorded this (`permission_expired`); the second call
|
|
497
|
+
// finds nothing to record.
|
|
498
|
+
recordPermissionEnded(requestId, 'expired')
|
|
283
499
|
}
|
|
284
500
|
|
|
285
501
|
req.on('aborted', onClose)
|
|
@@ -290,8 +506,19 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
290
506
|
closed = true
|
|
291
507
|
log.info(`Permission ${requestId} timed out, auto-denying`)
|
|
292
508
|
cleanup()
|
|
293
|
-
|
|
294
|
-
|
|
509
|
+
// #8348: nobody answered in time. The clients' own countdown shows this
|
|
510
|
+
// as "Timed out"; record it so the transcript still does after a switch.
|
|
511
|
+
recordPermissionEnded(requestId, 'expired')
|
|
512
|
+
// #8529: say WHY. Without `reason` this body is byte-identical to a real
|
|
513
|
+
// user deny, and permission-hook.sh told the model "Denied by user" about
|
|
514
|
+
// a prompt nobody answered. `decision` stays 'deny' (fail closed), so a
|
|
515
|
+
// hook that predates the field reads this exactly as it always did. Only
|
|
516
|
+
// this timer sets it. Every other deny goes out through `resolve` below
|
|
517
|
+
// with no reason: a human's, and also the daemon's own releases (an
|
|
518
|
+
// abandoned turn, a destroyed session, shutdown), which the hook
|
|
519
|
+
// therefore still words as a user deny.
|
|
520
|
+
sendJson(res, 200, { decision: 'deny', reason: 'timeout' })
|
|
521
|
+
}, PERMISSION_TTL_MS)
|
|
295
522
|
|
|
296
523
|
pendingPermissions.set(requestId, {
|
|
297
524
|
resolve: (decision) => {
|
|
@@ -302,9 +529,17 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
302
529
|
sendJson(res, 200, { decision })
|
|
303
530
|
},
|
|
304
531
|
timer,
|
|
305
|
-
|
|
532
|
+
// #7968: stash the SAME floor verdict computed above so a reconnect
|
|
533
|
+
// resend (resendPendingPermissions' legacy-HTTP branch) replays it
|
|
534
|
+
// rather than re-deriving (or silently dropping) it.
|
|
535
|
+
data: { requestId, tool, description, input: sanitizedInput, remainingMs: PERMISSION_TTL_MS, createdAt: Date.now(), floored, explicitConsent: false, nonDelegable: NOT_DELEGABLE_TOOLS.has(tool), ...(toolUseId ? { toolUseId } : {}) },
|
|
306
536
|
})
|
|
537
|
+
// Held: from here cleanup() releases the session's pause on every path.
|
|
538
|
+
releaseOwnerPause = null
|
|
307
539
|
} catch (err) {
|
|
540
|
+
if (releaseOwnerPause) {
|
|
541
|
+
try { releaseOwnerPause() } catch { /* the session is already gone */ }
|
|
542
|
+
}
|
|
308
543
|
// #5313 (WP-1.3): see the try at the top of this end callback.
|
|
309
544
|
const message = err?.message || String(err)
|
|
310
545
|
log.error(`POST /permission end handler threw: ${message}${err?.stack ? '\n' + err.stack : ''}`)
|
|
@@ -322,6 +557,137 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
322
557
|
})
|
|
323
558
|
}
|
|
324
559
|
|
|
560
|
+
/**
|
|
561
|
+
* #7004 — Handle POST /permission-floor from the hook script.
|
|
562
|
+
*
|
|
563
|
+
* WHY THIS EXISTS. `hooks/permission-hook.sh` decides `auto` and `acceptEdits`
|
|
564
|
+
* ITSELF, in shell, and never reaches `permission-manager.js` — so the
|
|
565
|
+
* protected-path / secret-read floor that #6794/#6803 put in front of every
|
|
566
|
+
* lenient-mode short-circuit did not exist for the hook-routed providers
|
|
567
|
+
* (claude-tui — the DEFAULT provider — and cli-session). Under `auto` /
|
|
568
|
+
* `acceptEdits` those sessions read `.env` / `id_rsa` and wrote into `.git`/
|
|
569
|
+
* `.claude` with no prompt.
|
|
570
|
+
*
|
|
571
|
+
* The floor is non-trivial path logic (lexical + symlink component-walk,
|
|
572
|
+
* fail-closed), so reimplementing it in bash would guarantee drift. Instead the
|
|
573
|
+
* hook asks the daemon: this route answers the ONE question the shell cannot,
|
|
574
|
+
* `{ floor: true | false }`, using the shared {@link isFlooredTarget}. The hook
|
|
575
|
+
* treats ONLY an explicit `floor:false` as clearance to short-circuit;
|
|
576
|
+
* everything else (floored, 4xx, 429, 5xx, an unparseable body, an unreachable
|
|
577
|
+
* daemon) routes the call to a real prompt. So every failure mode here degrades
|
|
578
|
+
* to "the user is asked", never to "silently allowed".
|
|
579
|
+
*
|
|
580
|
+
* Deliberately NOT a permission request: it creates no pending entry, mints no
|
|
581
|
+
* requestId, broadcasts nothing and sends no push. It is a read-only predicate
|
|
582
|
+
* over a path the caller already supplied, gated on the same per-session hook
|
|
583
|
+
* secret as `POST /permission` (see docs/security/bearer-token-authority.md §5).
|
|
584
|
+
*/
|
|
585
|
+
function handlePermissionFloorCheck(req, res) {
|
|
586
|
+
// Rate limit by source IP — see getRateLimitKey's note on the cloudflared
|
|
587
|
+
// loopback peer in handlePermissionRequest above. A 429 answers `floor:true`
|
|
588
|
+
// so a limited caller still fails CLOSED (prompt), never open.
|
|
589
|
+
const socketIp = req.socket?.remoteAddress || ''
|
|
590
|
+
const clientIp = getRateLimitKey(socketIp, req)
|
|
591
|
+
const { allowed, retryAfterMs } = _httpFloorLimiter.check(clientIp)
|
|
592
|
+
if (!allowed) {
|
|
593
|
+
log.warn(`Rate limited POST /permission-floor from ${clientIp}`)
|
|
594
|
+
sendJson(res, 429, { error: 'rate limited', floor: true, retryAfterMs }, { 'Retry-After': Math.ceil(retryAfterMs / 1000) })
|
|
595
|
+
return
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
if (!_validateHookAuth(req, res)) {
|
|
599
|
+
log.warn('Rejected unauthenticated POST /permission-floor')
|
|
600
|
+
return
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// Capped, byte-accurate body read — same shape as the other three capped
|
|
604
|
+
// readers (#5433); the oversize response carries `floor: true`.
|
|
605
|
+
req.setEncoding('utf8')
|
|
606
|
+
let body = ''
|
|
607
|
+
let bodyBytes = 0
|
|
608
|
+
let oversized = false
|
|
609
|
+
let streamFailed = false
|
|
610
|
+
req.on('data', (chunk) => {
|
|
611
|
+
if (oversized || streamFailed) return
|
|
612
|
+
bodyBytes += Buffer.byteLength(chunk, 'utf8')
|
|
613
|
+
if (bodyBytes > MAX_FLOOR_BODY) {
|
|
614
|
+
oversized = true
|
|
615
|
+
sendOversizeResponse(req, res, { floor: true })
|
|
616
|
+
return
|
|
617
|
+
}
|
|
618
|
+
body += chunk
|
|
619
|
+
})
|
|
620
|
+
// #7020 — a client that aborts mid-body emits 'error' on the request stream,
|
|
621
|
+
// and an 'error' with NO listener is an unhandled 'error' event (it rethrows,
|
|
622
|
+
// escaping to uncaughtException). mailbox-route.js and github-webhook.js both
|
|
623
|
+
// attach one; match that. Answers `floor: true` so even a torn-down request
|
|
624
|
+
// fails CLOSED, and flags the read so a late 'end' cannot double-respond.
|
|
625
|
+
//
|
|
626
|
+
// No post-'end' guard is needed here (unlike /permission's, which has one):
|
|
627
|
+
// this route's 'end' handler answers SYNCHRONOUSLY on every branch — 200,
|
|
628
|
+
// the 400 on an unparseable body, or the 500 from its catch — so once it has
|
|
629
|
+
// run `res.headersSent` is already true and a later 'error' takes the
|
|
630
|
+
// `res.end()` no-op arm. There is no deferred-response window to protect.
|
|
631
|
+
req.on('error', (err) => {
|
|
632
|
+
streamFailed = true
|
|
633
|
+
log.warn(`POST /permission-floor request stream error: ${err?.message || err}`)
|
|
634
|
+
try {
|
|
635
|
+
if (!res.headersSent) sendJson(res, 400, { floor: true })
|
|
636
|
+
else res.end()
|
|
637
|
+
} catch { /* socket already torn down */ }
|
|
638
|
+
})
|
|
639
|
+
req.on('end', () => {
|
|
640
|
+
// #5313 (WP-1.3): this fires on a later tick, so a throw here escapes the
|
|
641
|
+
// route wrapper straight to uncaughtException. Contain it — and answer
|
|
642
|
+
// `floor: true` so even a crash-path response fails closed.
|
|
643
|
+
try {
|
|
644
|
+
if (oversized || streamFailed) return
|
|
645
|
+
|
|
646
|
+
let hookData
|
|
647
|
+
try {
|
|
648
|
+
hookData = JSON.parse(body)
|
|
649
|
+
} catch {
|
|
650
|
+
sendJson(res, 400, { floor: true })
|
|
651
|
+
return
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// The cwd basis must match the in-process path's (`PermissionManager`'s
|
|
655
|
+
// `cwd: this.cwd`), so resolve the OWNING session from the presented hook
|
|
656
|
+
// secret — the same lookup handlePermissionRequest uses for the #2831
|
|
657
|
+
// inactivity pause and the #2832 session mapping.
|
|
658
|
+
const authHeader = (req.headers && req.headers['authorization']) || ''
|
|
659
|
+
const hookToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
|
|
660
|
+
const ownerLookup = (hookToken && typeof findSessionByHookSecret === 'function')
|
|
661
|
+
? findSessionByHookSecret(hookToken)
|
|
662
|
+
: null
|
|
663
|
+
const sessionCwd = ownerLookup?.session?.cwd ?? null
|
|
664
|
+
|
|
665
|
+
const { floor, reason } = evaluateHookFloorRequest(hookData, sessionCwd)
|
|
666
|
+
if (floor) {
|
|
667
|
+
// Security-relevant and RARE (a protected/secret target under a lenient
|
|
668
|
+
// mode), so info-level: this is the line that explains a prompt the user
|
|
669
|
+
// did not expect in auto mode. The tool name is safe to log; the path is
|
|
670
|
+
// not logged here (the prompt that follows carries a redacted description).
|
|
671
|
+
log.info(`Permission floor forces a prompt for ${hookData?.tool_name || 'unknown tool'} (${reason})`)
|
|
672
|
+
} else {
|
|
673
|
+
// One per tool call — debug only.
|
|
674
|
+
log.debug(`Permission floor clear for ${hookData.tool_name}`)
|
|
675
|
+
}
|
|
676
|
+
sendJson(res, 200, { floor })
|
|
677
|
+
} catch (err) {
|
|
678
|
+
const message = err?.message || String(err)
|
|
679
|
+
log.error(`POST /permission-floor end handler threw: ${message}${err?.stack ? '\n' + err.stack : ''}`)
|
|
680
|
+
try {
|
|
681
|
+
if (!res.headersSent) {
|
|
682
|
+
sendJson(res, 500, { error: 'Internal server error', floor: true })
|
|
683
|
+
} else {
|
|
684
|
+
res.end()
|
|
685
|
+
}
|
|
686
|
+
} catch { /* socket already torn down */ }
|
|
687
|
+
}
|
|
688
|
+
})
|
|
689
|
+
}
|
|
690
|
+
|
|
325
691
|
/** Handle POST /permission-response from iOS notification actions (HTTP fallback) */
|
|
326
692
|
function handlePermissionResponseHttp(req, res) {
|
|
327
693
|
if (!validateBearerAuth(req, res)) {
|
|
@@ -359,12 +725,15 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
359
725
|
presentedToken &&
|
|
360
726
|
pairingManager.isSessionTokenValid(presentedToken)
|
|
361
727
|
)
|
|
362
|
-
if (tokenIsPairingToken && callerBoundSessionId
|
|
728
|
+
if (tokenIsPairingToken && callerBoundSessionId == null) {
|
|
363
729
|
log.warn('Rejected HTTP /permission-response: an unbound pairing token cannot answer permission requests')
|
|
364
730
|
sendJson(res, 403, { error: 'unbound token cannot answer cross-session permissions' })
|
|
365
731
|
return
|
|
366
732
|
}
|
|
367
733
|
|
|
734
|
+
// Captured now, checked again when the body has arrived (bearer-recheck.js).
|
|
735
|
+
const bearer = captureBearer(req)
|
|
736
|
+
|
|
368
737
|
const MAX_BODY = 4096
|
|
369
738
|
// utf8 decoding + byte-accurate cap, checked BEFORE append — see
|
|
370
739
|
// handlePermissionRequest above; the three capped readers stay in lockstep.
|
|
@@ -397,6 +766,13 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
397
766
|
try {
|
|
398
767
|
if (oversized) return
|
|
399
768
|
|
|
769
|
+
// A bearer is checked again once the body has arrived: nothing below runs
|
|
770
|
+
// for a credential that ended while the body was in flight.
|
|
771
|
+
if (!bearerStillValid(bearer)) {
|
|
772
|
+
sendJson(res, 403, { error: 'unauthorized' })
|
|
773
|
+
return
|
|
774
|
+
}
|
|
775
|
+
|
|
400
776
|
let parsed
|
|
401
777
|
try {
|
|
402
778
|
parsed = JSON.parse(body)
|
|
@@ -422,7 +798,10 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
422
798
|
// entries (clientId=null) in forensic queries. HTTP passes NO dispatch
|
|
423
799
|
// fallback — it has no per-connection activeSessionId, so the dispatch
|
|
424
800
|
// session is the raw mapping only (unchanged from the prior inline code).
|
|
425
|
-
|
|
801
|
+
// #6773: forward an optional free-text deny reason (the WS path's msg.reason
|
|
802
|
+
// analog) so an HTTP caller can also steer a denial. buildDenyMessage bounds
|
|
803
|
+
// + redacts it and ignores it on a non-deny; a missing field is a no-op.
|
|
804
|
+
const result = permissionResolver.resolve(requestId, decision, callerBoundSessionId, { clientId: 'http', reason: parsed.reason, scope: parsed.scope })
|
|
426
805
|
switch (result.kind) {
|
|
427
806
|
case 'binding_mismatch': {
|
|
428
807
|
// For a bound caller the requestId MUST be explicitly mapped to that
|
|
@@ -445,13 +824,23 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
445
824
|
// (PermissionManager → SdkSession → SessionManager → broadcast). The
|
|
446
825
|
// legacy branch has no PermissionManager, so it keeps the inline
|
|
447
826
|
// broadcast (#2905) — sessionId included only when the request was mapped.
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
827
|
+
const effectiveDecision = result.decision ?? decision
|
|
828
|
+
const legacyBroadcast = buildLegacyResolvedBroadcast(result, requestId, effectiveDecision)
|
|
829
|
+
if (legacyBroadcast) broadcastFn(legacyBroadcast.frame, legacyBroadcast.filter)
|
|
830
|
+
// #6771 — an allowAlways over the HTTP fallback (iOS notification
|
|
831
|
+
// action) just persisted a durable project rule on the in-process
|
|
832
|
+
// session. Broadcast the updated rule sets so clients' rules surfaces
|
|
833
|
+
// refresh, mirroring the WS handler (settings-handlers.js).
|
|
834
|
+
if (effectiveDecision === 'allowAlways' && result.via === 'sdk' && result.sessionId) {
|
|
835
|
+
const rulesSession = getSessionManager()?.getSession?.(result.sessionId)?.session
|
|
836
|
+
if (rulesSession && typeof rulesSession.getPersistentPermissionRules === 'function') {
|
|
837
|
+
broadcastFn({
|
|
838
|
+
type: 'permission_rules_updated',
|
|
839
|
+
sessionId: result.sessionId,
|
|
840
|
+
rules: typeof rulesSession.getPermissionRules === 'function' ? rulesSession.getPermissionRules() : [],
|
|
841
|
+
persistentRules: rulesSession.getPersistentPermissionRules(),
|
|
842
|
+
})
|
|
843
|
+
}
|
|
455
844
|
}
|
|
456
845
|
log.info(`Permission ${requestId} resolved via HTTP: ${decision} (${result.via})`)
|
|
457
846
|
sendJson(res, 200, { ok: true })
|
|
@@ -486,15 +875,58 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
486
875
|
}
|
|
487
876
|
|
|
488
877
|
/**
|
|
489
|
-
* Re-send
|
|
878
|
+
* Re-send pending permission requests to a client.
|
|
879
|
+
*
|
|
880
|
+
* Two callers, ONE implementation (#8328 — a second copy of this loop is how
|
|
881
|
+
* the SDK and hook branches drifted apart before):
|
|
882
|
+
* - connect/reconnect (`ws-history.js` post-auth): no filter, every pending
|
|
883
|
+
* permission on every session;
|
|
884
|
+
* - a session replay (`finishReplay`, via `{ sessionId }`): only the
|
|
885
|
+
* permissions the replayed session is blocked on. `permission_request` is
|
|
886
|
+
* in `builtinTransient`, so it is never in history, and a full-rebuild
|
|
887
|
+
* replay swap (`switch_session` forceFull, `subscribe_sessions`) drops the
|
|
888
|
+
* prompt card the client appended live. The re-send is what puts it back.
|
|
889
|
+
*
|
|
890
|
+
* A duplicate delivery is safe by construction: both clients update an
|
|
891
|
+
* existing prompt in place by `requestId` rather than appending a second card.
|
|
892
|
+
*
|
|
893
|
+
* A session-bound client (`client.boundSessionId != null`) is re-sent only its
|
|
894
|
+
* own session's pending permissions, on both the unfiltered and the filtered
|
|
895
|
+
* call; an unbound client is unaffected.
|
|
896
|
+
*
|
|
490
897
|
* @param {WebSocket} ws
|
|
491
898
|
* @param {Object} [client] - Optional client descriptor for diagnostic logging (#2832)
|
|
899
|
+
* @param {Object} [opts]
|
|
900
|
+
* @param {string} [opts.sessionId] - Restrict the re-send to this session. A
|
|
901
|
+
* hook-held (legacy HTTP) permission with NO known owner is never sent by a
|
|
902
|
+
* filtered call: it cannot be shown to be this session's, and sending it
|
|
903
|
+
* would drop another session's prompt into this one's transcript.
|
|
904
|
+
* @param {string} [opts.excludeSessionId] - Skip this session's prompts
|
|
905
|
+
* (#9015). The connect handshake passes the session it is about to replay:
|
|
906
|
+
* that replay's exit re-sends the session's pending permissions itself
|
|
907
|
+
* (`finishReplay`, AFTER `history_replay_end`, where a full-rebuild swap
|
|
908
|
+
* cannot drop it), so a second copy from here would be a duplicate. A
|
|
909
|
+
* hook-held permission with NO known owner is not excluded: no replay will
|
|
910
|
+
* ever claim it, so this call stays the only path that can deliver it.
|
|
492
911
|
*/
|
|
493
|
-
function resendPendingPermissions(ws, client) {
|
|
912
|
+
function resendPendingPermissions(ws, client, { sessionId: onlySessionId, excludeSessionId } = {}) {
|
|
913
|
+
// A session-bound client (share-a-session pairing token, `boundSessionId`)
|
|
914
|
+
// is re-sent only its own session's pending permissions. The bound id is
|
|
915
|
+
// checked with the fail-safe `!= null` test (`isBoundClient`), so an
|
|
916
|
+
// empty-string id counts as bound; a missing client descriptor (unit
|
|
917
|
+
// fixtures that call the handler directly) is treated as unbound, as before.
|
|
918
|
+
// An explicit `sessionId` filter that names a different session than the
|
|
919
|
+
// binding narrows the result to nothing rather than widening it.
|
|
920
|
+
const boundSessionId = client && isBoundClient(client) ? client.boundSessionId : null
|
|
921
|
+
const isBound = boundSessionId != null
|
|
922
|
+
if (isBound && onlySessionId && onlySessionId !== boundSessionId) return
|
|
494
923
|
// SDK-mode: check all sessions for pending permissions
|
|
495
924
|
const sm = getSessionManager()
|
|
496
925
|
if (sm?._sessions instanceof Map) {
|
|
497
926
|
for (const [sessionId, entry] of sm._sessions) {
|
|
927
|
+
if (onlySessionId && sessionId !== onlySessionId) continue
|
|
928
|
+
if (isBound && sessionId !== boundSessionId) continue
|
|
929
|
+
const excluded = excludeSessionId != null && sessionId === excludeSessionId
|
|
498
930
|
if (entry.session?._pendingPermissions instanceof Map) {
|
|
499
931
|
for (const [requestId] of entry.session._pendingPermissions) {
|
|
500
932
|
const permData = entry.session._lastPermissionData?.get(requestId)
|
|
@@ -523,11 +955,27 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
523
955
|
// keeps the settings-handler subscription guard symmetric
|
|
524
956
|
// across the reconnect path. The bare Map.set fallback covers
|
|
525
957
|
// unit-test fixtures that construct the handler directly.
|
|
526
|
-
|
|
958
|
+
//
|
|
959
|
+
// #8328: a FILTERED call (a session replay) must not re-register a
|
|
960
|
+
// route that already exists. `registerPermissionRoute` re-subscribes
|
|
961
|
+
// EVERY eligible client on each call but seeds the #5704 refcount
|
|
962
|
+
// only on the first registration, so a client that deliberately
|
|
963
|
+
// unsubscribed after dispatch would be silently re-subscribed with
|
|
964
|
+
// no refcount, then treated as an explicit subscription and never
|
|
965
|
+
// torn down. The unfiltered connect-time call keeps its behaviour.
|
|
966
|
+
if (onlySessionId && permissionSessionMap.has(requestId)) {
|
|
967
|
+
// route already registered at dispatch/connect — leave it alone
|
|
968
|
+
} else if (typeof registerPermissionRoute === 'function') {
|
|
527
969
|
registerPermissionRoute(requestId, sessionId)
|
|
528
970
|
} else {
|
|
529
971
|
permissionSessionMap.set(requestId, sessionId)
|
|
530
972
|
}
|
|
973
|
+
// #9015: the excluded session's replay owns the FRAME, but the
|
|
974
|
+
// route registration / auto-subscribe above is connect-time
|
|
975
|
+
// bookkeeping the replay-exit resend skips for an already-routed
|
|
976
|
+
// request (#8328). Dropping it left the client unsubscribed, so
|
|
977
|
+
// the app's bootstrap `subscribe_sessions` replayed (and re-sent) again.
|
|
978
|
+
if (excluded) continue
|
|
531
979
|
// #6054: buildPermissionRequestMessage throws on field drift (the
|
|
532
980
|
// intended #6031 fail-loud guard). Isolate it per-permission so one
|
|
533
981
|
// malformed pending entry can't abort the loop and strand the
|
|
@@ -540,6 +988,14 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
540
988
|
input: permData.input,
|
|
541
989
|
remainingMs,
|
|
542
990
|
sessionId,
|
|
991
|
+
// #7968: replay the floor verdict permission-manager.js
|
|
992
|
+
// stashed on this SAME _lastPermissionData entry — never
|
|
993
|
+
// re-derived here (the resend path has no tool input to
|
|
994
|
+
// re-evaluate against; the entry already carries the answer).
|
|
995
|
+
// Fail-closed: a stash with no verdict replays as floored.
|
|
996
|
+
floored: permData.floored !== false,
|
|
997
|
+
explicitConsent: permData.explicitConsent,
|
|
998
|
+
nonDelegable: permData.nonDelegable,
|
|
543
999
|
}))
|
|
544
1000
|
} catch (err) {
|
|
545
1001
|
log.warn(`Skipping malformed pending permission ${requestId} on resend: ${err?.message ?? err}`)
|
|
@@ -554,6 +1010,15 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
554
1010
|
// Legacy HTTP-held permissions
|
|
555
1011
|
for (const [requestId, pending] of pendingPermissions) {
|
|
556
1012
|
if (pending.data) {
|
|
1013
|
+
// #8328: the owning session, recorded at dispatch (`registerPermissionRoute`
|
|
1014
|
+
// keyed by the hook secret's session). Undefined for a request the daemon
|
|
1015
|
+
// could not attribute.
|
|
1016
|
+
const ownerSessionId = permissionSessionMap.get(requestId)
|
|
1017
|
+
if (onlySessionId && ownerSessionId !== onlySessionId) continue
|
|
1018
|
+
// A bound client gets only the entries owned by its bound session; an
|
|
1019
|
+
// ownerless entry cannot be shown to be that session's, so it is skipped.
|
|
1020
|
+
if (isBound && ownerSessionId !== boundSessionId) continue
|
|
1021
|
+
const excluded = excludeSessionId != null && ownerSessionId === excludeSessionId
|
|
557
1022
|
const elapsed = Math.max(0, Date.now() - (pending.data.createdAt ?? Date.now()))
|
|
558
1023
|
const ttl = pending.data.remainingMs ?? PERMISSION_TTL_MS
|
|
559
1024
|
const remainingMs = Math.min(ttl, Math.max(0, ttl - elapsed))
|
|
@@ -561,6 +1026,19 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
561
1026
|
log.debug(`Skipping expired legacy permission ${requestId}`)
|
|
562
1027
|
continue
|
|
563
1028
|
}
|
|
1029
|
+
// #9015: same as the SDK branch — the replay owns the FRAME, but the
|
|
1030
|
+
// connect-time route registration / auto-subscribe stays here. Without
|
|
1031
|
+
// it the client is never subscribed to the session, and the app's
|
|
1032
|
+
// bootstrap `subscribe_sessions` treats it as new and replays (and
|
|
1033
|
+
// re-sends) again.
|
|
1034
|
+
if (excluded) {
|
|
1035
|
+
if (typeof registerPermissionRoute === 'function') {
|
|
1036
|
+
registerPermissionRoute(requestId, ownerSessionId)
|
|
1037
|
+
} else {
|
|
1038
|
+
permissionSessionMap.set(requestId, ownerSessionId)
|
|
1039
|
+
}
|
|
1040
|
+
continue
|
|
1041
|
+
}
|
|
564
1042
|
log.info(`Re-sending pending legacy permission ${requestId} to reconnected client (${Math.round(remainingMs / 1000)}s remaining)`)
|
|
565
1043
|
// Gated at debug level (#2854) — see comment above.
|
|
566
1044
|
if (client) {
|
|
@@ -577,6 +1055,22 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
577
1055
|
description: pending.data.description,
|
|
578
1056
|
input: pending.data.input,
|
|
579
1057
|
remainingMs,
|
|
1058
|
+
// #8328: route the prompt to the session that asked, exactly as the
|
|
1059
|
+
// dispatch-time broadcast does (`sessionId: ownerSessionId || undefined`
|
|
1060
|
+
// above). It was omitted here, so a hook permission for a background
|
|
1061
|
+
// session re-sent on connect landed in whichever session the client
|
|
1062
|
+
// was viewing. The builder leaves the field absent (not null) when
|
|
1063
|
+
// undefined — an unattributable request keeps the active-session
|
|
1064
|
+
// fallback, same as at dispatch.
|
|
1065
|
+
sessionId: ownerSessionId || undefined,
|
|
1066
|
+
// #7968: replay the floor verdict stashed on pending.data at
|
|
1067
|
+
// creation time (handlePermissionRequest above) — never re-derived.
|
|
1068
|
+
// Fail-closed: a stash with no verdict replays as floored.
|
|
1069
|
+
floored: pending.data.floored !== false,
|
|
1070
|
+
explicitConsent: pending.data.explicitConsent,
|
|
1071
|
+
nonDelegable: pending.data.nonDelegable,
|
|
1072
|
+
// #8357: the pairing id stashed at creation, replayed verbatim.
|
|
1073
|
+
toolUseId: typeof pending.data.toolUseId === 'string' ? pending.data.toolUseId : undefined,
|
|
580
1074
|
}))
|
|
581
1075
|
} catch (err) {
|
|
582
1076
|
log.warn(`Skipping malformed pending legacy permission ${requestId} on resend: ${err?.message ?? err}`)
|
|
@@ -586,6 +1080,57 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
586
1080
|
}
|
|
587
1081
|
}
|
|
588
1082
|
|
|
1083
|
+
/**
|
|
1084
|
+
* #7379 — release a pending HTTP-hook permission whose asker is gone.
|
|
1085
|
+
*
|
|
1086
|
+
* Called when a session reports (via `permission_expired`) that the turn a
|
|
1087
|
+
* prompt belonged to has died. The daemon cannot rely on the hook dying to
|
|
1088
|
+
* learn this: since #7606 `killProcessTree` does signal the hook's
|
|
1089
|
+
* `bash permission-hook.sh` -> `curl --max-time ...` grandchildren on a
|
|
1090
|
+
* respawn/destroy, but on a crash nothing runs at all. So the socket can stay
|
|
1091
|
+
* open, `req 'aborted'` / `res 'close'` never fire, and the entry sits there
|
|
1092
|
+
* with time left on its clock until `resendPendingPermissions` hands it to
|
|
1093
|
+
* the next client that connects — a live Allow button for a turn that no
|
|
1094
|
+
* longer exists (#7335 all over again, one reconnect later).
|
|
1095
|
+
*
|
|
1096
|
+
* Resolves as DENY, which is both the fail-closed default and the truth: the
|
|
1097
|
+
* request can no longer be honoured by anyone. The shared `cleanup()` then
|
|
1098
|
+
* deletes the map entry, tears down the permission-induced subscription, and
|
|
1099
|
+
* releases the session's inactivity pause.
|
|
1100
|
+
*
|
|
1101
|
+
* Quiet and idempotent when the entry is already gone — that is the NORMAL
|
|
1102
|
+
* case whenever the hook's socket did close on its own, and this is called on
|
|
1103
|
+
* every `permission_expired`, including the SDK path whose prompts never live
|
|
1104
|
+
* in this map at all. Returns whether it actually released something so
|
|
1105
|
+
* callers can log meaningfully.
|
|
1106
|
+
*/
|
|
1107
|
+
function releaseAbandonedPermission(requestId, sessionId = null) {
|
|
1108
|
+
if (!requestId) return false
|
|
1109
|
+
const pending = pendingPermissions.get(requestId)
|
|
1110
|
+
if (!pending) return false
|
|
1111
|
+
// Ownership guard. Not reachable today — ids are minted per-request here
|
|
1112
|
+
// (`perm-${randomUUID()}`) and registered against their owner via the
|
|
1113
|
+
// hook-secret lookup, and the SDK's `perm-<nonce>-<n>-<ts>` format cannot
|
|
1114
|
+
// collide — but this releases a permission on behalf of a session, and
|
|
1115
|
+
// "the caller passed the right id" is exactly the invariant a future
|
|
1116
|
+
// emitter breaks silently. One line, checked against the route map rather
|
|
1117
|
+
// than assumed.
|
|
1118
|
+
if (sessionId && permissionSessionMap.has(requestId) && permissionSessionMap.get(requestId) !== sessionId) {
|
|
1119
|
+
log.warn(`Refusing to release permission ${requestId}: owned by session ${permissionSessionMap.get(requestId)}, not ${sessionId}`)
|
|
1120
|
+
return false
|
|
1121
|
+
}
|
|
1122
|
+
log.info(`Releasing permission ${requestId}: the turn that raised it is gone (#7379)`)
|
|
1123
|
+
try {
|
|
1124
|
+
pending.resolve('deny')
|
|
1125
|
+
} catch (err) {
|
|
1126
|
+
// cleanup() runs BEFORE the response write inside resolve(), so the entry
|
|
1127
|
+
// IS released even when writing to a torn-down socket throws. Same
|
|
1128
|
+
// rationale as drainSessionPermissions — debug, not warn.
|
|
1129
|
+
log.debug(`Permission ${requestId} released, but the deny response write failed (socket likely gone): ${err?.message || err}`)
|
|
1130
|
+
}
|
|
1131
|
+
return true
|
|
1132
|
+
}
|
|
1133
|
+
|
|
589
1134
|
/** Resolve a pending permission request */
|
|
590
1135
|
function resolvePermission(requestId, decision) {
|
|
591
1136
|
const pending = pendingPermissions.get(requestId)
|
|
@@ -660,15 +1205,21 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
|
|
|
660
1205
|
|
|
661
1206
|
return {
|
|
662
1207
|
handlePermissionRequest,
|
|
1208
|
+
// #7004 — the floor probe the shell hook consults before its auto /
|
|
1209
|
+
// acceptEdits short-circuit (wired at POST /permission-floor).
|
|
1210
|
+
handlePermissionFloorCheck,
|
|
663
1211
|
handlePermissionResponseHttp,
|
|
664
1212
|
resendPendingPermissions,
|
|
665
1213
|
resolvePermission,
|
|
1214
|
+
releaseAbandonedPermission,
|
|
666
1215
|
drainSessionPermissions,
|
|
667
1216
|
destroy,
|
|
668
1217
|
// #3996: expose the HTTP-permission limiter so /diagnostics can include
|
|
669
1218
|
// its eviction stats alongside the three WsServer-owned limiters.
|
|
670
1219
|
// Read-only handle — callers must only invoke getEvictionStats() on it.
|
|
671
1220
|
_httpPermissionLimiter,
|
|
1221
|
+
// #7004 — same, for the /permission-floor limiter.
|
|
1222
|
+
_httpFloorLimiter,
|
|
672
1223
|
}
|
|
673
1224
|
}
|
|
674
1225
|
|