@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
@@ -463,6 +463,10 @@ function handlePermissionResponse(ws, client, msg, ctx) {
463
463
  // mergeEditedInput) — a client can narrow the content but not redirect the
464
464
  // path. Only present when the client reviewed + edited the proposed write.
465
465
  editedInput: msg.editedInput,
466
+ // #6773: the operator's free-text deny reason. Used only on a `deny` — the
467
+ // server bounds + redacts it (permission-manager.js buildDenyMessage) and
468
+ // feeds it back to the agent as the denial message instead of 'User denied'.
469
+ reason: msg.reason,
466
470
  })
467
471
 
468
472
  if (result.kind === 'binding_mismatch') {
@@ -508,7 +512,17 @@ function handlePermissionResponse(ws, client, msg, ctx) {
508
512
  }
509
513
 
510
514
  if (result.kind === 'expired' || result.kind === 'not_found') {
511
- ctx.transport.send(ws, { type: 'permission_expired', requestId, sessionId: originSessionId, message: 'This permission request has expired or was already handled' })
515
+ // #7096: OMIT sessionId when it is not a real id. `originSessionId` resolves to
516
+ // `client.activeSessionId`, which defaults to null (ws-server.js), so the
517
+ // expired/not_found branch could stamp null — and the wire field is
518
+ // `z.string().optional()`, where undefined is legal and null is not. This is the
519
+ // SECOND producer of this frame; the normalizer's mapping is the other.
520
+ ctx.transport.send(ws, {
521
+ type: 'permission_expired',
522
+ requestId,
523
+ ...(typeof originSessionId === 'string' && originSessionId.length > 0 ? { sessionId: originSessionId } : {}),
524
+ message: 'This permission request has expired or was already handled',
525
+ })
512
526
  return
513
527
  }
514
528
 
@@ -518,14 +532,56 @@ function handlePermissionResponse(ws, client, msg, ctx) {
518
532
  // broadcast). Legacy non-SDK sessions (no PermissionManager) keep an inline
519
533
  // broadcast for the unmapped case only — mirrors the prior `!originSessionId`.
520
534
  if (!result.sessionId) {
521
- ctx.transport.broadcast(
522
- { type: 'permission_resolved', requestId, decision },
523
- (c) => c.id !== client.id
524
- )
535
+ // #6590: broadcast to ALL clients INCLUDING the resolver (no `c.id !==
536
+ // client.id` exclusion). The resolving client needs its own
537
+ // `permission_resolved` to prune `permissionInputs[requestId]` (#6559) —
538
+ // append-only otherwise, so on this legacy path the entry used to linger
539
+ // until disconnect. Echoing to the resolver is SAFE to re-apply: the
540
+ // `permissionInputs` prune is a guarded copy-delete, the notification
541
+ // read-stamp only touches not-yet-acked rows, and re-marking the
542
+ // already-answered prompt is functionally inert (its label reads from
543
+ // `resolvedPermissions`, and the pending-count only checks that `answered`
544
+ // is truthy — only `answeredAt` is refreshed to the server-confirmed time).
545
+ // This also matches the SDK path, which broadcasts session events to every
546
+ // subscriber without excluding the origin client.
547
+ ctx.transport.broadcast({ type: 'permission_resolved', requestId, decision })
548
+ }
549
+
550
+ // #6771 — an `allowAlways` that resolved on an in-process session just
551
+ // persisted a durable project rule (permission-manager.js). Broadcast the
552
+ // updated rule sets so every client's rules surface (mobile SessionRules,
553
+ // etc.) reflects the new standing grant without a reconnect. The manager
554
+ // updated its in-memory persistent set synchronously during respondToPermission,
555
+ // so getPersistentPermissionRules() already includes it.
556
+ if (decision === 'allowAlways' && result.sessionId) {
557
+ const rulesEntry = ctx.sessions.sessionManager?.getSession?.(result.sessionId)
558
+ const rulesSession = rulesEntry?.session
559
+ if (rulesSession && typeof rulesSession.getPersistentPermissionRules === 'function') {
560
+ ctx.transport.broadcastToSession(result.sessionId, {
561
+ type: 'permission_rules_updated',
562
+ sessionId: result.sessionId,
563
+ rules: typeof rulesSession.getPermissionRules === 'function' ? rulesSession.getPermissionRules() : [],
564
+ persistentRules: rulesSession.getPersistentPermissionRules(),
565
+ })
566
+ }
525
567
  }
526
568
  }
527
569
 
528
570
  function handleQueryPermissionAudit(ws, client, msg, ctx) {
571
+ // #6837 — same authority principle as the adjacent handleGetPermissionInput: a
572
+ // pairing-bound (share-a-session) token is scoped to ITS OWN session. Without
573
+ // this gate a bound client could read another session's decision history, or
574
+ // omit sessionId entirely and pull the GLOBAL cross-session audit log. Bound
575
+ // clients must name their own boundSessionId explicitly; the global query is
576
+ // host-authority (unbound / primary token) only.
577
+ if (client.boundSessionId && msg.sessionId !== client.boundSessionId) {
578
+ loggerForSession('ws', client.boundSessionId).warn(`Client ${client.id} (bound to ${client.boundSessionId}) attempted to query permission audit for ${msg.sessionId || 'ALL sessions'} — rejected`)
579
+ sendError(ws, msg?.requestId, 'PERMISSION_AUDIT_FORBIDDEN_BOUND_CLIENT',
580
+ "Pairing-issued session tokens can only query their own session's permission audit.",
581
+ undefined, ctx)
582
+ return
583
+ }
584
+
529
585
  if (ctx.permissions.permissionAudit) {
530
586
  const entries = ctx.permissions.permissionAudit.query({
531
587
  sessionId: msg.sessionId,
@@ -702,17 +758,102 @@ function handleSetPermissionRules(ws, client, msg, ctx) {
702
758
  sendSessionError(ws, ctx, `rules[${i}]: tool '${rule.tool}' is not eligible for permission rules`)
703
759
  return
704
760
  }
761
+ // #6803 — optional path/glob scope: a non-empty string when present.
762
+ if (rule.path !== undefined && (typeof rule.path !== 'string' || !rule.path.trim())) {
763
+ sendSessionError(ws, ctx, `rules[${i}]: path scope must be a non-empty string`)
764
+ return
765
+ }
766
+ }
767
+
768
+ // #6771 — optional durable (project-scoped) rule set. When present, it FULLY
769
+ // REPLACES the persisted rules for this session's project cwd — the client
770
+ // "manage / remove persistent rule" path (send the reduced list to drop one).
771
+ // Validated with the same eligibility floor as session rules.
772
+ const projectRules = msg.projectRules
773
+ if (projectRules !== undefined) {
774
+ if (!Array.isArray(projectRules)) {
775
+ sendSessionError(ws, ctx, 'projectRules must be an array')
776
+ return
777
+ }
778
+ for (let i = 0; i < projectRules.length; i++) {
779
+ const rule = projectRules[i]
780
+ if (!rule || typeof rule !== 'object') {
781
+ sendSessionError(ws, ctx, `projectRules[${i}]: not an object`)
782
+ return
783
+ }
784
+ if (typeof rule.tool !== 'string' || !rule.tool.trim()) {
785
+ sendSessionError(ws, ctx, `projectRules[${i}]: missing tool name`)
786
+ return
787
+ }
788
+ if (rule.decision !== 'allow' && rule.decision !== 'deny') {
789
+ sendSessionError(ws, ctx, `projectRules[${i}]: decision must be 'allow' or 'deny'`)
790
+ return
791
+ }
792
+ if (rule.decision === 'allow' && NEVER_AUTO_ALLOW.has(rule.tool)) {
793
+ sendSessionError(ws, ctx, `projectRules[${i}]: tool '${rule.tool}' cannot be auto-allowed`)
794
+ return
795
+ }
796
+ if (rule.decision === 'allow' && !ELIGIBLE_TOOLS.has(rule.tool)) {
797
+ sendSessionError(ws, ctx, `projectRules[${i}]: tool '${rule.tool}' is not eligible for permission rules`)
798
+ return
799
+ }
800
+ // #6803 — optional path/glob scope: a non-empty string when present.
801
+ if (rule.path !== undefined && (typeof rule.path !== 'string' || !rule.path.trim())) {
802
+ sendSessionError(ws, ctx, `projectRules[${i}]: path scope must be a non-empty string`)
803
+ return
804
+ }
805
+ }
705
806
  }
706
807
 
707
808
  const sessionId = msg.sessionId || client.activeSessionId
708
809
  const entry = resolveSessionOrError(ws, ctx, msg, client)
709
810
  if (!entry) return
710
811
 
711
- if (!requireSessionMethod(ws, ctx, entry, 'setPermissionRules', 'This provider does not support permission rules')) {
712
- return
812
+ // #6829 — the two halves have DIFFERENT capability gates. Session rules need
813
+ // the session-rule setter (`setPermissionRules` — absent on codex by design,
814
+ // so it keeps advertising sessionRules:false). Durable project rules need only
815
+ // the persistent re-seed setter (`setPersistentPermissionRules` — which codex
816
+ // HAS since #6829). Gating the whole handler on `setPermissionRules` made the
817
+ // projectRules remove/clear path dead on codex: durable rules could be CREATED
818
+ // (allowAlways resolves inside the PermissionManager, no handler involved) but
819
+ // never removed from any client.
820
+ const supportsSessionRules = typeof entry.session?.setPermissionRules === 'function'
821
+
822
+ if (projectRules === undefined) {
823
+ // Session-rules-only request — unchanged legacy gate: providers without the
824
+ // session-rule setter (codex, cli, tui, gemini) are rejected.
825
+ if (!requireSessionMethod(ws, ctx, entry, 'setPermissionRules', 'This provider does not support permission rules')) {
826
+ return
827
+ }
828
+ } else {
829
+ // projectRules present — the durable half needs the persistent setter (all
830
+ // in-process-permission providers: sdk / byok / codex). Providers with no
831
+ // PermissionManager at all stay rejected, as before.
832
+ if (!requireSessionMethod(ws, ctx, entry, 'setPersistentPermissionRules', 'This provider does not support persistent permission rules')) {
833
+ return
834
+ }
835
+ // A NON-EMPTY session-rule set aimed at a provider without the session-rule
836
+ // setter must fail loudly, not be silently dropped. The rules:[] echo the
837
+ // clients send alongside a project-rule removal is a no-op and passes.
838
+ if (!supportsSessionRules && rules.length > 0) {
839
+ sendSessionError(ws, ctx, 'This provider does not support session permission rules')
840
+ return
841
+ }
713
842
  }
714
843
 
715
- entry.session.setPermissionRules(rules)
844
+ if (supportsSessionRules) {
845
+ entry.session.setPermissionRules(rules)
846
+ }
847
+
848
+ // #6771 — apply the durable project-rule replacement (if any) to the store,
849
+ // then re-seed THIS session's in-memory persistent set so it takes effect
850
+ // immediately. The store is keyed by the session's cwd. (The persistent-setter
851
+ // gate above already guaranteed the method exists on this path.)
852
+ const ruleStore = ctx.sessions.sessionManager?.permissionRuleStore
853
+ if (projectRules !== undefined && ruleStore && typeof ruleStore.setRules === 'function') {
854
+ const stored = ruleStore.setRules(entry.session.cwd, projectRules)
855
+ entry.session.setPersistentPermissionRules(stored)
856
+ }
716
857
 
717
858
  // Audit the whitelist change
718
859
  if (ctx.permissions.permissionAudit) {
@@ -723,11 +864,156 @@ function handleSetPermissionRules(ws, client, msg, ctx) {
723
864
  })
724
865
  }
725
866
 
726
- // Broadcast updated rules to all session clients
867
+ // Broadcast updated rules to all session clients. #6771 — include the durable
868
+ // persistentRules so the rules surfaces show session AND project grants.
727
869
  const currentRules = entry.session.getPermissionRules ? entry.session.getPermissionRules() : rules
728
- ctx.transport.broadcastToSession(sessionId, { type: 'permission_rules_updated', rules: currentRules, sessionId })
870
+ const persistentRules = typeof entry.session.getPersistentPermissionRules === 'function'
871
+ ? entry.session.getPersistentPermissionRules()
872
+ : []
873
+ ctx.transport.broadcastToSession(sessionId, { type: 'permission_rules_updated', rules: currentRules, persistentRules, sessionId })
729
874
  // #4828: session-scoped.
730
- loggerForSession('ws', sessionId).info(`Permission rules updated by ${client.id} on session ${sessionId}: ${rules.length} rule(s)`)
875
+ loggerForSession('ws', sessionId).info(`Permission rules updated by ${client.id} on session ${sessionId}: ${rules.length} session rule(s)${projectRules !== undefined ? `, ${projectRules.length} project rule(s)` : ''}`)
876
+ }
877
+
878
+ /**
879
+ * #6824 — enable/disable an already-configured MCP server for the active
880
+ * session (runtime toggle, not add/remove). Only the BYOK lane runs an
881
+ * in-daemon MCP fleet that can be parked/unparked, so this rejects other
882
+ * providers with a capability error the client uses to keep its toggle hidden.
883
+ *
884
+ * AUTH: routed through `resolveSession`, which enforces session-token
885
+ * binding — a pairing-bound client may only act on ITS OWN session; a bound
886
+ * token naming a different session resolves to no entry and is rejected. This
887
+ * is the own-session gate, not the host-authority (unbound-only) gate that
888
+ * `set_permission_rules` uses: enabling a server can never ADD an untrusted
889
+ * one (the fleet re-runs the trust gate on unpark) and disabling only REDUCES
890
+ * capability, so neither direction is the privilege escalation that rule-
891
+ * setting is. Every rejection — validation, session resolution, capability,
892
+ * unknown server — echoes `requestId` (when supplied) with a stable code
893
+ * (MCP_SERVER_NOT_APPLIED / MCP_SERVER_TOGGLE_UNSUPPORTED /
894
+ * MCP_SERVER_NOT_FOUND), the same echo discipline as the set_model /
895
+ * set_permission_mode / set_thinking_level NOT_APPLIED family.
896
+ *
897
+ * On success the session re-emits `mcp_servers` (broadcast to every subscriber
898
+ * → multi-device consistency), so this handler does not send its own ack — the
899
+ * updated list IS the confirmation.
900
+ */
901
+ async function handleSetMcpServerEnabled(ws, client, msg, ctx) {
902
+ const requestId = msg?.requestId
903
+ const server = typeof msg?.server === 'string' ? msg.server.trim() : ''
904
+ if (!server) {
905
+ sendError(ws, requestId, 'MCP_SERVER_NOT_APPLIED', 'set_mcp_server_enabled requires a non-empty `server` name', undefined, ctx)
906
+ return
907
+ }
908
+ if (typeof msg?.enabled !== 'boolean') {
909
+ sendError(ws, requestId, 'MCP_SERVER_NOT_APPLIED', 'set_mcp_server_enabled requires a boolean `enabled`', undefined, ctx)
910
+ return
911
+ }
912
+
913
+ const sessionId = msg?.sessionId || client?.activeSessionId
914
+ // Session resolution failures (no active session, or a bound token naming a
915
+ // DIFFERENT session — resolveSession enforces the binding) echo requestId +
916
+ // the stable NOT_APPLIED code, mirroring handleSetThinkingLevel, rather than
917
+ // resolveSessionOrError's code-less session_error, so the doc-block contract
918
+ // ("every rejection echoes requestId with a stable code") holds on ALL paths.
919
+ const entry = resolveSession(ctx, msg, client)
920
+ if (!entry) {
921
+ sendError(ws, requestId, 'MCP_SERVER_NOT_APPLIED', 'No active session', undefined, ctx)
922
+ return
923
+ }
924
+
925
+ // Capability gate — only providers that expose `setMcpServerEnabled` (the
926
+ // BYOK lane) can toggle. Others ride the claude binary's own MCP config.
927
+ if (!entry.session || typeof entry.session.setMcpServerEnabled !== 'function') {
928
+ sendError(ws, requestId, 'MCP_SERVER_TOGGLE_UNSUPPORTED',
929
+ 'This provider does not support enabling/disabling MCP servers (its MCP config is managed by the underlying CLI).',
930
+ undefined, ctx)
931
+ return
932
+ }
933
+
934
+ try {
935
+ const result = await entry.session.setMcpServerEnabled(server, msg.enabled)
936
+ if (!result || result.found === false) {
937
+ sendError(ws, requestId, 'MCP_SERVER_NOT_FOUND', `No configured MCP server named '${server}' for this session.`, undefined, ctx)
938
+ return
939
+ }
940
+ // The session re-emits `mcp_servers` on a real change (forwarded to all
941
+ // subscribers). Persist immediately so a crash inside the debounce window
942
+ // can't lose the parked-set change — same discipline as the permission-rule
943
+ // and per-session-setting handlers.
944
+ if (result.changed) {
945
+ try {
946
+ ctx.sessions.sessionManager?.serializeState?.()
947
+ } catch (err) {
948
+ loggerForSession('ws', sessionId).warn(`Failed to persist disabledMcpServers for ${sessionId}: ${err?.message || err}`)
949
+ }
950
+ }
951
+ loggerForSession('ws', sessionId).info(`MCP server '${server}' ${msg.enabled ? 'enabled' : 'disabled'} by ${client.id} on session ${sessionId} (changed=${result.changed})`)
952
+ } catch (err) {
953
+ sendError(ws, requestId, 'MCP_SERVER_NOT_APPLIED', `Failed to ${msg.enabled ? 'enable' : 'disable'} MCP server '${server}': ${err?.message || String(err)}`, undefined, ctx)
954
+ }
955
+ }
956
+
957
+ /**
958
+ * #6822 — submit a pasted OAuth authorization code for a remote MCP server that
959
+ * reported `oauth-required`. The daemon redeems the code (holding the PKCE
960
+ * verifier + state server-side), persists the tokens encrypted at rest, and
961
+ * reconnects the server authenticated. Only the BYOK lane runs an in-daemon MCP
962
+ * fleet, so this rejects other providers with a capability error.
963
+ *
964
+ * AUTH: identical own-session gate as `set_mcp_server_enabled` (routed through
965
+ * `resolveSession`, which enforces session-token binding). Redeeming a code can
966
+ * only authorize the server the user is already trying to connect — it never
967
+ * escalates. Every rejection echoes `requestId` (when supplied) with a stable
968
+ * code (MCP_AUTH_NOT_APPLIED / MCP_AUTH_UNSUPPORTED / MCP_AUTH_NOT_FOUND /
969
+ * MCP_AUTH_FAILED). On success the session re-emits `mcp_servers` (the new
970
+ * status IS the confirmation) — no separate ack. The `code` and any token are
971
+ * NEVER logged.
972
+ */
973
+ async function handleSubmitMcpAuthCode(ws, client, msg, ctx) {
974
+ const requestId = msg?.requestId
975
+ const server = typeof msg?.server === 'string' ? msg.server.trim() : ''
976
+ const code = typeof msg?.code === 'string' ? msg.code.trim() : ''
977
+ if (!server) {
978
+ sendError(ws, requestId, 'MCP_AUTH_NOT_APPLIED', 'submit_mcp_auth_code requires a non-empty `server` name', undefined, ctx)
979
+ return
980
+ }
981
+ if (!code) {
982
+ sendError(ws, requestId, 'MCP_AUTH_NOT_APPLIED', 'submit_mcp_auth_code requires a non-empty `code`', undefined, ctx)
983
+ return
984
+ }
985
+
986
+ const sessionId = msg?.sessionId || client?.activeSessionId
987
+ const entry = resolveSession(ctx, msg, client)
988
+ if (!entry) {
989
+ sendError(ws, requestId, 'MCP_AUTH_NOT_APPLIED', 'No active session', undefined, ctx)
990
+ return
991
+ }
992
+
993
+ if (!entry.session || typeof entry.session.submitMcpAuthCode !== 'function') {
994
+ sendError(ws, requestId, 'MCP_AUTH_UNSUPPORTED',
995
+ 'This provider does not support MCP OAuth authorization (its MCP config is managed by the underlying CLI).',
996
+ undefined, ctx)
997
+ return
998
+ }
999
+
1000
+ try {
1001
+ const result = await entry.session.submitMcpAuthCode(server, code)
1002
+ if (!result || result.found === false) {
1003
+ sendError(ws, requestId, 'MCP_AUTH_NOT_FOUND', `No configured MCP server named '${server}' awaiting authorization for this session.`, undefined, ctx)
1004
+ return
1005
+ }
1006
+ if (result.ok === false) {
1007
+ // Value-free reason — redemption failed (wrong/expired code, AS error).
1008
+ sendError(ws, requestId, 'MCP_AUTH_FAILED', result.error || `Authorization for MCP server '${server}' failed.`, undefined, ctx)
1009
+ return
1010
+ }
1011
+ // Success: the session re-emitted `mcp_servers` (status now connected or,
1012
+ // if the server still rejects, oauth-required again). Never log the code.
1013
+ loggerForSession('ws', sessionId).info(`MCP server '${server}' authorization completed by ${client.id} on session ${sessionId} (status=${result.status || 'unknown'})`)
1014
+ } catch (err) {
1015
+ sendError(ws, requestId, 'MCP_AUTH_FAILED', `Authorization for MCP server '${server}' failed: ${err?.message || String(err)}`, undefined, ctx)
1016
+ }
731
1017
  }
732
1018
 
733
1019
  // #4664: assemble the per-session-setting WS handlers from the registry.
@@ -793,6 +1079,210 @@ function handleGetPermissionInput(ws, client, msg, ctx) {
793
1079
  return send({ found: true, tool, input: pending._redactedPull })
794
1080
  }
795
1081
 
1082
+ /**
1083
+ * #6974 — MCP config-MUTATION gate: require the STRICT PRIMARY token class
1084
+ * (`client.isPrimaryToken === true`) before any validation or write.
1085
+ *
1086
+ * Why strict-primary rather than the "any unbound client" host-authority bar the
1087
+ * credential-write (#5155) / permission-rule / file-git (#6541) gates use: those
1088
+ * gates reject only `client.boundSessionId`, which leaves the unbound
1089
+ * linking-mode pairing token — an ordinary paired phone — with full authority. A
1090
+ * configured MCP server is a command this daemon SPAWNS, so an add is arbitrary
1091
+ * host code execution, which is the same escalation class as creating a
1092
+ * `user-shell` session, `terminal_input`, `revoke_token` and
1093
+ * `orchestration_run_start` — every one of which checks strict
1094
+ * `client.isPrimaryToken === true` (docs/security/bearer-token-authority.md,
1095
+ * "The WS primary-token gate"). #6974's first cut rejected only bound tokens
1096
+ * while its own error message told the user to "use the primary API token from a
1097
+ * device with physical access": the message was right and the gate was one tier
1098
+ * too weak (#7001 review).
1099
+ *
1100
+ * REMOVE carries the same gate. It only reduces capability, but it still mutates
1101
+ * a host-owned file, and a non-primary client able to delete servers could
1102
+ * silently strip a session's tooling out from under its owner.
1103
+ *
1104
+ * There is no shared cross-surface helper to import: each surface defines its own
1105
+ * local reject helper so the error CODE names the surface that refused
1106
+ * (`rejectMutationIfBound` in file-handlers.js, `rejectCredentialWriteIfBound` in
1107
+ * credential-handlers.js, `guardAction` in orchestration-handlers.js). This
1108
+ * follows that convention exactly — strict `!== true` comparison, an `op`
1109
+ * parameter for the log line, and a surface-specific code.
1110
+ *
1111
+ * Logging uses `sessionLogger` (not `loggerForSession`) because a non-primary
1112
+ * client is frequently UNBOUND — `loggerForSession` throws on an absent sessionId,
1113
+ * which would turn a rejection into a 500-shaped throw.
1114
+ *
1115
+ * @returns {boolean} true if the caller was rejected (handler must return).
1116
+ */
1117
+ function rejectMcpConfigWriteUnlessPrimary(ws, client, msg, ctx, op) {
1118
+ if (client?.isPrimaryToken === true) return false
1119
+ // A non-primary client attempting a host-level config write is a potential
1120
+ // privilege-escalation signal — log it (with the client id + binding) so it
1121
+ // surfaces in triage, the same discipline as token-handlers.js.
1122
+ sessionLogger(client?.boundSessionId).warn(
1123
+ `Client ${client?.id}${client?.boundSessionId ? ` (bound to ${client.boundSessionId})` : ' (unbound, non-primary)'} attempted ${op} — rejected (MCP config writes require the primary token)`,
1124
+ )
1125
+ sendError(
1126
+ ws,
1127
+ msg?.requestId,
1128
+ 'MCP_CONFIG_FORBIDDEN_NON_PRIMARY_CLIENT',
1129
+ 'Pairing-issued tokens cannot add or remove MCP servers — a configured MCP server is a command this machine will run. Use the primary API token from a device with physical access to this machine.',
1130
+ undefined,
1131
+ ctx,
1132
+ )
1133
+ return true
1134
+ }
1135
+
1136
+ /**
1137
+ * #6974 — add a brand-new MCP server, persisting it to the user's MCP config.
1138
+ *
1139
+ * AUTH: two gates, in this order. (1) strict-primary — anything that is not the
1140
+ * primary token class is refused up front by
1141
+ * `rejectMcpConfigWriteUnlessPrimary`, BEFORE any validation, session resolve,
1142
+ * config read or payload logging, so a non-primary client's payload never
1143
+ * reaches the config file. (2) own-session — `resolveSession` still enforces
1144
+ * session-token binding for the primary client's target session.
1145
+ *
1146
+ * Only the BYOK lane runs an in-daemon MCP fleet it can mutate, so other
1147
+ * providers reject with `MCP_CONFIG_UNSUPPORTED` (their MCP config is managed by
1148
+ * the underlying CLI). Every rejection echoes `requestId` with a stable code
1149
+ * (MCP_CONFIG_FORBIDDEN_NON_PRIMARY_CLIENT / MCP_SERVER_ADD_NOT_APPLIED /
1150
+ * MCP_CONFIG_UNSUPPORTED / MCP_SERVER_EXISTS / MCP_SERVER_ADD_TRUST_DENIED), the
1151
+ * same echo discipline as the #6824 toggle family.
1152
+ *
1153
+ * The user's spawn-trust decision is taken BEFORE the config is written (#7001),
1154
+ * so a denied add leaves no entry behind; the denial surfaces as
1155
+ * `MCP_SERVER_ADD_TRUST_DENIED` rather than a generic failure.
1156
+ *
1157
+ * On success the session re-emits `mcp_servers` to every subscriber — that
1158
+ * broadcast IS the ack, so this handler sends nothing on the happy path.
1159
+ */
1160
+ async function handleAddMcpServer(ws, client, msg, ctx) {
1161
+ if (rejectMcpConfigWriteUnlessPrimary(ws, client, msg, ctx, 'add_mcp_server')) return
1162
+ const requestId = msg?.requestId
1163
+ const name = typeof msg?.name === 'string' ? msg.name.trim() : ''
1164
+ if (!name) {
1165
+ sendError(ws, requestId, 'MCP_SERVER_ADD_NOT_APPLIED', 'add_mcp_server requires a non-empty `name`', undefined, ctx)
1166
+ return
1167
+ }
1168
+ if (!msg?.config || typeof msg.config !== 'object' || Array.isArray(msg.config)) {
1169
+ sendError(ws, requestId, 'MCP_SERVER_ADD_NOT_APPLIED', 'add_mcp_server requires a `config` object', undefined, ctx)
1170
+ return
1171
+ }
1172
+ const scope = msg?.scope === 'project' ? 'project' : 'user'
1173
+
1174
+ const sessionId = msg?.sessionId || client?.activeSessionId
1175
+ const entry = resolveSession(ctx, msg, client)
1176
+ if (!entry) {
1177
+ sendError(ws, requestId, 'MCP_SERVER_ADD_NOT_APPLIED', 'No active session', undefined, ctx)
1178
+ return
1179
+ }
1180
+ if (!entry.session || typeof entry.session.addMcpServer !== 'function') {
1181
+ sendError(ws, requestId, 'MCP_CONFIG_UNSUPPORTED',
1182
+ 'This provider does not support adding MCP servers (its MCP config is managed by the underlying CLI).',
1183
+ undefined, ctx)
1184
+ return
1185
+ }
1186
+
1187
+ try {
1188
+ const result = await entry.session.addMcpServer(name, msg.config, scope)
1189
+ if (!result || result.ok !== true) {
1190
+ // #7001: a denied spawn-trust prompt is a distinct outcome from a failure —
1191
+ // nothing was written, and the client should say "you declined" rather than
1192
+ // "the add failed".
1193
+ const code = result?.code === 'EXISTS'
1194
+ ? 'MCP_SERVER_EXISTS'
1195
+ : result?.code === 'TRUST_DENIED'
1196
+ ? 'MCP_SERVER_ADD_TRUST_DENIED'
1197
+ : 'MCP_SERVER_ADD_NOT_APPLIED'
1198
+ sendError(ws, requestId, code, result?.error || `Failed to add MCP server '${name}'.`, undefined, ctx)
1199
+ return
1200
+ }
1201
+ // Log the NAME and scope only — never the command, args, env, url or headers
1202
+ // (they routinely carry tokens and local paths).
1203
+ //
1204
+ // sessionLogger, not loggerForSession: `sessionId` is undefined whenever the
1205
+ // request carried no sessionId and the client has no activeSessionId (the
1206
+ // single-session cliSession adapter still resolves an entry for a null sid),
1207
+ // and loggerForSession THROWS on an absent sessionId — inside this try/catch
1208
+ // that turned a SUCCESSFUL mutation into an MCP_SERVER_ADD_NOT_APPLIED
1209
+ // rejection (#7001 review).
1210
+ sessionLogger(sessionId).info(
1211
+ `MCP server '${name}' added in ${scope} scope by ${client.id} on session ${sessionId} (status=${result.status})`,
1212
+ )
1213
+ // #7002: a group/world-readable MCP config that just received env/headers.
1214
+ // Operator-visible warning only — the message names the file and its mode and
1215
+ // never echoes a secret value, and the add itself succeeded, so this must not
1216
+ // turn into an error frame.
1217
+ if (result.warning) sessionLogger(sessionId).warn(`MCP config permissions: ${result.warning}`)
1218
+ } catch (err) {
1219
+ sendError(ws, requestId, 'MCP_SERVER_ADD_NOT_APPLIED',
1220
+ `Failed to add MCP server '${name}': ${err?.message || String(err)}`, undefined, ctx)
1221
+ }
1222
+ }
1223
+
1224
+ /**
1225
+ * #6974 — permanently remove a configured MCP server from the user's MCP config.
1226
+ *
1227
+ * Same two-gate AUTH as `handleAddMcpServer` (strict-primary first, then
1228
+ * own-session), same capability gate, same requestId echo discipline. A name
1229
+ * absent from the REQUESTED scope yields `MCP_SERVER_NOT_FOUND` and no write —
1230
+ * a remove never silently jumps scope to find something to delete.
1231
+ */
1232
+ async function handleRemoveMcpServer(ws, client, msg, ctx) {
1233
+ if (rejectMcpConfigWriteUnlessPrimary(ws, client, msg, ctx, 'remove_mcp_server')) return
1234
+ const requestId = msg?.requestId
1235
+ const name = typeof msg?.name === 'string' ? msg.name.trim() : ''
1236
+ if (!name) {
1237
+ sendError(ws, requestId, 'MCP_SERVER_REMOVE_NOT_APPLIED', 'remove_mcp_server requires a non-empty `name`', undefined, ctx)
1238
+ return
1239
+ }
1240
+ const scope = msg?.scope === 'project' ? 'project' : 'user'
1241
+
1242
+ const sessionId = msg?.sessionId || client?.activeSessionId
1243
+ const entry = resolveSession(ctx, msg, client)
1244
+ if (!entry) {
1245
+ sendError(ws, requestId, 'MCP_SERVER_REMOVE_NOT_APPLIED', 'No active session', undefined, ctx)
1246
+ return
1247
+ }
1248
+ if (!entry.session || typeof entry.session.removeMcpServer !== 'function') {
1249
+ sendError(ws, requestId, 'MCP_CONFIG_UNSUPPORTED',
1250
+ 'This provider does not support removing MCP servers (its MCP config is managed by the underlying CLI).',
1251
+ undefined, ctx)
1252
+ return
1253
+ }
1254
+
1255
+ try {
1256
+ const result = await entry.session.removeMcpServer(name, scope)
1257
+ if (!result || result.ok !== true) {
1258
+ sendError(ws, requestId, 'MCP_SERVER_REMOVE_NOT_APPLIED',
1259
+ result?.error || `Failed to remove MCP server '${name}'.`, undefined, ctx)
1260
+ return
1261
+ }
1262
+ if (result.found === false) {
1263
+ sendError(ws, requestId, 'MCP_SERVER_NOT_FOUND',
1264
+ `No MCP server named '${name}' in ${scope} scope.`, undefined, ctx)
1265
+ return
1266
+ }
1267
+ // The parked-set may have lost an entry (a disabled server that was removed),
1268
+ // so flush session state immediately rather than waiting on the debounce —
1269
+ // same discipline as the #6824 toggle handler.
1270
+ try {
1271
+ ctx.sessions.sessionManager?.serializeState?.()
1272
+ } catch (err) {
1273
+ sessionLogger(sessionId).warn(`Failed to persist session state after MCP remove on ${sessionId}: ${err?.message || err}`)
1274
+ }
1275
+ // sessionLogger, not loggerForSession — see the note in handleAddMcpServer:
1276
+ // an absent sessionId made a successful remove report as REMOVE_NOT_APPLIED.
1277
+ sessionLogger(sessionId).info(
1278
+ `MCP server '${name}' removed from ${scope} scope by ${client.id} on session ${sessionId}`,
1279
+ )
1280
+ } catch (err) {
1281
+ sendError(ws, requestId, 'MCP_SERVER_REMOVE_NOT_APPLIED',
1282
+ `Failed to remove MCP server '${name}': ${err?.message || String(err)}`, undefined, ctx)
1283
+ }
1284
+ }
1285
+
796
1286
  export const settingsHandlers = {
797
1287
  set_model: handleSetModel,
798
1288
  set_permission_mode: handleSetPermissionMode,
@@ -803,6 +1293,15 @@ export const settingsHandlers = {
803
1293
  list_providers: handleListProviders,
804
1294
  set_thinking_level: handleSetThinkingLevel,
805
1295
  set_permission_rules: handleSetPermissionRules,
1296
+ // #6824: per-server MCP enable/disable (BYOK lane; capability-gated).
1297
+ set_mcp_server_enabled: handleSetMcpServerEnabled,
1298
+ // #6822: submit a pasted OAuth authorization code (BYOK lane; capability-gated).
1299
+ submit_mcp_auth_code: handleSubmitMcpAuthCode,
1300
+ // #6974: MCP config MUTATION — add/remove a server (BYOK lane;
1301
+ // capability-gated AND strict-primary gated: anything that is not the primary
1302
+ // token class is refused, since a configured server is host code execution).
1303
+ add_mcp_server: handleAddMcpServer,
1304
+ remove_mcp_server: handleRemoveMcpServer,
806
1305
  // promptEvaluatorSkipPattern keeps its bespoke handler because the
807
1306
  // payload shape (string-or-null + pre-validation regex compile to
808
1307
  // surface a distinct error code) doesn't fit the boolean/string
@@ -6,6 +6,14 @@
6
6
  * sever-shells + force-re-auth behavior lives in WsServer's `token_rotated`
7
7
  * handler (fired by the `TokenManager.revoke()` event) — this handler only
8
8
  * gates the request and pulls the trigger.
9
+ *
10
+ * #6965: that broadcast is the revoke's ACK, and WsServer withholds it until the
11
+ * new token's persist reports success — so a client is never told the primary token
12
+ * is dead before the revocation has been stored. A durability failure sends
13
+ * `{ type: 'error', code: 'REVOKE_NOT_DURABLE' }` FIRST and then the broadcast
14
+ * anyway: the revoke holds in the running process, so the client must still
15
+ * re-authenticate (that broadcast is its only automatic trigger for doing so), and
16
+ * the "may not survive a restart" caveat rides the error.
9
17
  */
10
18
 
11
19
  import { createLogger } from '../logger.js'
@@ -17,9 +25,10 @@ const log = createLogger('token-handlers')
17
25
  *
18
26
  * Gated on `client.isPrimaryToken === true` (the same class the user-shell
19
27
  * create/terminal gates use): a paired or pairing-bound client must NOT be able
20
- * to revoke the primary token. On success there is no explicit ack — the
28
+ * to revoke the primary token. On success there is no handler-local ack — the
21
29
  * requester is de-authed by the revoke and receives the token-less
22
- * `token_rotated{reason:'revoke'}` broadcast like every other connection.
30
+ * `token_rotated{reason:'revoke'}` broadcast (gated on the durable write, #6965)
31
+ * like every other connection.
23
32
  */
24
33
  function handleRevokeToken(ws, client, msg, ctx) {
25
34
  const correlationId = ctx.correlationId