@chroxy/server 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -0,0 +1,207 @@
1
+ /**
2
+ * #7085 — the outbound (server → client) schema registry, DERIVED not declared.
3
+ *
4
+ * The 243-field wire-cap audit found 8 "store-legal / wire-illegal" fields: the
5
+ * server held a value its outbound schema rejects, so a client's `safeParse` of the
6
+ * whole snapshot failed and a panel rendered nothing while N live items existed.
7
+ * Every one of them would have been caught by validating outbound messages. The
8
+ * server does not: `ws-server.js`'s only `safeParse` calls are INBOUND, and
9
+ * `event-normalizer.js` says outright that outgoing messages are not validated.
10
+ *
11
+ * A gate needs to know which schema governs a given message. There is no union to
12
+ * ask — despite the name, `ServerMessageSchema` is the schema for a single
13
+ * `type: 'message'` frame, and no discriminated union over server messages exists.
14
+ *
15
+ * So the registry is built by INTROSPECTION: every `Server*Schema` export whose
16
+ * shape carries a `type: z.literal(...)` registers itself under that literal. This
17
+ * is deliberate rather than a convenience — a hand-maintained 153-entry map is
18
+ * exactly the kind of parallel list this codebase has repeatedly watched drift out
19
+ * of sync with its source of truth (see the BASE_SESSION_OPT_KEYS lint, the
20
+ * protocol handler-coverage lint, and the `clampWire` caps that were retyped in
21
+ * three loaders). A derived map cannot drift, and a frame with no schema is
22
+ * detectable by ABSENCE rather than by someone remembering to add an arm.
23
+ *
24
+ * Schemas WITHOUT a `type` literal are correctly excluded: they are sub-objects
25
+ * (`ServerSessionListEntrySchema`, `ServerPermissionAuditEntrySchema`, …) reached
26
+ * through a parent frame, not frames in their own right.
27
+ *
28
+ * A type may map to MORE THAN ONE schema. `type: 'error'` is claimed by both
29
+ * `ServerErrorEnvelopeSchema` and `ServerSkillTrustGrantInvalidAuthorSchema`, so the
30
+ * registry stores a list per type and a message is valid if ANY arm accepts it.
31
+ * Keying one-schema-per-type would silently validate half the `error` frames against
32
+ * the wrong shape.
33
+ */
34
+
35
+ import * as protocol from '@chroxy/protocol'
36
+
37
+ /** Zod object shape, whichever way this version exposes it. */
38
+ function shapeOf(schema) {
39
+ const shape = schema?.shape ?? schema?._def?.shape
40
+ // A shape can be lazily defined as a getter/thunk.
41
+ return typeof shape === 'function' ? shape() : shape
42
+ }
43
+
44
+ /** The union arms of a schema, or null when it is not a union. */
45
+ function unionArmsOf(schema) {
46
+ const def = schema?._def
47
+ const kind = def?.type ?? def?.typeName
48
+ if (kind !== 'union' && kind !== 'discriminatedUnion' && kind !== 'ZodUnion' && kind !== 'ZodDiscriminatedUnion') return null
49
+ const options = def?.options ?? schema?.options
50
+ return options ? [...options] : null
51
+ }
52
+
53
+ /**
54
+ * Every `type` literal a schema can produce.
55
+ *
56
+ * Returns a Set because a UNION is still one frame schema but reaches the
57
+ * registry through each arm's literal. Missing this is not a cosmetic gap: a
58
+ * union-shaped frame schema has no top-level `.shape`, so a naive
59
+ * `shape.type.value` lookup drops it SILENTLY and the frame then looks
60
+ * schema-less. That is exactly what happened to `evaluate_draft_result`
61
+ * (ServerEvaluateDraftResultSchema) and `permission_input`
62
+ * (ServerPermissionInputSchema) — both real frames, both briefly recorded as
63
+ * uncovered because of it.
64
+ *
65
+ * @param {object} schema
66
+ * @returns {Set<string>}
67
+ */
68
+ export function typeLiteralsOf(schema) {
69
+ const out = new Set()
70
+ const arms = unionArmsOf(schema)
71
+ if (arms) {
72
+ for (const arm of arms) for (const t of typeLiteralsOf(arm)) out.add(t)
73
+ return out
74
+ }
75
+ const type = shapeOf(schema)?.type
76
+ if (!type) return out
77
+ // `values` FIRST, deliberately. On a multi-value literal (`z.literal(['a','b'])`)
78
+ // reading `.value` THROWS — and this runs inside a top-level buildRegistry(), so
79
+ // that would be a module-load crash, not a silent miss. `_def.values` is populated
80
+ // for the single-value case too (`z.literal('a')._def.values === ['a']`), so
81
+ // values-first covers both and `.value` is only a fallback for older shapes.
82
+ const values = type?._def?.values ?? type?.options
83
+ if (values) {
84
+ for (const v of values) if (typeof v === 'string') out.add(v)
85
+ if (out.size > 0) return out
86
+ }
87
+ try {
88
+ if (typeof type.value === 'string') out.add(type.value)
89
+ } catch {
90
+ // A throwing accessor means we could not read it — leave `out` empty so the
91
+ // caller files this under UNREADABLE rather than treating it as a non-frame.
92
+ }
93
+ return out
94
+ }
95
+
96
+ /**
97
+ * True when a schema is a sub-object rather than a frame.
98
+ *
99
+ * A frame is discriminated by a `type` LITERAL. A schema whose `type` is ordinary
100
+ * data — `ServerPermissionAuditEntrySchema.type` is `z.string()`, naming the audited
101
+ * tool — is not a frame, and neither is one with no `type` at all.
102
+ *
103
+ * Classifying on "has a type field" instead of "has a type LITERAL" is too crude and
104
+ * flagged that audit-entry schema as unreadable. The distinction that matters is
105
+ * between a legitimate exclusion and a SILENT DROP, so the rule is: no literal to
106
+ * read is fine; a literal we failed to read is not.
107
+ */
108
+ function looksLikeNonFrame(schema) {
109
+ const arms = unionArmsOf(schema)
110
+ if (arms) return arms.every((arm) => looksLikeNonFrame(arm))
111
+
112
+ // FAIL LOUD BY DEFAULT. Only a plain object can be a legitimate sub-object. Any
113
+ // other combinator — intersection, pipe, transform, catch, default, optional,
114
+ // nullable, readonly, lazy — hides `.shape`, so keying "non-frame" off a missing
115
+ // shape would file every one of them as legitimately excluded and the invariant
116
+ // would defend the union case and nothing else. Reporting them instead means a
117
+ // frame wrapped in a combinator surfaces as UNREADABLE rather than vanishing.
118
+ const kind = schema?._def?.type ?? schema?._def?.typeName
119
+ if (kind !== 'object' && kind !== 'ZodObject') return false
120
+
121
+ const type = shapeOf(schema)?.type
122
+ if (type === undefined) return true
123
+ const typeKind = type?._def?.type ?? type?._def?.typeName
124
+ // Only a literal (or an enum of literals) can discriminate a frame; a `type` that
125
+ // is ordinary data (ServerPermissionAuditEntrySchema.type is z.string(), naming the
126
+ // audited tool) does not make its owner a frame.
127
+ return typeKind !== 'literal' && typeKind !== 'ZodLiteral' && typeKind !== 'enum' && typeKind !== 'ZodEnum'
128
+ }
129
+
130
+ function buildRegistry() {
131
+ /** @type {Map<string, Array<{ name: string, schema: object }>>} */
132
+ const byType = new Map()
133
+ const nonFrame = []
134
+ const unreadable = []
135
+ for (const [name, schema] of Object.entries(protocol)) {
136
+ if (!name.startsWith('Server') || !name.endsWith('Schema')) continue
137
+ const types = typeLiteralsOf(schema)
138
+ if (types.size === 0) {
139
+ // No literal extracted. Either it genuinely has no `type` field (fine), or it
140
+ // has one this code could not read (NOT fine — that is the silent drop).
141
+ if (looksLikeNonFrame(schema)) nonFrame.push(name)
142
+ else unreadable.push(name)
143
+ continue
144
+ }
145
+ for (const type of types) {
146
+ if (!byType.has(type)) byType.set(type, [])
147
+ byType.get(type).push({ name, schema })
148
+ }
149
+ }
150
+ return { byType, nonFrame, unreadable }
151
+ }
152
+
153
+ /** Exposed for the coverage test — the classifier's bias is the invariant's whole value. */
154
+ export const looksLikeNonFrameForTests = looksLikeNonFrame
155
+
156
+ const { byType: REGISTRY, nonFrame: NON_FRAME_SCHEMAS, unreadable: UNREADABLE_SCHEMAS } = buildRegistry()
157
+
158
+ /**
159
+ * Schemas that DO carry a `type` field whose literal could not be extracted.
160
+ *
161
+ * Must always be empty. A non-empty list means the derivation silently dropped a
162
+ * frame and the coverage numbers are understated — so the test asserts on it
163
+ * rather than leaving it to be noticed.
164
+ */
165
+ export const UNREADABLE_FRAME_SCHEMA_NAMES = Object.freeze([...UNREADABLE_SCHEMAS].sort())
166
+
167
+ /** Every outbound message `type` that has at least one schema. */
168
+ export const SCHEMA_BACKED_OUTBOUND_TYPES = Object.freeze([...REGISTRY.keys()].sort())
169
+
170
+ /** `Server*Schema` exports with no `type` literal — sub-objects, not frames. */
171
+ export const NON_FRAME_SCHEMA_NAMES = Object.freeze([...NON_FRAME_SCHEMAS].sort())
172
+
173
+ /**
174
+ * Schemas governing a message `type`, or an empty array when the type is unknown
175
+ * to the protocol package.
176
+ *
177
+ * An empty array is the signal a gate must NOT treat as "valid": it means nothing
178
+ * describes this frame, which is the vacuous-pass failure mode.
179
+ *
180
+ * @param {string} type
181
+ * @returns {Array<{ name: string, schema: object }>}
182
+ */
183
+ export function outboundSchemasForType(type) {
184
+ return REGISTRY.get(type) ?? []
185
+ }
186
+
187
+ /**
188
+ * Validate an outbound message against its registered schema(s).
189
+ *
190
+ * @param {unknown} message
191
+ * @returns {{ ok: true } | { ok: false, reason: 'no-type' | 'no-schema' | 'invalid', type?: string, schema?: string, issue?: object }}
192
+ */
193
+ export function validateOutbound(message) {
194
+ const type = message && typeof message === 'object' ? message.type : undefined
195
+ if (typeof type !== 'string') return { ok: false, reason: 'no-type' }
196
+ const arms = outboundSchemasForType(type)
197
+ if (arms.length === 0) return { ok: false, reason: 'no-schema', type }
198
+ let first = null
199
+ for (const { name, schema } of arms) {
200
+ const result = schema.safeParse(message)
201
+ if (result.success) return { ok: true }
202
+ // Report the FIRST arm's complaint. With multiple arms the others' errors are
203
+ // noise — a message is meant to match exactly one shape.
204
+ if (!first) first = { schema: name, issue: result.error.issues[0] }
205
+ }
206
+ return { ok: false, reason: 'invalid', type, ...first }
207
+ }
@@ -6,6 +6,12 @@ import { settlePush } from './push.js'
6
6
  import { createPermissionResolver } from './permission-resolver.js'
