@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,663 @@
1
+ /**
2
+ * Shared utilities, constants, and validators for message handlers.
3
+ *
4
+ * This module is the dependency root for handler modules — it must NOT
5
+ * import from ws-message-handlers.js or any handler module to avoid
6
+ * circular dependencies.
7
+ */
8
+ import { statSync, realpathSync, readFileSync } from 'fs'
9
+ import { homedir } from 'os'
10
+ import { resolve, relative, sep } from 'path'
11
+ import { createLogger } from './logger.js'
12
+
13
+ const log = createLogger('handler-utils')
14
+
15
+ // -- Permission modes --
16
+ // `description` is a short, plain-English sentence the dashboard
17
+ // surfaces as a tooltip / inline hint (#4013). Keep terse — the picker
18
+ // space is limited and screen readers re-narrate the whole string.
19
+ // The auto-mode description deliberately names `--dangerously-skip-permissions`
20
+ // so users searching for that Claude CLI flag find the chroxy equivalent.
21
+ export const PERMISSION_MODES = [
22
+ { id: 'approve', label: 'Approve', description: 'Default. Every tool call gates on your approval in the dashboard or mobile app.' },
23
+ { id: 'acceptEdits', label: 'Accept Edits', description: 'Auto-approve Read/Write/Edit/NotebookEdit/Glob/Grep. Bash, MCP, and other tools still gate on approval.' },
24
+ { id: 'auto', label: 'Auto (skip all prompts)', description: 'Auto-approve every tool call without prompting. Equivalent to `claude --dangerously-skip-permissions`.' },
25
+ { id: 'plan', label: 'Plan', description: 'Plan mode — Claude is asked to plan before acting; each tool call still gates on approval.' },
26
+ ]
27
+ export const ALLOWED_PERMISSION_MODE_IDS = new Set(PERMISSION_MODES.map((m) => m.id))
28
+
29
+ // -- Attachment validation constants --
30
+ export const MAX_ATTACHMENT_COUNT = 5
31
+ export const MAX_IMAGE_SIZE = 2 * 1024 * 1024 // 2MB decoded
32
+ export const MAX_DOCUMENT_SIZE = 5 * 1024 * 1024 // 5MB decoded
33
+ export const ALLOWED_IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/gif', 'image/webp'])
34
+ const ALLOWED_DOC_TYPES = new Set(['application/pdf', 'text/plain', 'text/markdown', 'text/csv', 'application/json'])
35
+
36
+ /**
37
+ * Validate an attachments array from a WebSocket message.
38
+ * Returns null if valid, or an error string if invalid.
39
+ */
40
+ export function validateAttachments(attachments) {
41
+ if (!Array.isArray(attachments)) return 'attachments must be an array'
42
+ if (attachments.length > MAX_ATTACHMENT_COUNT) return `too many attachments (max ${MAX_ATTACHMENT_COUNT})`
43
+ for (let i = 0; i < attachments.length; i++) {
44
+ const att = attachments[i]
45
+ if (!att || typeof att !== 'object') return `attachment[${i}]: not an object`
46
+ if (typeof att.type !== 'string' || (att.type !== 'image' && att.type !== 'document' && att.type !== 'file_ref')) {
47
+ return `attachment[${i}]: type must be 'image', 'document', or 'file_ref'`
48
+ }
49
+
50
+ // file_ref: project-relative path — server reads content before sending to Claude
51
+ if (att.type === 'file_ref') {
52
+ if (typeof att.path !== 'string' || !att.path.trim()) {
53
+ return `attachment[${i}]: file_ref requires a non-empty path`
54
+ }
55
+ if (att.path.startsWith('/')) {
56
+ return `attachment[${i}]: file_ref path must not be absolute`
57
+ }
58
+ if (att.path.split('/').includes('..')) {
59
+ return `attachment[${i}]: file_ref path must not contain traversal (..)`
60
+ }
61
+ continue
62
+ }
63
+
64
+ if (typeof att.mediaType !== 'string') return `attachment[${i}]: missing mediaType`
65
+ if (typeof att.data !== 'string') return `attachment[${i}]: missing data`
66
+ if (typeof att.name !== 'string') return `attachment[${i}]: missing name`
67
+
68
+ if (att.type === 'image' && !ALLOWED_IMAGE_TYPES.has(att.mediaType)) {
69
+ return `attachment[${i}]: type 'image' requires an image mediaType`
70
+ }
71
+ if (att.type === 'document' && !ALLOWED_DOC_TYPES.has(att.mediaType)) {
72
+ return `attachment[${i}]: type 'document' requires a document mediaType`
73
+ }
74
+
75
+ const decodedSize = Math.ceil(att.data.length * 3 / 4)
76
+ const maxSize = att.type === 'image' ? MAX_IMAGE_SIZE : MAX_DOCUMENT_SIZE
77
+ if (decodedSize > maxSize) {
78
+ return `attachment[${i}]: exceeds ${maxSize / (1024 * 1024)}MB limit`
79
+ }
80
+ }
81
+ return null
82
+ }
83
+
84
+ const MAX_FILE_REF_SIZE = 1 * 1024 * 1024 // 1MB max per file_ref
85
+
86
+ /**
87
+ * Resolve file_ref attachments by reading file content from the session's cwd.
88
+ * Converts file_ref entries to standard document attachments with base64 data.
89
+ * Non-file_ref attachments are passed through unchanged.
90
+ *
91
+ * @param {Array} attachments - Validated attachment array
92
+ * @param {string} cwd - Session working directory
93
+ * @returns {Array} Resolved attachments (file_ref → document with inline text)
94
+ */
95
+ export function resolveFileRefAttachments(attachments, cwd) {
96
+ if (!attachments?.length || !cwd) return attachments
97
+ return attachments.map(att => {
98
+ if (att.type !== 'file_ref') return att
99
+ const absPath = resolve(cwd, att.path)
100
+ // Security: ensure resolved path is within cwd
101
+ const rel = relative(cwd, absPath)
102
+ if (rel.startsWith('..') || resolve(cwd, rel) !== absPath) {
103
+ return { type: 'document', mediaType: 'text/plain', data: Buffer.from(`[Error: cannot read file outside project: ${att.path}]`).toString('base64'), name: att.name || att.path }
104
+ }
105
+ // Security: verify after symlink resolution to prevent symlink escape
106
+ try {
107
+ const realAbs = realpathSync(absPath)
108
+ const realCwd = realpathSync(cwd)
109
+ const realRel = relative(realCwd, realAbs)
110
+ if (realRel.startsWith('..')) {
111
+ return { type: 'document', mediaType: 'text/plain', data: Buffer.from(`[Error: cannot read file outside project: ${att.path}]`).toString('base64'), name: att.name || att.path }
112
+ }
113
+ } catch {
114
+ // realpathSync fails if file doesn't exist — let readFileSync handle ENOENT below
115
+ }
116
+ try {
117
+ const stat = statSync(absPath)
118
+ if (stat.size > MAX_FILE_REF_SIZE) {
119
+ return { type: 'document', mediaType: 'text/plain', data: Buffer.from(`[Error: file too large (${(stat.size / 1024).toFixed(0)}KB, max 1MB): ${att.path}]`).toString('base64'), name: att.name || att.path }
120
+ }
121
+ // Detect binary files by checking for null bytes in the first 8KB
122
+ const raw = readFileSync(absPath)
123
+ const sample = raw.subarray(0, 8192)
124
+ if (sample.includes(0)) {
125
+ return { type: 'document', mediaType: 'text/plain', data: Buffer.from(`[Error: binary file not supported: ${att.path}]`).toString('base64'), name: att.name || att.path }
126
+ }
127
+ const content = raw.toString('utf-8')
128
+ return { type: 'document', mediaType: 'text/plain', data: Buffer.from(content).toString('base64'), name: att.name || att.path }
129
+ } catch (err) {
130
+ const msg = err?.code === 'ENOENT' ? 'file not found' : err?.code === 'EACCES' ? 'permission denied' : 'read error'
131
+ return { type: 'document', mediaType: 'text/plain', data: Buffer.from(`[Error: ${msg}: ${att.path}]`).toString('base64'), name: att.name || att.path }
132
+ }
133
+ })
134
+ }
135
+
136
+ /**
137
+ * Directories within $HOME that hold credentials or other sensitive
138
+ * material a session should NEVER use as a working directory. Found in
139
+ * the 2026-04-11 production readiness audit (Adversary A1 + Blocker 1):
140
+ * the old validateCwdWithinHome accepted any $HOME-relative path,
141
+ * letting an authenticated client set cwd to ~/.ssh / ~/.aws / etc. and
142
+ * read or write credentials via the normal file-op handlers.
143
+ *
144
+ * Match semantics: the FIRST path segment of the real-resolved cwd
145
+ * relative to $HOME must not match any entry. So `~/.ssh/keys` is
146
+ * rejected (first segment `.ssh`) but `~/projects/foo/.ssh/keys` is
147
+ * allowed (first segment `projects`). Project-local directories that
148
+ * happen to contain a `.ssh` subdir are NOT blocked — blocking them
149
+ * would be overly restrictive for legitimate tooling that scaffolds
150
+ * these directories inside project trees.
151
+ *
152
+ * The check is layered on top of the existing home-prefix check, so
153
+ * it's defense-in-depth — active whether or not the user has also set
154
+ * an explicit workspaceRoots allowlist.
155
+ */
156
+ const FORBIDDEN_HOME_SUBDIRS = new Set([
157
+ '.ssh',
158
+ '.aws',
159
+ '.azure', // `az login` tokens + service-principal secrets
160
+ '.gcloud', // legacy path (GCP's newer tools use ~/.config/gcloud)
161
+ '.gnupg',
162
+ '.docker',
163
+ '.kube',
164
+ '.config', // blocks ~/.config/gcloud, ~/.config/gh, ~/.config/op, etc.
165
+ '.netrc', // file, but catch accidental dir usage
166
+ '.password-store',
167
+ '.pgpass',
168
+ '.git-credentials',
169
+ '.npmrc',
170
+ '.yarnrc',
171
+ '.pypirc',
172
+ '.m2', // Maven settings.xml frequently holds repo credentials
173
+ '.terraform.d', // Terraform Cloud login tokens
174
+ '.helm', // Helm repo credentials
175
+ '.rclone', // rclone remote configs with cloud-storage keys
176
+ '.dbt', // dbt profiles with warehouse passwords
177
+ '.passage', // passage password store
178
+ // Chroxy's own internal state: supervisor PID, known-good git ref,
179
+ // push tokens, config. Added 2026-04-11 (Adversary A9) — without
180
+ // this, an authenticated client could create a session in
181
+ // ~/.chroxy, write_file `known-good-ref`, and poison the
182
+ // supervisor's crash-rollback target.
183
+ '.chroxy',
184
+ // Claude Code's own internal state: conversation JSONLs, settings,
185
+ // hooks. Pairs with the A8 conversation-scope fix — prevents a
186
+ // bound client from creating a session that writes directly into
187
+ // the JSONL ring Claude Code is reading from.
188
+ '.claude',
189
+ ])
190
+
191
+ /**
192
+ * Returns true if `absPath` is underneath OR equal to `baseDir`,
193
+ * using segment-aware comparison so `/home/user/workspace` is NOT
194
+ * considered within `/home/user/work`.
195
+ *
196
+ * Both arguments must already be realpath-resolved and absolute.
197
+ *
198
+ * Edge case: when `baseDir` already ends with a path separator (e.g.
199
+ * POSIX `'/'` filesystem root, or Windows drive roots like `'C:\\'`),
200
+ * `baseDir + sep` would become `'//'` / `'C:\\\\'` and startsWith()
201
+ * would return false for paths that ARE inside the base. Strip the
202
+ * trailing separator first to normalize. Found by Copilot review on
203
+ * PR #2808.
204
+ */
205
+ // #5835: a client "views" a session iff it's its active session or in its
206
+ // subscribed set — the SAME viewing clause ws-forwarding's terminalSubscriberFilter
207
+ // uses to scope terminal_output/terminal_size broadcasts. Every PTY-touching
208
+ // terminal handler (terminal_size send, terminal_resize, terminal_input) gates on
209
+ // this so a client that merely knows a session id — but isn't watching it — can't
210
+ // drive or leak its terminal (#5840 review; extended to terminal_input in #5842).
211
+ // Shared here so the session-handlers and input-handlers copies can't drift.
212
+ //
213
+ // #6030: this is ALSO the single source of truth for the answer-authorization
214
+ // invariant "who may ANSWER a permission/question == who could have RECEIVED it".
215
+ // The broadcaster's recipient predicate (_matchesSession), the unbound
216
+ // AskUserQuestion answer guard (input-handlers.js, #4788), and the unbound
217
+ // permission-response guard (settings-handlers.js, #4798) all route through this
218
+ // SAME function — so if the receiver set is ever widened (a new viewer class, the
219
+ // LAN shared-session epic), the answer guards follow automatically and cannot
220
+ // drift back into the cross-session answer-hijack vector #4788/#4798 closed.
221
+ export function isSessionViewer(client, sid) {
222
+ return client.activeSessionId === sid ||
223
+ Boolean(client.subscribedSessionIds && client.subscribedSessionIds.has(sid))
224
+ }
225
+
226
+ // #5985b (epic #5982): is this session entry a general-purpose user shell? The
227
+ // session-scoped viewer/primary-claim gates that suffice for the claude-tui
228
+ // mirror are NOT enough for a root shell — terminal_subscribe (output exfil),
229
+ // terminal_resize, and terminal_input must additionally require the PRIMARY
230
+ // token class (swarm-audit findings C1/C4). Reads the positive `isUserShell`
231
+ // class discriminator (false on every existing session type), so the gates that
232
+ // call this are inert until the UserShellSession provider lands (#5983).
233
+ export function isUserShellSession(entry) {
234
+ return entry?.session?.constructor?.isUserShell === true
235
+ }
236
+
237
+ // #5835 / audit P1-2: the single predicate for who RECEIVES a session's live
238
+ // terminal mirror — opted into the terminal (`terminalSessionIds`) AND a viewer
239
+ // of the session (`isSessionViewer`). The delivery filter
240
+ // (ws-forwarding's terminalSubscriberFilter) and the coalescer gate
241
+ // (ws-server's _syncTerminalMirror) MUST use the SAME predicate: gate-true /
242
+ // filter-false wastes the coalescer on nobody, and gate-false / filter-true is
243
+ // a black terminal for a real viewer. Both inlined it before and could drift;
244
+ // shared here so they can't.
245
+ export function terminalMirrorRecipient(client, sid) {
246
+ return Boolean(client.terminalSessionIds && client.terminalSessionIds.has(sid)) &&
247
+ isSessionViewer(client, sid)
248
+ }
249
+
250
+ export function isPathWithin(absPath, baseDir) {
251
+ if (absPath === baseDir) return true
252
+ // Normalize: strip a trailing separator so filesystem root and
253
+ // drive roots work correctly. After this, baseDir is never
254
+ // '/' or 'C:\\' — it's '' or 'C:'. We then append sep before the
255
+ // prefix match so we still require a separator boundary.
256
+ const normalized = baseDir.endsWith(sep) ? baseDir.slice(0, -1) : baseDir
257
+ // If the normalization drove baseDir to an empty string, the
258
+ // original was '/' (posix) — everything absolute is within it.
259
+ if (normalized === '') return true
260
+ return absPath.startsWith(normalized + sep)
261
+ }
262
+
263
+ /**
264
+ * Returns true if `absPath` touches any FORBIDDEN_HOME_SUBDIRS entry
265
+ * at any depth below $HOME. E.g. `/home/user/.ssh` and
266
+ * `/home/user/.config/gcloud/credentials` both match.
267
+ *
268
+ * The match is CASE-INSENSITIVE on purpose: on case-insensitive
269
+ * filesystems (macOS APFS default, Windows NTFS default), `~/.SSH` is
270
+ * the same directory as `~/.ssh` but the raw Set lookup would miss it
271
+ * — trivially bypassing the deny-list with `cwd: ~/.SSH`. Doing a
272
+ * lowercase compare closes that bypass on every filesystem. On
273
+ * case-sensitive filesystems nobody sensibly creates two distinct
274
+ * `.ssh`/`.SSH` directories, so the broader match is safe.
275
+ * Found by agent review on PR #2808.
276
+ */
277
+ function pathTouchesForbiddenSubdir(absPath, home) {
278
+ if (!isPathWithin(absPath, home)) return false
279
+ const rel = relative(home, absPath)
280
+ if (rel === '') return false
281
+ const firstSegment = rel.split(sep)[0].toLowerCase()
282
+ return FORBIDDEN_HOME_SUBDIRS.has(firstSegment)
283
+ }
284
+
285
+ /**
286
+ * Validate that a cwd path is allowed as a session working directory.
287
+ *
288
+ * Layers (each must pass):
289
+ *
290
+ * 1. Path hygiene — must exist, be a directory, and be realpath-
291
+ * resolvable. Catches broken or non-directory paths up front.
292
+ *
293
+ * 2. Credential-directory deny-list — regardless of any allowlist, the
294
+ * cwd must NOT be inside any FORBIDDEN_HOME_SUBDIRS entry below
295
+ * $HOME. Closes the 2026-04-11 audit Adversary A1 attack where an
296
+ * authenticated client could set cwd to ~/.ssh to read credentials.
297
+ *
298
+ * 3. Workspace allowlist (opt-in) — if `config.workspaceRoots` is a
299
+ * non-empty array, the cwd must be inside at least one of the
300
+ * realpath-resolved entries. This is the strict mode audit blocker 1
301
+ * recommends for security-conscious deployments.
302
+ *
303
+ * 4. Home fallback (default) — if no allowlist is configured, the cwd
304
+ * must still be inside $HOME. Preserves backward compatibility for
305
+ * existing deployments while the deny-list (layer 2) closes the
306
+ * worst of the attack surface.
307
+ *
308
+ * @param {string} cwd - Directory path to validate
309
+ * @param {object} [config] - Optional runtime config. `config.workspaceRoots` is an array of absolute paths that form the allowlist. `config.homeOverride` is a test-only override for `os.homedir()`; setting it lets tests run hermetically against a throwaway directory without touching the real user home. Never use homeOverride in production code.
310
+ * @returns {string|null} Error message or null if valid
311
+ */
312
+ export function validateCwdAllowed(cwd, config = null) {
313
+ // Layer 1: path hygiene
314
+ try {
315
+ const s = statSync(cwd)
316
+ if (!s.isDirectory()) return `Not a directory: ${cwd}`
317
+ } catch {
318
+ return `Directory does not exist: ${cwd}`
319
+ }
320
+ let realCwd
321
+ try {
322
+ realCwd = realpathSync(cwd)
323
+ } catch {
324
+ return `Cannot resolve path: ${cwd}`
325
+ }
326
+
327
+ // Layer 2: credential-directory deny-list (always active).
328
+ // `homeOverride` exists so tests can use a hermetic fake home
329
+ // directory instead of creating throwaway dirs under the user's
330
+ // real ~/.config. Never used in production — config.js does not
331
+ // declare or forward homeOverride from user config.
332
+ const home = (config?.homeOverride && typeof config.homeOverride === 'string')
333
+ ? realpathSync(config.homeOverride)
334
+ : homedir()
335
+ if (pathTouchesForbiddenSubdir(realCwd, home)) {
336
+ return 'Directory is not allowed: credential/config directories under $HOME are blocked for security'
337
+ }
338
+
339
+ // Layer 3: explicit allowlist (opt-in, strict)
340
+ const roots = Array.isArray(config?.workspaceRoots)
341
+ ? config.workspaceRoots.filter((r) => typeof r === 'string' && r.length > 0)
342
+ : []
343
+ if (roots.length > 0) {
344
+ let anyRootResolved = false
345
+ for (const root of roots) {
346
+ let realRoot
347
+ try {
348
+ realRoot = realpathSync(root)
349
+ } catch {
350
+ // Configured root that doesn't resolve is a config error — skip
351
+ // it rather than failing the whole check, but it can't match.
352
+ continue
353
+ }
354
+ anyRootResolved = true
355
+ if (isPathWithin(realCwd, realRoot)) return null
356
+ }
357
+ // If at least ONE root resolved, enforce strictly. Otherwise every
358
+ // configured root is stale (mount offline, typo, removed dir) and
359
+ // the user would be silently locked out of every session. Fall
360
+ // through to the home-fallback in that case rather than denying
361
+ // everything. Found by Copilot review on PR #2808.
362
+ if (anyRootResolved) {
363
+ return `Directory is not within any configured workspace root (${roots.length} configured)`
364
+ }
365
+ // else fall through to layer 4 home fallback
366
+ }
367
+
368
+ // Layer 4: home fallback (default)
369
+ if (!isPathWithin(realCwd, home)) {
370
+ return 'Directory must be within your home directory'
371
+ }
372
+ return null
373
+ }
374
+
375
+ /**
376
+ * @deprecated Use validateCwdAllowed(cwd, config) instead.
377
+ *
378
+ * Kept as a back-compat alias that calls validateCwdAllowed with no
379
+ * config, so the deny-list layer is still active for callers that
380
+ * haven't been migrated yet. New code and tests should use the name
381
+ * that reflects the current behavior.
382
+ */
383
+ export function validateCwdWithinHome(cwd) {
384
+ return validateCwdAllowed(cwd, null)
385
+ }
386
+
387
+ // Exported for tests
388
+ export { FORBIDDEN_HOME_SUBDIRS }
389
+
390
+ /**
391
+ * Check whether a connected WS client declared a specific capability during auth.
392
+ *
393
+ * @param {WebSocket} ws - The WebSocket connection object
394
+ * @param {string} capability - The capability string to check
395
+ * @returns {boolean} true if the client declared the capability, false otherwise
396
+ */
397
+ export function clientHasCapability(ws, capability) {
398
+ return ws.clientCapabilities?.has(capability) ?? false
399
+ }
400
+
401
+ /** Broadcast client_focus_changed to other clients when a client's active session changes */
402
+ export function broadcastFocusChanged(client, sessionId, ctx) {
403
+ ctx.transport.broadcast(
404
+ { type: 'client_focus_changed', clientId: client.id, sessionId, timestamp: Date.now() },
405
+ (c) => c.id !== client.id
406
+ )
407
+ }
408
+
409
+ /**
410
+ * Auto-subscribe all other authenticated clients to a session.
411
+ * Call after creating a session so streaming messages reach every connected client
412
+ * (dashboard, other mobile clients, etc.) without requiring explicit subscribe_sessions.
413
+ */
414
+ export function autoSubscribeOtherClients(sessionId, excludeWs, ctx) {
415
+ for (const [clientWs, c] of ctx.transport.clients) {
416
+ if (c.authenticated && clientWs !== excludeWs) {
417
+ // #5563: route through the index-maintaining helper so the
418
+ // sessionId→clients reverse index stays in sync. Falls back to a bare
419
+ // add for fixtures whose ctx predates the helper.
420
+ if (typeof ctx.transport.subscribeClient === 'function') {
421
+ ctx.transport.subscribeClient(c, sessionId)
422
+ } else {
423
+ // lint-ignore-ws-index-mutation: guarded fixture fallback. This
424
+ // else-branch only runs for legacy test fixtures whose ctx predates the
425
+ // #5563 index-maintaining subscribeClient helper; production always takes
426
+ // the helper path above, so this bare add can't drift the reverse index.
427
+ c.subscribedSessionIds.add(sessionId)
428
+ }
429
+ }
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Resolve a session from a message and client context.
435
+ * Prefers msg.sessionId, falls back to client.activeSessionId.
436
+ * Returns the session entry, or null if not found.
437
+ *
438
+ * If the client has a boundSessionId, enforces that the resolved session
439
+ * matches the binding. Returns null if the binding is violated.
440
+ *
441
+ * @param {object} ctx - Handler context with sessionManager
442
+ * @param {object} msg - Incoming WebSocket message
443
+ * @param {object} client - Connected client state
444
+ * @returns {object|null} Session entry or null
445
+ */
446
+ export function resolveSession(ctx, msg, client) {
447
+ const sid = msg.sessionId || client?.activeSessionId
448
+
449
+ // Enforce session token binding: a bound client can only resolve its own
450
+ // session. If a specific sid was requested and it doesn't match, reject.
451
+ if (sid && client?.boundSessionId && client.boundSessionId !== sid) {
452
+ return null
453
+ }
454
+
455
+ // Delegate to sessionManager — its getSession handles null/undefined sid
456
+ // (real SessionManager returns null, cliSession adapter returns default entry).
457
+ return ctx.sessions?.sessionManager?.getSession(sid) ?? null
458
+ }
459
+
460
+ /**
461
+ * Send a `session_error` envelope to a WebSocket client (#4773, #4809).
462
+ *
463
+ * All `ctx.transport.send(ws, { type: 'session_error', message })` sites across the
464
+ * handler modules build the same two-field payload by hand. Centralising the
465
+ * shape here means a future schema tweak (adding `code`, `recoverable`,
466
+ * `sessionId`, etc.) lands in one place instead of being scattered across
467
+ * every handler. As of #4809 only ~11 deliberate-soft-fallback sites remain
468
+ * in src/handlers/ — every one of them carries an extra field beyond
469
+ * `message` (the `input_conflict` category, the SESSION_TOKEN_MISMATCH
470
+ * `buildSessionTokenMismatchPayload` spread, or the create-session `code`
471
+ * field) so they cannot use this helper without extending its signature.
472
+ *
473
+ * Routed through `ctx.transport.send` rather than `ws.send` so it stays compatible
474
+ * with the existing handler tests (which monkey-patch `ctx.transport.send` and
475
+ * inspect the captured payloads). In production both surfaces ultimately
476
+ * call `ws.send(JSON.stringify(msg))` via WsServer._send, so behaviour is
477
+ * identical.
478
+ *
479
+ * @param {WebSocket} ws - Target WebSocket connection
480
+ * @param {object} ctx - Handler context with `send(ws, msg)`
481
+ * @param {string} message - Human-readable, user-facing error message
482
+ */
483
+ export function sendSessionError(ws, ctx, message) {
484
+ if (!ws || !ctx || typeof ctx.transport?.send !== 'function') return
485
+ ctx.transport.send(ws, { type: 'session_error', message })
486
+ }
487
+
488
+ /**
489
+ * Resolve a session and emit a canonical "No active session" error on miss (#4773).
490
+ *
491
+ * Wraps the 13-times-verbatim handler pattern:
492
+ *
493
+ * const entry = resolveSession(ctx, msg, client)
494
+ * if (!entry) {
495
+ * ctx.transport.send(ws, { type: 'session_error', message: 'No active session' })
496
+ * return
497
+ * }
498
+ *
499
+ * Returning `null` on miss (after emitting the envelope) preserves the
500
+ * existing call-site idiom — callers stay `if (!entry) return`. On a hit
501
+ * the helper is a pure pass-through to `resolveSession`, including its
502
+ * session-token-binding enforcement (a bound client asking for a different
503
+ * session resolves to `null` and triggers the same error envelope, matching
504
+ * the pre-refactor behaviour).
505
+ *
506
+ * @param {WebSocket} ws - Target WebSocket connection for the error envelope
507
+ * @param {object} ctx - Handler context with sessionManager + send
508
+ * @param {object} msg - Incoming WebSocket message
509
+ * @param {object} client - Connected client state
510
+ * @returns {object|null} Session entry on hit, null after emitting on miss
511
+ */
512
+ export function resolveSessionOrError(ws, ctx, msg, client) {
513
+ const entry = resolveSession(ctx, msg, client)
514
+ if (!entry) {
515
+ sendSessionError(ws, ctx, 'No active session')
516
+ return null
517
+ }
518
+ return entry
519
+ }
520
+
521
+ /**
522
+ * Capability-gate the bound session's provider before invoking a method (#4773).
523
+ *
524
+ * Wraps the 6-times-repeated handler pattern:
525
+ *
526
+ * if (typeof entry.session.setX !== 'function') {
527
+ * ctx.transport.send(ws, { type: 'session_error',
528
+ * message: 'This provider does not support X' })
529
+ * return
530
+ * }
531
+ *
532
+ * Returns `true` when the method is callable so the caller can proceed,
533
+ * `false` (after emitting the `session_error` envelope) otherwise. The
534
+ * helper also defends against a missing `entry` / `entry.session` so call
535
+ * sites don't need a second null-check before reaching the gate.
536
+ *
537
+ * @param {WebSocket} ws - Target WebSocket connection for the error envelope
538
+ * @param {object} ctx - Handler context with `send(ws, msg)`
539
+ * @param {object|null} entry - Session entry from resolveSession[OrError]
540
+ * @param {string} method - Method name to probe on entry.session
541
+ * @param {string} message - Human-readable capability-gate error message
542
+ * @returns {boolean} true if method is callable, false after emitting on miss
543
+ */
544
+ export function requireSessionMethod(ws, ctx, entry, method, message) {
545
+ if (!entry || !entry.session || typeof entry.session[method] !== 'function') {
546
+ sendSessionError(ws, ctx, message)
547
+ return false
548
+ }
549
+ return true
550
+ }
551
+
552
+ /**
553
+ * Send a structured error response to a WebSocket client.
554
+ * Use in handler catch blocks so the client can clear loading state
555
+ * and surface a user-facing message instead of silently spinning.
556
+ *
557
+ * Optionally accepts a `data` object whose own enumerable fields are merged
558
+ * onto the wire payload alongside the canonical four (#3538). Use this to
559
+ * attach structured context — e.g. `actualAuthor` on `INVALID_AUTHOR` — so
560
+ * dashboard clients can branch on `code` and read fields directly instead of
561
+ * regex-parsing the human-readable `message`. Canonical fields always win:
562
+ * `data` keys named `type`/`requestId`/`code`/`message` are ignored, so a
563
+ * misbehaving caller cannot spoof the wire shape.
564
+ *
565
+ * #5632: routes through the encryption-aware transport when a handler `ctx`
566
+ * is supplied. `sendError` emits a plaintext `{ type: 'error' }` frame, and the
567
+ * client's post-handshake plaintext guard (connection.ts) closes the socket on
568
+ * any non-`encrypted` frame that isn't a handshake frame once E2E encryption is
569
+ * established. Passing `ctx` makes the error go out through `ctx.transport.send`
570
+ * (→ WsServer._send → the per-client encrypting sender), so a post-handshake
571
+ * error is encrypted (the client decrypts it normally) and a pre-handshake one
572
+ * stays cleartext (the client's guard is inactive while encState is null —
573
+ * correct). When `ctx` is absent (pre-auth call sites with no handler context,
574
+ * e.g. pairing rejectIfBound) we fall back to the raw `ws.send`; those paths run
575
+ * before encryption is established, so cleartext is correct there too.
576
+ *
577
+ * @param {WebSocket} ws - Target WebSocket connection
578
+ * @param {string|null} requestId - Correlating request ID (may be null)
579
+ * @param {string} code - Machine-readable error code (e.g. 'HANDLER_ERROR')
580
+ * @param {string} message - Human-readable error description
581
+ * @param {object} [data] - Optional structured fields merged into the payload
582
+ * @param {object} [ctx] - Handler context; when present routes via
583
+ * `ctx.transport.send` so the frame is encrypted for post-handshake clients
584
+ */
585
+ export function sendError(ws, requestId, code, message, data, ctx) {
586
+ if (!ws || ws.readyState !== 1) return
587
+ const payload = { type: 'error', requestId: requestId ?? null, code, message }
588
+ if (data && typeof data === 'object' && !Array.isArray(data)) {
589
+ for (const [key, value] of Object.entries(data)) {
590
+ // Canonical fields are reserved — never let a caller clobber them.
591
+ if (key === 'type' || key === 'requestId' || key === 'code' || key === 'message') continue
592
+ // #3578: block prototype-pollution keys. event-normalizer.js applies
593
+ // the same guard. sendError is a generic utility that may end up
594
+ // called with partially user-derived data, so harden defensively even
595
+ // though no current caller passes untrusted input.
596
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue
597
+ payload[key] = value
598
+ }
599
+ }
600
+ // #5632: prefer the encryption-aware transport so post-handshake errors are
601
+ // encrypted; fall back to raw send for pre-auth call sites without a ctx.
602
+ // #5702 (8a): guard both sends. A throw here (e.g. a torn-down socket) would
603
+ // otherwise escape an error-reporting path — which often runs from a catch
604
+ // block — and could mask the original failure or take down the caller. The
605
+ // error frame failing to reach a half-open client is itself non-fatal, so we
606
+ // log and move on rather than rethrow.
607
+ if (ctx && typeof ctx.transport?.send === 'function') {
608
+ try {
609
+ ctx.transport.send(ws, payload)
610
+ } catch (err) {
611
+ log.warn(`sendError: transport send failed for ${payload.code || 'error'}: ${String(err?.message || err)}`)
612
+ }
613
+ return
614
+ }
615
+ try {
616
+ ws.send(JSON.stringify(payload))
617
+ } catch (err) {
618
+ log.warn(`sendError: raw send failed for ${payload.code || 'error'}: ${String(err?.message || err)}`)
619
+ }
620
+ }
621
+
622
+ // Issue #2912: every handler that rejects with SESSION_TOKEN_MISMATCH used to
623
+ // build its own ad-hoc payload — some included boundSessionId/boundSessionName
624
+ // (PR #2911 for create_session + resume_conversation), some included only
625
+ // `code` and `message`. Clients branching on `code === 'SESSION_TOKEN_MISMATCH'`
626
+ // therefore saw divergent shapes depending on which handler rejected them.
627
+ // Centralise the shape here so every call site produces the same four fields.
628
+ export const SESSION_TOKEN_MISMATCH_DEFAULT_MESSAGE = 'Not authorized to access this session'
629
+
630
+ /**
631
+ * Build the canonical SESSION_TOKEN_MISMATCH error payload fields.
632
+ *
633
+ * Always returns `{ code, message, boundSessionId, boundSessionName }` so
634
+ * clients can rely on the shape regardless of which handler rejected. When
635
+ * the bound session is still resolvable via `sessionManager`, `boundSessionName`
636
+ * is the session's name; when the binding is stale or no sessionManager is
637
+ * available, it is `null`. When the client has no bound session at all (the
638
+ * HTTP fallback path), both `boundSessionId` and `boundSessionName` are `null`.
639
+ *
640
+ * @param {object} opts
641
+ * @param {object|null} [opts.sessionManager] - Session manager for name lookup (optional)
642
+ * @param {string|null|undefined} [opts.boundSessionId] - The client's bound session id
643
+ * @param {string} [opts.message] - Human-readable error message
644
+ * @returns {{code: string, message: string, boundSessionId: string|null, boundSessionName: string|null}}
645
+ */
646
+ export function buildSessionTokenMismatchPayload({
647
+ sessionManager = null,
648
+ boundSessionId = null,
649
+ message = SESSION_TOKEN_MISMATCH_DEFAULT_MESSAGE,
650
+ } = {}) {
651
+ const normalisedBoundId = typeof boundSessionId === 'string' && boundSessionId ? boundSessionId : null
652
+ let boundSessionName = null
653
+ if (normalisedBoundId && sessionManager && typeof sessionManager.getSession === 'function') {
654
+ const entry = sessionManager.getSession(normalisedBoundId)
655
+ boundSessionName = (entry && typeof entry.name === 'string') ? entry.name : null
656
+ }
657
+ return {
658
+ code: 'SESSION_TOKEN_MISMATCH',
659
+ message,
660
+ boundSessionId: normalisedBoundId,
661
+ boundSessionName,
662
+ }
663
+ }