@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,131 @@
1
+ /**
2
+ * Quick test client — connect to the server from your terminal.
3
+ * Usage: node src/test-client.js wss://your-cloudflare-url [--no-encrypt]
4
+ *
5
+ * This lets you validate the server works before building the mobile app.
6
+ */
7
+ import WebSocket from "ws";
8
+ import "dotenv/config";
9
+ import { createKeyPair, deriveSharedKey, deriveConnectionKey, generateConnectionSalt, encrypt, decrypt, DIRECTION_SERVER, DIRECTION_CLIENT } from "@chroxy/store-core/crypto";
10
+
11
+ const url = process.argv[2];
12
+ const token = process.env.API_TOKEN;
13
+ const noEncrypt = process.argv.includes("--no-encrypt");
14
+
15
+ if (!url) {
16
+ console.error("Usage: node src/test-client.js <wss://url> [--no-encrypt]");
17
+ process.exit(1);
18
+ }
19
+
20
+ const ws = new WebSocket(url);
21
+
22
+ /** E2E encryption state */
23
+ let encryptionState = null;
24
+ let pendingKeyPair = null;
25
+ let pendingSalt = null;
26
+
27
+ /** Send a message, encrypting if E2E is active */
28
+ function wsSend(payload) {
29
+ if (encryptionState) {
30
+ const envelope = encrypt(JSON.stringify(payload), encryptionState.sharedKey, encryptionState.sendNonce, DIRECTION_CLIENT);
31
+ encryptionState.sendNonce++;
32
+ ws.send(JSON.stringify(envelope));
33
+ } else {
34
+ ws.send(JSON.stringify(payload));
35
+ }
36
+ }
37
+
38
+ ws.on("open", () => {
39
+ console.log("[connected] Authenticating...");
40
+ ws.send(JSON.stringify({ type: "auth", token }));
41
+ });
42
+
43
+ ws.on("message", (raw) => {
44
+ let msg = JSON.parse(raw.toString());
45
+
46
+ // Decrypt incoming encrypted messages
47
+ if (msg.type === "encrypted" && encryptionState) {
48
+ try {
49
+ msg = decrypt(msg, encryptionState.sharedKey, encryptionState.recvNonce, DIRECTION_SERVER);
50
+ encryptionState.recvNonce++;
51
+ } catch (err) {
52
+ console.error("[crypto] Decryption failed:", err.message);
53
+ ws.close();
54
+ return;
55
+ }
56
+ }
57
+
58
+ switch (msg.type) {
59
+ case "auth_ok":
60
+ console.log(`[authenticated] server v${msg.serverVersion} protocol v${msg.protocolVersion}`, msg.encryption === "required" ? "E2E encryption required" : "No encryption");
61
+ if (msg.encryption === "required" && !noEncrypt) {
62
+ pendingKeyPair = createKeyPair();
63
+ pendingSalt = generateConnectionSalt();
64
+ // salt is REQUIRED by the server as of the 2026-04-11 audit fix —
65
+ // see packages/server/src/ws-auth.js and KEY_EXCHANGE_SALT_REQUIRED.
66
+ ws.send(JSON.stringify({ type: "key_exchange", publicKey: pendingKeyPair.publicKey, salt: pendingSalt }));
67
+ console.log("[crypto] Key exchange initiated...");
68
+ } else {
69
+ console.log("Switching to terminal mode. Type to interact.\n");
70
+ wsSend({ type: "mode", mode: "terminal" });
71
+ }
72
+ break;
73
+
74
+ case "key_exchange_ok":
75
+ if (pendingKeyPair) {
76
+ if (typeof msg.publicKey !== "string") {
77
+ console.error("[crypto] Invalid key_exchange_ok message: missing or non-string publicKey");
78
+ ws.close();
79
+ process.exit(1);
80
+ }
81
+ // Match the server: derive per-connection sub-key using the salt we
82
+ // generated for this connection. Without this, encrypt/decrypt on
83
+ // either end would use mismatched keys and fail.
84
+ const rawSharedKey = deriveSharedKey(msg.publicKey, pendingKeyPair.secretKey);
85
+ const sharedKey = deriveConnectionKey(rawSharedKey, pendingSalt);
86
+ encryptionState = { sharedKey, sendNonce: 0, recvNonce: 0 };
87
+ pendingKeyPair = null;
88
+ pendingSalt = null;
89
+ console.log("[crypto] E2E encryption established");
90
+ console.log("Switching to terminal mode. Type to interact.\n");
91
+ wsSend({ type: "mode", mode: "terminal" });
92
+ }
93
+ break;
94
+
95
+ case "auth_fail":
96
+ console.error("[auth failed]", msg.reason);
97
+ process.exit(1);
98
+ break;
99
+
100
+ case "raw":
101
+ // Write raw PTY output directly to stdout
102
+ process.stdout.write(msg.data);
103
+ break;
104
+
105
+ case "message":
106
+ // Show parsed chat messages with a prefix
107
+ console.log(`\n[${msg.type}:${msg.tool || "claude"}] ${msg.content}`);
108
+ break;
109
+
110
+ default:
111
+ // Show other messages for debugging
112
+ console.log(`[${msg.type}]`, JSON.stringify(msg).slice(0, 200));
113
+ }
114
+ });
115
+
116
+ // Forward stdin keystrokes to the PTY
117
+ process.stdin.setRawMode?.(true);
118
+ process.stdin.resume();
119
+ process.stdin.on("data", (data) => {
120
+ wsSend({ type: "input", data: data.toString() });
121
+ });
122
+
123
+ ws.on("close", () => {
124
+ console.log("\n[disconnected]");
125
+ process.exit(0);
126
+ });
127
+
128
+ ws.on("error", (err) => {
129
+ console.error("[error]", err.message);
130
+ process.exit(1);
131
+ });
@@ -0,0 +1,28 @@
1
+ import { timingSafeEqual } from 'crypto'
2
+
3
+ /**
4
+ * Constant-time string comparison for auth tokens.
5
+ * Prevents timing attacks by always comparing the full buffer length.
6
+ * Node.js-specific (uses native crypto.timingSafeEqual).
7
+ */
8
+ export function safeTokenCompare(a, b) {
9
+ let valid = true
10
+ if (typeof a !== 'string' || typeof b !== 'string') {
11
+ valid = false
12
+ a = ''
13
+ b = ''
14
+ }
15
+
16
+ const bufA = Buffer.from(a)
17
+ const bufB = Buffer.from(b)
18
+ const maxLen = Math.max(bufA.length, bufB.length)
19
+
20
+ // Always compare buffers of equal length to avoid leaking length via timing
21
+ const paddedA = Buffer.alloc(maxLen)
22
+ const paddedB = Buffer.alloc(maxLen)
23
+ bufA.copy(paddedA)
24
+ bufB.copy(paddedB)
25
+
26
+ const equal = maxLen === 0 ? false : timingSafeEqual(paddedA, paddedB)
27
+ return valid && equal && bufA.length === bufB.length
28
+ }
@@ -0,0 +1,220 @@
1
+ import { randomBytes } from 'crypto'
2
+ import { EventEmitter } from 'events'
3
+ import { safeTokenCompare } from './token-compare.js'
4
+ import { parseDuration } from './duration.js'
5
+ import { createLogger } from './logger.js'
6
+
7
+ const log = createLogger('token-manager')
8
+
9
+ /**
10
+ * Manages token lifecycle with optional rotation and expiry.
11
+ *
12
+ * When tokenExpiry is set, the manager:
13
+ * 1. Schedules a rotation before the current token expires
14
+ * 2. Generates a new token and emits 'token_rotated'
15
+ * 3. Keeps the old token valid for a grace period
16
+ * 4. Calls the persist callback to save the new token
17
+ *
18
+ * Events:
19
+ * token_rotated { oldToken, newToken, expiresAt, reason }
20
+ *
21
+ * `reason` distinguishes a scheduled/periodic rotation ('scheduled') from an
22
+ * operator revoke ('revoke', via `revoke()`). A revoke is the panic button:
23
+ * the old token is invalidated immediately (no grace window) and downstream
24
+ * (WsServer) severs privileged sessions and forces every connection to
25
+ * re-authenticate (#6006). A scheduled rotation re-keys gracefully — the old
26
+ * token stays valid through the grace period and live sessions survive.
27
+ */
28
+
29
+ // Default grace period: 5 minutes
30
+ const DEFAULT_GRACE_MS = 5 * 60 * 1000
31
+
32
+ // Rotate 10% before expiry (min 60s, max 10min before)
33
+ function rotationLeadTime(expiryMs) {
34
+ const lead = Math.max(60_000, Math.min(expiryMs * 0.1, 10 * 60 * 1000))
35
+ return lead
36
+ }
37
+
38
+ // Re-export so existing `import { parseDuration } from './token-manager.js'` keeps working
39
+ export { parseDuration }
40
+
41
+ export class TokenManager extends EventEmitter {
42
+ /**
43
+ * @param {Object} opts
44
+ * @param {string} opts.token - Current API token
45
+ * @param {string|null} opts.tokenExpiry - Expiry duration (e.g. '24h', '7d') or null
46
+ * @param {number} opts.graceMs - Grace period in ms (default: 5 min)
47
+ * @param {Function} opts.onPersist - Callback to save new token: async (newToken) => {}
48
+ */
49
+ constructor({ token, tokenExpiry, graceMs, onPersist } = {}) {
50
+ super()
51
+ this._currentToken = token
52
+ this._previousToken = null
53
+ this._graceMs = graceMs ?? DEFAULT_GRACE_MS
54
+ this._onPersist = onPersist || null
55
+ this._rotationTimer = null
56
+ this._graceTimer = null
57
+ this._expiryMs = parseDuration(tokenExpiry)
58
+ // Minimum expiry floor: 5 minutes (prevents excessive rotation spam)
59
+ const MIN_EXPIRY_MS = 5 * 60 * 1000
60
+ if (this._expiryMs != null && this._expiryMs < MIN_EXPIRY_MS) {
61
+ log.warn(`tokenExpiry ${tokenExpiry} (${this._expiryMs}ms) is below minimum ${MIN_EXPIRY_MS}ms — clamping to 5 minutes`)
62
+ this._expiryMs = MIN_EXPIRY_MS
63
+ }
64
+ this._expiresAt = null
65
+ }
66
+
67
+ /** The current valid token */
68
+ get currentToken() {
69
+ return this._currentToken
70
+ }
71
+
72
+ /** When the current token expires (ms epoch), or null */
73
+ get expiresAt() {
74
+ return this._expiresAt
75
+ }
76
+
77
+ /** Whether rotation is enabled */
78
+ get rotationEnabled() {
79
+ return this._expiryMs != null && this._expiryMs > 0
80
+ }
81
+
82
+ /**
83
+ * Validate a token. Returns true if the token matches the current
84
+ * token or the previous token (during grace period).
85
+ */
86
+ validate(token) {
87
+ if (!token) return false
88
+ if (safeTokenCompare(token, this._currentToken)) return true
89
+ if (this._previousToken && safeTokenCompare(token, this._previousToken)) return true
90
+ return false
91
+ }
92
+
93
+ /**
94
+ * #6004 — whether a token is the CURRENT token specifically (NOT the previous
95
+ * token honored during the grace window). Used to gate user-shell creation so
96
+ * a connection authed with a just-rotated (now grace-period) token can't
97
+ * create a NEW shell during the grace window. Constant-time.
98
+ */
99
+ isCurrentToken(token) {
100
+ if (!token) return false
101
+ return safeTokenCompare(token, this._currentToken)
102
+ }
103
+
104
+ /**
105
+ * Start the rotation schedule. Call after server startup.
106
+ * No-op if tokenExpiry is not configured.
107
+ */
108
+ start() {
109
+ if (!this.rotationEnabled) return
110
+ this._expiresAt = Date.now() + this._expiryMs
111
+ this._scheduleRotation()
112
+ log.info(`Token rotation enabled (every ${formatDuration(this._expiryMs)}, grace: ${formatDuration(this._graceMs)})`)
113
+ }
114
+
115
+ /**
116
+ * Immediately revoke the current token — the operator panic button (#6006).
117
+ *
118
+ * Unlike a scheduled rotation this (a) invalidates the old token at once,
119
+ * with NO grace window, so a leaked token can't ride out the (default 5min)
120
+ * grace, and (b) carries `reason: 'revoke'` so WsServer severs privileged
121
+ * (user-shell) sessions and forces every connection to re-authenticate with
122
+ * the new token rather than transparently re-keying. Returns the new token.
123
+ */
124
+ revoke() {
125
+ return this.rotate('revoke')
126
+ }
127
+
128
+ /**
129
+ * Perform an immediate rotation. `reason` defaults to 'scheduled' (the
130
+ * graceful periodic path used by the rotation timer); pass 'revoke' (via
131
+ * `revoke()`) for the panic-button behavior described above.
132
+ * Returns the new token.
133
+ */
134
+ rotate(reason = 'scheduled') {
135
+ const isRevoke = reason === 'revoke'
136
+ const oldToken = this._currentToken
137
+ const newToken = randomBytes(32).toString('base64url')
138
+
139
+ this._currentToken = newToken
140
+ this._expiresAt = this._expiryMs ? Date.now() + this._expiryMs : null
141
+
142
+ if (isRevoke) {
143
+ // Panic button: the old token is compromised. Kill it NOW — drop it as
144
+ // the previous-token and tear down any in-flight grace timer so
145
+ // validate() rejects it immediately.
146
+ this._previousToken = null
147
+ if (this._graceTimer) {
148
+ clearTimeout(this._graceTimer)
149
+ this._graceTimer = null
150
+ }
151
+ log.warn(`Token REVOKED (old token invalidated immediately, no grace)`)
152
+ } else {
153
+ this._previousToken = oldToken
154
+ log.info(`Token rotated`)
155
+ }
156
+
157
+ // Emit event for WsServer to broadcast to clients
158
+ this.emit('token_rotated', {
159
+ oldToken,
160
+ newToken,
161
+ expiresAt: this._expiresAt,
162
+ reason,
163
+ })
164
+
165
+ // Persist the new token
166
+ if (this._onPersist) {
167
+ Promise.resolve(this._onPersist(newToken)).catch(err => {
168
+ log.error(`Failed to persist new token: ${err.message}`)
169
+ })
170
+ }
171
+
172
+ // Start grace period for the old token — scheduled rotations only. A revoke
173
+ // killed the old token above and must not resurrect it via a grace window.
174
+ if (!isRevoke) {
175
+ if (this._graceTimer) clearTimeout(this._graceTimer)
176
+ this._graceTimer = setTimeout(() => {
177
+ this._graceTimer = null
178
+ this._previousToken = null
179
+ log.info(`Grace period expired, old token invalidated`)
180
+ }, this._graceMs)
181
+ }
182
+
183
+ // Schedule next rotation
184
+ if (this.rotationEnabled) {
185
+ this._scheduleRotation()
186
+ }
187
+
188
+ return newToken
189
+ }
190
+
191
+ /** Schedule the next automatic rotation */
192
+ _scheduleRotation() {
193
+ if (this._rotationTimer) clearTimeout(this._rotationTimer)
194
+ const delay = this._expiryMs - rotationLeadTime(this._expiryMs)
195
+ this._rotationTimer = setTimeout(() => {
196
+ this._rotationTimer = null
197
+ this.rotate()
198
+ }, Math.max(1000, delay))
199
+ }
200
+
201
+ /** Clean up timers */
202
+ destroy() {
203
+ if (this._rotationTimer) {
204
+ clearTimeout(this._rotationTimer)
205
+ this._rotationTimer = null
206
+ }
207
+ if (this._graceTimer) {
208
+ clearTimeout(this._graceTimer)
209
+ this._graceTimer = null
210
+ }
211
+ this.removeAllListeners()
212
+ }
213
+ }
214
+
215
+ function formatDuration(ms) {
216
+ if (ms >= 86400000) return `${Math.round(ms / 86400000)}d`
217
+ if (ms >= 3600000) return `${Math.round(ms / 3600000)}h`
218
+ if (ms >= 60000) return `${Math.round(ms / 60000)}m`
219
+ return `${Math.round(ms / 1000)}s`
220
+ }
@@ -0,0 +1,87 @@
1
+ // Max size for tool result text forwarded to mobile (10KB)
2
+ export const MAX_TOOL_RESULT_SIZE = 10240
3
+
4
+ // Max base64 size per image forwarded to mobile (500KB base64 ≈ 375KB decoded)
5
+ export const MAX_TOOL_IMAGE_SIZE = 512000
6
+
7
+ // Max number of images forwarded per tool result (prevents oversized WS frames on mobile)
8
+ export const MAX_TOOL_IMAGES_PER_RESULT = 5
9
+
10
+ // Allowed image media types
11
+ const ALLOWED_IMAGE_TYPES = new Set([
12
+ 'image/png',
13
+ 'image/jpeg',
14
+ 'image/gif',
15
+ 'image/webp',
16
+ ])
17
+
18
+ /**
19
+ * Extract tool_result events from a user-role message's content blocks.
20
+ * Used by both CliSession and SdkSession to avoid duplicating the parsing logic.
21
+ *
22
+ * Extracts both text and image content blocks. Images are forwarded as base64
23
+ * with media type metadata for inline display on the mobile client.
24
+ *
25
+ * @param {Array} content - The message.content array from a user-role event
26
+ * @param {EventEmitter} emitter - Session instance to emit tool_result events on
27
+ * @param {number} [maxSize] - Optional override for max text result size
28
+ */
29
+ export function emitToolResults(content, emitter, maxSize = MAX_TOOL_RESULT_SIZE) {
30
+ if (!Array.isArray(content)) return
31
+
32
+ for (const block of content) {
33
+ if (block.type !== 'tool_result' || !block.tool_use_id) continue
34
+
35
+ let result = ''
36
+ const images = []
37
+
38
+ if (typeof block.content === 'string') {
39
+ result = block.content
40
+ } else if (Array.isArray(block.content)) {
41
+ // Extract text blocks
42
+ result = block.content
43
+ .filter(b => b.type === 'text')
44
+ .map(b => b.text)
45
+ .join('\n')
46
+
47
+ // Extract image blocks
48
+ for (const b of block.content) {
49
+ if (b.type !== 'image' || !b.source) continue
50
+ const mediaType = b.source.media_type || b.source.mediaType
51
+ if (!mediaType || !ALLOWED_IMAGE_TYPES.has(mediaType)) continue
52
+ const data = b.source.data
53
+ if (!data || typeof data !== 'string') continue
54
+ // Skip images that exceed the size limit
55
+ if (data.length > MAX_TOOL_IMAGE_SIZE) continue
56
+ images.push({ mediaType, data })
57
+ // Cap total images per result
58
+ if (images.length >= MAX_TOOL_IMAGES_PER_RESULT) break
59
+ }
60
+ }
61
+
62
+ const truncated = result.length > maxSize
63
+ if (truncated) {
64
+ result = result.slice(0, maxSize)
65
+ }
66
+
67
+ const event = {
68
+ toolUseId: block.tool_use_id,
69
+ result,
70
+ truncated,
71
+ }
72
+
73
+ if (images.length > 0) {
74
+ event.images = images
75
+ }
76
+
77
+ emitter.emit('tool_result', event)
78
+ // #4628: drop the in-flight tracker entry so _emitResult's sweep
79
+ // (BaseSession) doesn't double-emit a synthetic for an already-
80
+ // resolved tool. Only the BaseSession-derived emitter exposes
81
+ // _trackToolResult; ignore for any other emitter shape (e.g. tests
82
+ // that pass a bare EventEmitter).
83
+ if (typeof emitter._trackToolResult === 'function') {
84
+ emitter._trackToolResult(block.tool_use_id)
85
+ }
86
+ }
87
+ }