7
7
  import { sendOversizeResponse } from './http-oversize.js'
8
8
  import { redactValue, sanitizeToolInput } 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'
10
16
 
11
17
  const log = createLogger('ws')
@@ -13,6 +19,77 @@ const log = createLogger('ws')
13
19
  // -- Permission TTL --
14
20
  const PERMISSION_TTL_MS = 300_000 // 5 minutes
15
21
 
22
+ // #7004 — body cap for POST /permission-floor. Deliberately MUCH larger than
23
+ // /permission's 64KB, for two reasons:
24
+ // 1. Nothing is retained. /permission's cap bounds a request that is HELD for up
25
+ // to 5 minutes with its payload stashed in `pendingPermissions`; the floor
26
+ // probe parses the body, answers a boolean, and drops it inside one tick.
27
+ // 2. Over-capping here would BREAK legitimate work rather than merely prompt for
28
+ // it. The hook POSTs the whole PreToolUse payload, and a `Write` carries its
29
+ // full `content` — a >64KB file write in auto/acceptEdits would 413, and the
30
+ // hook's fail-closed rule would then route it to a prompt whose own POST is
31
+ // likewise oversize (a deny). 1 MiB keeps every realistic write on the
32
+ // auto-allow path; a payload past it is pathological and still fails CLOSED.
33
+ const MAX_FLOOR_BODY = 1_048_576
34
+
35
+ /**
36
+ * #7004 — the hook path's floor decision for one PreToolUse payload.
37
+ *
38
+ * Pure, and exported for tests: the HTTP handler below is only auth + body
39
+ * plumbing around this. The floor VERDICT itself comes from
40
+ * {@link isFlooredTarget} (permission-floor.js), the same call
41
+ * `permission-manager.js` `handlePermission` makes — so the two pipelines cannot
42
+ * disagree about which tool gets which floor or how targets are extracted.
43
+ *
44
+ * FAILS CLOSED on an ambiguous payload — a floored verdict only ever forces the
45
+ * interactive PROMPT (never a deny), so "prompt when unsure" costs one prompt,
46
+ * whereas guessing `false` would silently auto-approve a target we could not
47
+ * inspect. Ambiguous means: a non-object payload, a missing/blank `tool_name`, a
48
+ * missing or non-object `tool_input` (a path-carrying tool call always has one),
49
+ * or no resolvable cwd to anchor the resolution on. This is deliberately STRICTER
50
+ * than the in-process path, which receives already-typed inputs from the SDK
51
+ * rather than parsing an HTTP body.
52
+ *
53
+ * The cwd basis is the OWNING SESSION's cwd (`session.cwd` — exactly what
54
+ * `PermissionManager` is constructed with, `cwd: this.cwd`) and NOTHING ELSE. It
55
+ * never falls back to the daemon's `process.cwd()`, and (#7020) never to the
56
+ * payload's own `cwd`: both are resolution bases the floor did not choose, and
57
+ * resolving a target against the wrong root UNDER-floors. The payload case is the
58
+ * sharper of the two because it is CALLER-chosen — naming the protected directory
59
+ * itself as the base makes the relative scan see nothing protected (target
60
+ * `/repo/.git/config` with `cwd: "/repo/.git"` scans just `config` → `floor:
61
+ * false`). `session.cwd` is always a real string (`BaseSession` sets
62
+ * `cwd || process.cwd()`), including in legacy single-session mode where
63
+ * `_findSessionByHookSecret` returns `{ session, sessionId: null }`, so the only
64
+ * shape this rejects is one where the owning session genuinely cannot be
65
+ * resolved — e.g. `_validateHookAuth` taking its primary-token fallback with no
66
+ * hook secrets registered. That answers `floor: true` (one prompt), not `false`.
67
+ *
68
+ * @param {*} hookData the parsed PreToolUse payload (untrusted)
69
+ * @param {string|null} sessionCwd the owning session's cwd, when resolvable
70
+ * @returns {{ floor: boolean, reason: string }}
71
+ */
72
+ export function evaluateHookFloorRequest(hookData, sessionCwd) {
73
+ if (!hookData || typeof hookData !== 'object' || Array.isArray(hookData)) {
74
+ return { floor: true, reason: 'payload is not an object' }
75
+ }
76
+ const tool = hookData.tool_name
77
+ if (typeof tool !== 'string' || tool.length === 0) {
78
+ return { floor: true, reason: 'missing tool_name' }
79
+ }
80
+ const input = hookData.tool_input
81
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
82
+ return { floor: true, reason: 'missing or non-object tool_input' }
83
+ }
84
+ // #7020 — the OWNING SESSION's cwd is the only accepted resolution base. Never
85
+ // `hookData.cwd` (caller-chosen → under-floors), never `process.cwd()`.
86
+ const cwd = (typeof sessionCwd === 'string' && sessionCwd.length > 0) ? sessionCwd : null
87
+ if (!cwd) {
88
+ return { floor: true, reason: 'no resolvable session cwd' }
89
+ }
90
+ return { floor: isFlooredTarget(tool, input, cwd), reason: 'floor predicate' }
91
+ }
92
+
16
93
  // -- Broadcast safety --
17
94
  // `sanitizeToolInput` (key-name + recursive value-shape redaction) lives in
18
95
  // redaction.js (#6038) so the SDK/TUI provider path (permission-manager.js)
@@ -90,6 +167,18 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
90
167
  // tag that operators rely on in eviction logs and /diagnostics.
91
168
  const _httpPermissionLimiter = new RateLimiter({ ...(rateLimit || { windowMs: 60_000, maxMessages: 30, burst: 10 }), name: 'http-permission' })
92
169
 
170
+ // #7004 — separate, MUCH larger budget for POST /permission-floor. Unlike
171
+ // /permission (one request per HUMAN decision, so 30/min is generous), the floor
172
+ // probe fires once per TOOL CALL while a lenient mode is active — machine speed.
173
+ // A budget as low as /permission's would rate-limit the probe, and because the
174
+ // hook fails CLOSED on anything but an explicit `floor:false` that would turn a
175
+ // busy auto-mode session into a prompt storm (and then, with /permission itself
176
+ // limited, a deny storm). 600/min + 200 burst sits far above any real session's
177
+ // tool-call rate while still bounding an abusive caller; the work per request is
178
+ // a few lstat/realpath calls, so the ceiling is about bounding, not cost.
179
+ // Overridable via `rateLimit.floor` for tests.
180
+ const _httpFloorLimiter = new RateLimiter({ ...(rateLimit?.floor || { windowMs: 60_000, maxMessages: 600, burst: 200 }), name: 'http-permission-floor' })
181
+
93
182
  // Fall back to validateBearerAuth if validateHookAuth is not provided (backwards compat for tests)
94
183
  const _validateHookAuth = validateHookAuth || validateBearerAuth
95
184
 
@@ -149,8 +238,10 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
149
238
  let body = ''
150
239
  let bodyBytes = 0
151
240
  let oversized = false
241
+ let streamFailed = false
242
+ let ended = false
152
243
  req.on('data', (chunk) => {
153
- if (oversized) return
244
+ if (oversized || streamFailed) return
154
245
  bodyBytes += Buffer.byteLength(chunk, 'utf8')
155
246
  if (bodyBytes > MAX_BODY) {
156
247
  oversized = true
@@ -164,7 +255,34 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
164
255
  }
165
256
  body += chunk
166
257
  })
258
+ // #7020 — same omission the floor route had: an 'error' on a stream with no
259
+ // listener rethrows into uncaughtException. A mid-body abort answers a DENY,
260
+ // so this route's fail-closed contract holds on the torn-down path too.
261
+ //
262
+ // ONLY while the body is still being read. Unlike every other capped reader in
263
+ // this file, THIS route's 'end' handler does not respond — it registers a
264
+ // `pendingPermissions` entry and DEFERS the response for up to five minutes
265
+ // while the prompt sits on the user's phone. So a post-'end' 'error' must be a
266
+ // no-op on both counts: answering a 400 there would (a) send a second response
267
+ // on a socket the pending entry still owns — the later `resolve()` then throws
268
+ // ERR_HTTP_HEADERS_SENT on the #5313 tick that reaches uncaughtException — and
269
+ // (b) DENY, from a transient stream error, a request the user is still looking
270
+ // at, while leaving the pending entry alive. Teardown after 'end' belongs to
271
+ // the existing `req 'aborted'` / `res 'close'` → onClose path, which cleans the
272
+ // map up and leaves `closed` set so nothing responds twice.
273
+ req.on('error', (err) => {
274
+ streamFailed = true
275
+ log.warn(`POST /permission request stream error: ${err?.message || err}`)
276
+ if (ended) return
277
+ try {
278
+ if (!res.headersSent) sendJson(res, 400, { decision: 'deny' })
279
+ else res.end()
280
+ } catch { /* socket already torn down */ }
281
+ })
167
282
  req.on('end', () => {
283
+ // Claim the response BEFORE anything below can defer it (see the 'error'
284
+ // listener above) — this must hold even on the paths that return early.
285
+ ended = true
168
286
  // #5313 (WP-1.3): this callback fires on a later tick, after the HTTP
169
287
  // dispatch that registered it has already returned — so a throw here is
170
288
  // NOT caught by the route handler's wrapper and escapes to
@@ -174,7 +292,8 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
174
292
  // throw is contained and returns a 500 to the client when possible.
175
293
  try {
176
294
  // #5433: the 413 deny was already sent from the 'data' handler.
177
- if (oversized) return
295
+ // #7020: ditto the 400 deny from the 'error' handler.
296
+ if (oversized || streamFailed) return
178
297
 
179
298
  let hookData
180
299
  try {
@@ -251,8 +370,16 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
251
370
  // #5702 (8d): settle the fire-and-forget send so a failed phone
252
371
  // notification is logged (named), not silently dropped while the
253
372
  // dashboard card still appears.
373
+ // #6792: carry the owning sessionId in the push data payload (data-only,
374
+ // doesn't change the visible notification) so the app can route a
375
+ // notification tap straight to the session that asked, instead of the
376
+ // OS just opening the app to its default screen. Mirrors the
377
+ // sessionId already included in the broadcastFn call above (#5667)
378
+ // and in the activity_update/activity_waiting/inactivity_warning
379
+ // pushes (push-notification-handler.js). Omitted (not null) when the
380
+ // request maps to no chroxy session, matching the broadcast's convention.
254
381
  settlePush(
255
- pushManager.send('permission', 'Permission needed', `Claude wants to use: ${tool}`, { requestId, tool }, 'permission'),
382
+ pushManager.send('permission', 'Permission needed', `Claude wants to use: ${tool}`, { requestId, tool, sessionId: ownerSessionId || undefined }, 'permission'),
256
383
  `permission requested: ${tool}`,
257
384
  log,
258
385
  )
@@ -322,6 +449,137 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
322
449
  })
323
450
  }
324
451
 
452
+ /**
453
+ * #7004 — Handle POST /permission-floor from the hook script.
454
+ *
455
+ * WHY THIS EXISTS. `hooks/permission-hook.sh` decides `auto` and `acceptEdits`
456
+ * ITSELF, in shell, and never reaches `permission-manager.js` — so the
457
+ * protected-path / secret-read floor that #6794/#6803 put in front of every
458
+ * lenient-mode short-circuit did not exist for the hook-routed providers
459
+ * (claude-tui — the DEFAULT provider — and cli-session). Under `auto` /
460
+ * `acceptEdits` those sessions read `.env` / `id_rsa` and wrote into `.git`/
461
+ * `.claude` with no prompt.
462
+ *
463
+ * The floor is non-trivial path logic (lexical + symlink component-walk,
464
+ * fail-closed), so reimplementing it in bash would guarantee drift. Instead the
465
+ * hook asks the daemon: this route answers the ONE question the shell cannot,
466
+ * `{ floor: true | false }`, using the shared {@link isFlooredTarget}. The hook
467
+ * treats ONLY an explicit `floor:false` as clearance to short-circuit;
468
+ * everything else (floored, 4xx, 429, 5xx, an unparseable body, an unreachable
469
+ * daemon) routes the call to a real prompt. So every failure mode here degrades
470
+ * to "the user is asked", never to "silently allowed".
471
+ *
472
+ * Deliberately NOT a permission request: it creates no pending entry, mints no
473
+ * requestId, broadcasts nothing and sends no push. It is a read-only predicate
474
+ * over a path the caller already supplied, gated on the same per-session hook
475
+ * secret as `POST /permission` (see docs/security/bearer-token-authority.md §5).
476
+ */
477
+ function handlePermissionFloorCheck(req, res) {
478
+ // Rate limit by source IP — see getRateLimitKey's note on the cloudflared
479
+ // loopback peer in handlePermissionRequest above. A 429 answers `floor:true`
480
+ // so a limited caller still fails CLOSED (prompt), never open.
481
+ const socketIp = req.socket?.remoteAddress || ''
482
+ const clientIp = getRateLimitKey(socketIp, req)
483
+ const { allowed, retryAfterMs } = _httpFloorLimiter.check(clientIp)
484
+ if (!allowed) {
485
+ log.warn(`Rate limited POST /permission-floor from ${clientIp}`)
486
+ sendJson(res, 429, { error: 'rate limited', floor: true, retryAfterMs }, { 'Retry-After': Math.ceil(retryAfterMs / 1000) })
487
+ return
488
+ }
489
+
490
+ if (!_validateHookAuth(req, res)) {
491
+ log.warn('Rejected unauthenticated POST /permission-floor')
492
+ return
493
+ }
494
+
495
+ // Capped, byte-accurate body read — same shape as the other three capped
496
+ // readers (#5433); the oversize response carries `floor: true`.
497
+ req.setEncoding('utf8')
498
+ let body = ''
499
+ let bodyBytes = 0
500
+ let oversized = false
501
+ let streamFailed = false
502
+ req.on('data', (chunk) => {
503
+ if (oversized || streamFailed) return
504
+ bodyBytes += Buffer.byteLength(chunk, 'utf8')
505
+ if (bodyBytes > MAX_FLOOR_BODY) {
506
+ oversized = true
507
+ sendOversizeResponse(req, res, { floor: true })
508
+ return
509
+ }
510
+ body += chunk
511
+ })
512
+ // #7020 — a client that aborts mid-body emits 'error' on the request stream,
513
+ // and an 'error' with NO listener is an unhandled 'error' event (it rethrows,
514
+ // escaping to uncaughtException). mailbox-route.js and github-webhook.js both
515
+ // attach one; match that. Answers `floor: true` so even a torn-down request
516
+ // fails CLOSED, and flags the read so a late 'end' cannot double-respond.
517
+ //
518
+ // No post-'end' guard is needed here (unlike /permission's, which has one):
519
+ // this route's 'end' handler answers SYNCHRONOUSLY on every branch — 200,
520
+ // the 400 on an unparseable body, or the 500 from its catch — so once it has
521
+ // run `res.headersSent` is already true and a later 'error' takes the
522
+ // `res.end()` no-op arm. There is no deferred-response window to protect.
523
+ req.on('error', (err) => {
524
+ streamFailed = true
525
+ log.warn(`POST /permission-floor request stream error: ${err?.message || err}`)
526
+ try {
527
+ if (!res.headersSent) sendJson(res, 400, { floor: true })
528
+ else res.end()
529
+ } catch { /* socket already torn down */ }
530
+ })
531
+ req.on('end', () => {
532
+ // #5313 (WP-1.3): this fires on a later tick, so a throw here escapes the
533
+ // route wrapper straight to uncaughtException. Contain it — and answer
534
+ // `floor: true` so even a crash-path response fails closed.
535
+ try {
536
+ if (oversized || streamFailed) return
537
+
538
+ let hookData
539
+ try {
540
+ hookData = JSON.parse(body)
541
+ } catch {
542
+ sendJson(res, 400, { floor: true })
543
+ return
544
+ }
545
+
546
+ // The cwd basis must match the in-process path's (`PermissionManager`'s
547
+ // `cwd: this.cwd`), so resolve the OWNING session from the presented hook
548
+ // secret — the same lookup handlePermissionRequest uses for the #2831
549
+ // inactivity pause and the #2832 session mapping.
550
+ const authHeader = (req.headers && req.headers['authorization']) || ''
551
+ const hookToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
552
+ const ownerLookup = (hookToken && typeof findSessionByHookSecret === 'function')
553
+ ? findSessionByHookSecret(hookToken)
554
+ : null
555
+ const sessionCwd = ownerLookup?.session?.cwd ?? null
556
+
557
+ const { floor, reason } = evaluateHookFloorRequest(hookData, sessionCwd)
558
+ if (floor) {
559
+ // Security-relevant and RARE (a protected/secret target under a lenient
560
+ // mode), so info-level: this is the line that explains a prompt the user
561
+ // did not expect in auto mode. The tool name is safe to log; the path is
562
+ // not logged here (the prompt that follows carries a redacted description).
563
+ log.info(`Permission floor forces a prompt for ${hookData?.tool_name || 'unknown tool'} (${reason})`)
564
+ } else {
565
+ // One per tool call — debug only.
566
+ log.debug(`Permission floor clear for ${hookData.tool_name}`)
567
+ }
568
+ sendJson(res, 200, { floor })
569
+ } catch (err) {
570
+ const message = err?.message || String(err)
571
+ log.error(`POST /permission-floor end handler threw: ${message}${err?.stack ? '\n' + err.stack : ''}`)
572
+ try {
573
+ if (!res.headersSent) {
574
+ sendJson(res, 500, { error: 'Internal server error', floor: true })
575
+ } else {
576
+ res.end()
577
+ }
578
+ } catch { /* socket already torn down */ }
579
+ }
580
+ })
581
+ }
582
+
325
583
  /** Handle POST /permission-response from iOS notification actions (HTTP fallback) */
326
584
  function handlePermissionResponseHttp(req, res) {
327
585
  if (!validateBearerAuth(req, res)) {
@@ -422,7 +680,10 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
422
680
  // entries (clientId=null) in forensic queries. HTTP passes NO dispatch
423
681
  // fallback — it has no per-connection activeSessionId, so the dispatch
424
682
  // session is the raw mapping only (unchanged from the prior inline code).
425
- const result = permissionResolver.resolve(requestId, decision, callerBoundSessionId, { clientId: 'http' })
683
+ // #6773: forward an optional free-text deny reason (the WS path's msg.reason
684
+ // analog) so an HTTP caller can also steer a denial. buildDenyMessage bounds
685
+ // + redacts it and ignores it on a non-deny; a missing field is a no-op.
686
+ const result = permissionResolver.resolve(requestId, decision, callerBoundSessionId, { clientId: 'http', reason: parsed.reason })
426
687
  switch (result.kind) {
427
688
  case 'binding_mismatch': {
428
689
  // For a bound caller the requestId MUST be explicitly mapped to that
@@ -453,6 +714,21 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
453
714
  ...(result.sessionId ? { sessionId: result.sessionId } : {}),
454
715
  })
455
716
  }
717
+ // #6771 — an allowAlways over the HTTP fallback (iOS notification
718
+ // action) just persisted a durable project rule on the in-process
719
+ // session. Broadcast the updated rule sets so clients' rules surfaces
720
+ // refresh, mirroring the WS handler (settings-handlers.js).
721
+ if (decision === 'allowAlways' && result.via === 'sdk' && result.sessionId) {
722
+ const rulesSession = getSessionManager()?.getSession?.(result.sessionId)?.session
723
+ if (rulesSession && typeof rulesSession.getPersistentPermissionRules === 'function') {
724
+ broadcastFn({
725
+ type: 'permission_rules_updated',
726
+ sessionId: result.sessionId,
727
+ rules: typeof rulesSession.getPermissionRules === 'function' ? rulesSession.getPermissionRules() : [],
728
+ persistentRules: rulesSession.getPersistentPermissionRules(),
729
+ })
730
+ }
731
+ }
456
732
  log.info(`Permission ${requestId} resolved via HTTP: ${decision} (${result.via})`)
457
733
  sendJson(res, 200, { ok: true })
458
734
  return
@@ -660,6 +936,9 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
660
936
 
661
937
  return {
662
938
  handlePermissionRequest,
939
+ // #7004 — the floor probe the shell hook consults before its auto /
940
+ // acceptEdits short-circuit (wired at POST /permission-floor).
941
+ handlePermissionFloorCheck,
663
942
  handlePermissionResponseHttp,
664
943
  resendPendingPermissions,
665
944
  resolvePermission,
@@ -669,6 +948,8 @@ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAut
669
948
  // its eviction stats alongside the three WsServer-owned limiters.
670
949
  // Read-only handle — callers must only invoke getEvictionStats() on it.
671
950
  _httpPermissionLimiter,
951
+ // #7004 — same, for the /permission-floor limiter.
952
+ _httpFloorLimiter,
672
953
  }
673
954
  }
674
955
 
package/src/ws-schemas.js CHANGED
@@ -47,6 +47,7 @@ export {
47
47
  GitStageSchema,
48
48
  GitUnstageSchema,
49
49
  GitCommitSchema,
50
+ GitCreatePrSchema,
50
51
  ResumeBudgetSchema,
51
52
  ListCheckpointsSchema,
52
53
  RestoreCheckpointSchema,