@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,163 @@
1
+ import { randomBytes } from 'crypto'
2
+
3
+ // #6277 — host-local per-spawn user-shell approval store.
4
+ //
5
+ // When `userShell.requireApproval` is on, a user-shell create is HELD here as a
6
+ // pending approval instead of spawning immediately. The host operator reads the
7
+ // one-time approval id from the daemon log and approves it out-of-band via the
8
+ // loopback-only `/api/shell/*` routes (or `chroxy shell approve <id>`); only then
9
+ // is the session actually created. This is the defense-in-depth control from
10
+ // `docs/security/bearer-token-authority.md §12`: a leaked primary token can no
11
+ // longer spawn an unmediated host shell over the tunnel without a host-side OK.
12
+ //
13
+ // Design (user-decided):
14
+ // - PER-SPAWN: every create needs its own approval; an approval is single-use
15
+ // and there is NO trust window.
16
+ // - SHORT TTL: a held approval expires (default 60s) so a stale id can't be
17
+ // redeemed later.
18
+ // - PURE STATE: this store holds no side effects — `approve()`/`deny()` just
19
+ // resolve the entry; the WS layer runs the deferred `createSession` + notify.
20
+ // That keeps it trivially unit-testable and keeps the create logic in one
21
+ // place (the same `finalizeShellCreate` the synchronous path uses).
22
+
23
+ /** Default time a held approval stays redeemable. */
24
+ export const DEFAULT_APPROVAL_TTL_MS = 60_000
25
+
26
+ /** Cap on simultaneously-pending approvals; oldest is evicted FIFO past this so
27
+ * a spammy client can't grow the map unbounded (mirrors MAX_ACTIVE_PAIRINGS). */
28
+ export const DEFAULT_MAX_PENDING = 32
29
+
30
+ /** Short, operator-typeable approval id (8 hex chars). Collisions within a
31
+ * handful of pending entries are astronomically unlikely; we retry anyway. */
32
+ function defaultGenerateId() {
33
+ return randomBytes(4).toString('hex')
34
+ }
35
+
36
+ export class ShellApprovalStore {
37
+ /**
38
+ * @param {object} [opts]
39
+ * @param {number} [opts.ttlMs] - approval lifetime (default 60s)
40
+ * @param {number} [opts.maxPending] - FIFO cap (default 32)
41
+ * @param {() => number} [opts.now] - clock (injectable for tests)
42
+ * @param {() => string} [opts.generateId] - id generator (injectable for tests)
43
+ */
44
+ constructor({ ttlMs = DEFAULT_APPROVAL_TTL_MS, maxPending = DEFAULT_MAX_PENDING, now = () => Date.now(), generateId = defaultGenerateId } = {}) {
45
+ this._ttlMs = ttlMs
46
+ this._maxPending = maxPending
47
+ this._now = now
48
+ this._generateId = generateId
49
+ // Insertion-ordered Map → the first key is the oldest (FIFO eviction).
50
+ this._pending = new Map()
51
+ }
52
+
53
+ get size() {
54
+ return this._pending.size
55
+ }
56
+
57
+ /**
58
+ * Hold a user-shell create as a pending approval. Returns the one-time
59
+ * `approvalId` (log this for the host operator) and `expiresAt`.
60
+ *
61
+ * `createSessionOptions` is the FULL options object destined for
62
+ * SessionManager.createSession — stored, NOT executed. createSession has
63
+ * side effects (worktree, event wiring) and must run exactly once, only after
64
+ * approval; running it here would duplicate the session.
65
+ *
66
+ * @param {object} req
67
+ * @param {string} req.clientId - the requesting WS client (to notify on approve)
68
+ * @param {object} req.createSessionOptions - replayed to createSession on approve
69
+ * @param {string} [req.tokenClass] - for the post-create audit record
70
+ * @param {string} [req.deviceName] - for the audit + `shell list`
71
+ * @param {string} [req.hint] - human-facing label surfaced to the client/log
72
+ * @returns {{ approvalId: string, expiresAt: number }}
73
+ */
74
+ createPendingApproval({ clientId, createSessionOptions, tokenClass = null, deviceName = null, hint = null } = {}) {
75
+ this._sweepExpired()
76
+ // FIFO-evict the oldest while at/over the cap (a fresh request shouldn't be
77
+ // refused; the oldest held approval is the most likely to be abandoned).
78
+ while (this._pending.size >= this._maxPending) {
79
+ const oldest = this._pending.keys().next().value
80
+ if (oldest === undefined) break
81
+ this._pending.delete(oldest)
82
+ }
83
+ const requestedAt = this._now()
84
+ const expiresAt = requestedAt + this._ttlMs
85
+ let approvalId = this._generateId()
86
+ // Defend against an id collision (or a deterministic test generator).
87
+ let guard = 0
88
+ while (this._pending.has(approvalId) && guard < 1000) {
89
+ approvalId = this._generateId()
90
+ guard += 1
91
+ }
92
+ this._pending.set(approvalId, {
93
+ approvalId,
94
+ clientId,
95
+ createSessionOptions,
96
+ tokenClass,
97
+ deviceName,
98
+ hint,
99
+ requestedAt,
100
+ expiresAt,
101
+ })
102
+ return { approvalId, expiresAt }
103
+ }
104
+
105
+ /**
106
+ * Resolve a pending approval. Single-use: a present, unexpired entry is
107
+ * removed and returned; a second call on the same id is `not_found`.
108
+ * @returns {{ ok: true, entry: object } | { ok: false, reason: 'not_found'|'expired' }}
109
+ */
110
+ approve(approvalId) {
111
+ return this._consume(approvalId)
112
+ }
113
+
114
+ /**
115
+ * Reject a pending approval (host operator declines the spawn). Same
116
+ * lookup/removal as approve; the caller notifies the requester.
117
+ * @returns {{ ok: true, entry: object } | { ok: false, reason: 'not_found'|'expired' }}
118
+ */
119
+ deny(approvalId) {
120
+ return this._consume(approvalId)
121
+ }
122
+
123
+ _consume(approvalId) {
124
+ if (typeof approvalId !== 'string' || approvalId.length === 0) {
125
+ return { ok: false, reason: 'not_found' }
126
+ }
127
+ const entry = this._pending.get(approvalId)
128
+ if (!entry) return { ok: false, reason: 'not_found' }
129
+ // Check expiry on the looked-up entry BEFORE any sweep so a just-expired id
130
+ // returns the specific `expired` reason rather than a generic `not_found`.
131
+ if (this._now() > entry.expiresAt) {
132
+ this._pending.delete(approvalId)
133
+ return { ok: false, reason: 'expired' }
134
+ }
135
+ this._pending.delete(approvalId) // single-use — no trust window
136
+ return { ok: true, entry }
137
+ }
138
+
139
+ /**
140
+ * Non-secret snapshot of currently-pending approvals for `chroxy shell list`.
141
+ * Deliberately omits createSessionOptions internals beyond the cwd.
142
+ * @returns {Array<{approvalId:string, clientId:string, cwd:string|null, deviceName:string|null, requestedAt:number, expiresAt:number}>}
143
+ */
144
+ list() {
145
+ this._sweepExpired()
146
+ return [...this._pending.values()].map((e) => ({
147
+ approvalId: e.approvalId,
148
+ clientId: e.clientId,
149
+ cwd: e.createSessionOptions?.cwd ?? null,
150
+ deviceName: e.deviceName,
151
+ requestedAt: e.requestedAt,
152
+ expiresAt: e.expiresAt,
153
+ }))
154
+ }
155
+
156
+ /** Drop entries past their TTL (lazy GC; runs on create + list). */
157
+ _sweepExpired() {
158
+ const now = this._now()
159
+ for (const [id, entry] of this._pending) {
160
+ if (now > entry.expiresAt) this._pending.delete(id)
161
+ }
162
+ }
163
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * shell-audit.js (#5985, epic #5982) — an audit trail for embedded user-shell
3
+ * sessions.
4
+ *
5
+ * A user-shell is a raw `$SHELL` PTY — arbitrary host code execution over the
6
+ * tunnel — so its lifecycle must be traceable: who opened a shell (token class
7
+ * + client), where (cwd), which shell, and how it ended. Entries are emitted as
8
+ * single greppable `[shell-audit]` log lines (filter the server log on that
9
+ * component) at create and destroy.
10
+ *
11
+ * This is the lifecycle audit required by #5985's acceptance criteria
12
+ * ("create/destroy audited, with the token class"). Per-keystroke command-input
13
+ * auditing is deliberately out of scope (volume + privacy); the create/destroy
14
+ * pair with the token class is the traceability anchor.
15
+ *
16
+ * Entries are emitted via the logger's always-on `audit()` path (#6001), so the
17
+ * trail survives a quiet `LOG_LEVEL` (warn/error) — a security record for a
18
+ * host-RCE capability must not vanish just because the operator turned down
19
+ * ordinary logging. Lines are tagged `[AUDIT] [shell-audit]`.
20
+ */
21
+ import { createLogger } from './logger.js'
22
+
23
+ const log = createLogger('shell-audit')
24
+
25
+ /**
26
+ * Build a stable, greppable `key=value` audit line. Pure (no I/O) so it can be
27
+ * asserted directly in tests. Null / undefined / empty-string fields are
28
+ * dropped; numbers render unquoted, everything else is JSON-quoted so a value
29
+ * containing spaces stays a single token.
30
+ *
31
+ * @param {string} event - e.g. 'user_shell_create' / 'user_shell_destroy'
32
+ * @param {Record<string, unknown>} fields
33
+ * @returns {string}
34
+ */
35
+ export function formatShellAuditLine(event, fields = {}) {
36
+ const parts = [`event=${event}`]
37
+ for (const [k, v] of Object.entries(fields)) {
38
+ if (v === undefined || v === null || v === '') continue
39
+ const rendered = typeof v === 'number' ? v : JSON.stringify(String(v))
40
+ parts.push(`${k}=${rendered}`)
41
+ }
42
+ return parts.join(' ')
43
+ }
44
+
45
+ /**
46
+ * Audit a user-shell session creation. `tokenClass` records the bearer-token
47
+ * class that authorized the spawn (always 'primary' today — the create gate
48
+ * rejects every other class, #5985b — but recorded explicitly so a future
49
+ * widening of the authz is captured in the trail).
50
+ */
51
+ export function auditShellCreate({ sessionId, clientId, tokenClass, cwd, shell, deviceName } = {}) {
52
+ log.audit(formatShellAuditLine('user_shell_create', { sessionId, clientId, tokenClass, cwd, shell, deviceName }))
53
+ }
54
+
55
+ /**
56
+ * Audit a user-shell session teardown. `exitCode` is the shell's natural exit
57
+ * code when it ended on its own before the session was destroyed; null when the
58
+ * session is destroyed while the shell is still live (it's then SIGTERM-killed
59
+ * asynchronously). `reason` is the shell's own exit reason or 'destroyed'.
60
+ */
61
+ export function auditShellDestroy({ sessionId, exitCode, reason } = {}) {
62
+ log.audit(formatShellAuditLine('user_shell_destroy', { sessionId, exitCode, reason }))
63
+ }
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Skills budget + allowlist enforcement helpers (#3223).
3
+ *
4
+ * Extracted from skills-loader.js. Two pruning concerns live here:
5
+ *
6
+ * - Total-byte budget (#3202): `_enforceTotalBudget`, `_priorityOf`,
7
+ * DEFAULT_SKILL_PRIORITY. Sorts by priority desc, name asc; walks
8
+ * the list accumulating bytes; drops skills past the cap.
9
+ * - Per-provider allowlist (#3207): `_filterByProviderAllowlist`.
10
+ * Operator-side gate that restricts which skills reach a given
11
+ * non-Claude provider; Claude-family providers stay permissive.
12
+ *
13
+ * Defaults exported alongside so the loader and (future) callers can
14
+ * size their inputs without re-deriving the constants.
15
+ */
16
+ import { createLogger } from './logger.js'
17
+ import { _normalizeProviderName, _isClaudeFamilyProvider } from './skills-frontmatter.js'
18
+ import { _pathLabel } from './skills-content-validator.js'
19
+
20
+ const log = createLogger('skills-loader')
21
+
22
+ // Per-skill byte cap and global skills budget (#3202). Tuned to keep skills
23
+ // from ballooning the system prompt — 32KB is roughly 8K tokens, 256KB is
24
+ // ~64K tokens, both well under any provider's context window but large
25
+ // enough that no honest skill should bump them.
26
+ export const DEFAULT_MAX_SKILL_BYTES = 32 * 1024
27
+ export const DEFAULT_MAX_TOTAL_SKILL_BYTES = 256 * 1024
28
+
29
+ // Default priority for skills without an explicit `priority:` in frontmatter
30
+ // (and for v1 skills that have no frontmatter at all). Per the #2958 schema,
31
+ // the documented default is 100. Returning 0 here (the previous behaviour)
32
+ // would push v1 / no-priority skills to the BOTTOM of the budget-prune order,
33
+ // so any new v2 skill with even `priority: 1` would outrank them — wrong for
34
+ // mixed v1/v2 sets.
35
+ export const DEFAULT_SKILL_PRIORITY = 100
36
+
37
+ /**
38
+ * Resolve a skill's effective priority. Reads `metadata.priority` when the
39
+ * frontmatter parser produced a numeric value; falls back to
40
+ * DEFAULT_SKILL_PRIORITY for v1 skills and v2 skills without the field.
41
+ */
42
+ export function _priorityOf(skill) {
43
+ if (skill && skill.metadata && Number.isFinite(skill.metadata.priority)) {
44
+ return skill.metadata.priority
45
+ }
46
+ return DEFAULT_SKILL_PRIORITY
47
+ }
48
+
49
+ /**
50
+ * Comparator for sorting skills by priority descending, then name ascending
51
+ * as a tiebreaker. Returns a negative number when `a` should come first.
52
+ *
53
+ * Used by both `_enforceTotalBudget` (post-merge prune order) and — going
54
+ * forward — the loader's pass-1 candidate sort (#3279 priority-aware
55
+ * pre-pass). Keeping both in sync here is intentional: the pass-1 ranking
56
+ * and the post-merge prune MUST use the same comparator, or a high-priority
57
+ * skill that survives pass-1 could be pruned ahead of a lower-priority one
58
+ * by the budget enforcer. NEVER change this function without also auditing
59
+ * every call site that relies on it for stable ordering.
60
+ *
61
+ * @param {{ name: string, metadata?: { priority?: number } | null }} a
62
+ * @param {{ name: string, metadata?: { priority?: number } | null }} b
63
+ * @returns {number}
64
+ */
65
+ // Load-bearing for _collectCandidates pass-1 sort (#3279) AND _enforceTotalBudget — must never drift.
66
+ export function _compareByPriorityThenName(a, b) {
67
+ const pa = _priorityOf(a)
68
+ const pb = _priorityOf(b)
69
+ if (pa !== pb) return pb - pa // higher priority first
70
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0
71
+ }
72
+
73
+ /**
74
+ * Apply the global skills budget (#3202). Skills are sorted by priority
75
+ * descending (higher priority kept first), with alphabetical name as the
76
+ * tiebreaker — same order enforced by `_compareByPriorityThenName`. We then walk
77
+ * the list, accumulating bytes until we'd exceed the cap; the first skill
78
+ * that wouldn't fit (and every later one) is dropped.
79
+ *
80
+ * Returns a fresh array sorted by name (for deterministic ordering downstream).
81
+ *
82
+ * @param {Array<object>} skills
83
+ * @param {number} maxTotalBytes
84
+ * @returns {Array<object>}
85
+ */
86
+ export function _enforceTotalBudget(skills, maxTotalBytes) {
87
+ if (!Array.isArray(skills) || skills.length === 0) return []
88
+
89
+ const ranked = skills.slice().sort(_compareByPriorityThenName)
90
+
91
+ const kept = []
92
+ let total = 0
93
+ for (const s of ranked) {
94
+ const size = typeof s.body === 'string' ? Buffer.byteLength(s.body, 'utf8') : 0
95
+ if (total + size > maxTotalBytes) {
96
+ log.warn(
97
+ `Skipping skill ${_pathLabel(s.name)}: cumulative size would exceed total cap ${maxTotalBytes}`,
98
+ )
99
+ continue
100
+ }
101
+ total += size
102
+ kept.push(s)
103
+ }
104
+
105
+ kept.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
106
+ return kept
107
+ }
108
+
109
+ /**
110
+ * Apply the per-provider skill allowlist (#3207).
111
+ *
112
+ * Semantics:
113
+ * - `allowlist` is null / undefined / not an object → no allowlist
114
+ * configured: legacy permissive behaviour, every skill passes through
115
+ * unchanged. This keeps existing setups working without forcing
116
+ * operators to opt every skill into a list before upgrading.
117
+ * - `provider` starts with `claude` (the family alias used by
118
+ * `_skillMatchesProvider`) → permissive. Claude has built-in tool
119
+ * gating so skills there are lower risk; the allowlist is meant to
120
+ * harden providers (Codex, Gemini, …) that don't enforce tool scopes
121
+ * the same way.
122
+ * - For any other (non-Claude) provider: only skills whose `name` is
123
+ * present in `allowlist[provider]` are kept. A missing key OR an
124
+ * empty array filters out ALL skills (fail-secure default — an
125
+ * operator who configures the allowlist but forgets to add an entry
126
+ * for `gemini` should NOT be silently permissive).
127
+ * - `provider` is null / unknown when an allowlist is configured →
128
+ * fail-secure: drop everything. The operator opted in to scoping;
129
+ * unknown contexts shouldn't bypass it.
130
+ *
131
+ * @param {Array<object>} skills
132
+ * @param {string|null} provider
133
+ * @param {Record<string, string[]>|null|undefined} allowlist
134
+ * @returns {Array<object>}
135
+ */
136
+ export function _filterByProviderAllowlist(skills, provider, allowlist) {
137
+ if (!Array.isArray(skills) || skills.length === 0) return skills
138
+ if (allowlist == null || typeof allowlist !== 'object' || Array.isArray(allowlist)) {
139
+ return skills // no allowlist configured → permissive (back-compat)
140
+ }
141
+
142
+ const norm = _normalizeProviderName(provider)
143
+ // Claude-family providers stay permissive even when an allowlist is
144
+ // configured. Membership covers the bare alias `claude`, the
145
+ // `claude-*` variants (`claude-sdk`, `claude-cli`), and the Docker
146
+ // wrappers (`docker`, `docker-cli`, `docker-sdk`) which inherit
147
+ // Claude's built-in tool gating. The shared
148
+ // `_isClaudeFamilyProvider` helper keeps the membership rule in one
149
+ // place so the trust / allowlist / family-alias paths can't drift.
150
+ if (_isClaudeFamilyProvider(norm)) return skills
151
+
152
+ // No provider id at all — fail-secure: the operator scoped the
153
+ // allowlist but we can't tell which bucket this session belongs to.
154
+ if (!norm) return []
155
+
156
+ // Look up the per-provider entry. Missing key OR empty array →
157
+ // fail-secure (drop everything for this provider). Anything other
158
+ // than an array of strings is treated as missing.
159
+ const raw = Object.prototype.hasOwnProperty.call(allowlist, norm) ? allowlist[norm] : undefined
160
+ if (!Array.isArray(raw) || raw.length === 0) {
161
+ if (skills.length > 0) {
162
+ log.warn(`Per-provider skill allowlist: no entry for provider '${norm}' — dropping all ${skills.length} skill(s)`)
163
+ }
164
+ return []
165
+ }
166
+
167
+ const allowedNames = new Set()
168
+ for (const v of raw) {
169
+ if (typeof v === 'string' && v) allowedNames.add(v)
170
+ }
171
+
172
+ const kept = []
173
+ for (const s of skills) {
174
+ if (s && typeof s.name === 'string' && allowedNames.has(s.name)) {
175
+ kept.push(s)
176
+ } else if (s && typeof s.name === 'string') {
177
+ log.warn(`Per-provider skill allowlist: skill '${s.name}' not in allowlist for provider '${norm}' — filtered`)
178
+ }
179
+ }
180
+ return kept
181
+ }
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Skills content + path validation helpers (#3223).
3
+ *
4
+ * Extracted from skills-loader.js so the loader can stay focused on
5
+ * discovery, IO, and the trust pipeline. The validation concerns live
6
+ * here:
7
+ *
8
+ * - DEFAULT_ALLOWED_EXTENSIONS, SKIP_DIRECTORY_NAMES — caller-side
9
+ * defaults the loader uses to gate which files / dirs to consider.
10
+ * - `_normalizeExtension` — coerces caller-supplied extension strings
11
+ * to the lowercase-without-dot form the allowlist Set uses.
12
+ * - `_bufferLooksLikeText` — full-content text sniff (#3203 + #3216)
13
+ * that rejects NUL + non-whitespace control chars.
14
+ * - `_pathLabel` — sanitised log label (#3215) — basename + 8-char
15
+ * SHA-256 prefix so cross-line correlation works without fanning
16
+ * filesystem layout out to paired clients.
17
+ *
18
+ * Pure helpers — no side effects, no Node-side state. Importing from
19
+ * here is cycle-free for the loader and the future split-out budget /
20
+ * frontmatter modules.
21
+ */
22
+ import { basename } from 'path'
23
+ import { createHash } from 'crypto'
24
+
25
+ // Default extensions accepted for skills. Just the suffix without the dot.
26
+ // `markdown` is included alongside `md` because some editors / users prefer
27
+ // the long form (#3219).
28
+ export const DEFAULT_ALLOWED_EXTENSIONS = ['md', 'markdown']
29
+
30
+ // Subdirectories we never recurse into. Keeps the loader from accidentally
31
+ // inhaling vendored trees, build outputs, or compiled caches if a user drops
32
+ // .chroxy/skills/ at a repo root that happens to contain them. (We only
33
+ // scan the top level today, but the skip list is also applied if the loader
34
+ // is asked to scan a directory tree explicitly.)
35
+ export const SKIP_DIRECTORY_NAMES = new Set([
36
+ '.git',
37
+ 'node_modules',
38
+ '__pycache__',
39
+ 'dist',
40
+ 'build',
41
+ ])
42
+
43
+ /**
44
+ * Return true if `s` is a string of `[a-z0-9]+` (i.e., a clean extension
45
+ * suffix without leading dot). Cheap input validation for the allowlist so a
46
+ * caller passing `'.md'` or `'MD'` doesn't silently break the comparison.
47
+ */
48
+ export function _normalizeExtension(ext) {
49
+ if (typeof ext !== 'string') return null
50
+ const trimmed = ext.trim().replace(/^\.+/, '').toLowerCase()
51
+ if (!trimmed) return null
52
+ if (!/^[a-z0-9]+$/.test(trimmed)) return null
53
+ return trimmed
54
+ }
55
+
56
+ /**
57
+ * Validate that `body` looks like printable text (#3203 + #3216). UTF-8
58
+ * multi-byte sequences are fine — we only reject NUL bytes and control
59
+ * characters outside the standard whitespace set (\t, \n, \v, \f, \r).
60
+ *
61
+ * The earlier implementation only sniffed the first 512 bytes, which let a
62
+ * file with a valid markdown head and a binary tail past that window load
63
+ * as a skill. We now walk every byte; cost is linear in file size, which is
64
+ * already bounded by `maxSkillBytes` upstream.
65
+ *
66
+ * @param {Buffer} buf - Full file contents (raw bytes, not decoded).
67
+ * @returns {boolean} true when every byte is acceptable, false on first violation.
68
+ */
69
+ export function _bufferLooksLikeText(buf) {
70
+ for (let i = 0; i < buf.length; i++) {
71
+ const byte = buf[i]
72
+ if (byte === 0) return false
73
+ // Allow standard ASCII whitespace control chars.
74
+ if (byte === 0x09 || byte === 0x0a || byte === 0x0b || byte === 0x0c || byte === 0x0d) continue
75
+ // Reject other control chars (0x00–0x1F, 0x7F). Bytes >= 0x80 are
76
+ // accepted: they're either valid UTF-8 continuation bytes for
77
+ // non-ASCII text, or genuinely binary content that we'd rather let
78
+ // pass than risk false-rejecting unicode markdown.
79
+ if (byte < 0x20 || byte === 0x7f) return false
80
+ }
81
+ return true
82
+ }
83
+
84
+ /**
85
+ * Build a sanitized label for a skill file path (#3215). The label includes
86
+ * the basename plus an 8-char SHA-256 prefix of the absolute path so server
87
+ * operators correlating across log lines still get a stable identifier,
88
+ * but a fan-out to a paired dashboard / mobile client (`log_entry`) does not
89
+ * reveal the user's filesystem layout.
90
+ *
91
+ * Example: `evil.md#a1b2c3d4`
92
+ *
93
+ * @param {string} absPath
94
+ * @returns {string}
95
+ */
96
+ export function _pathLabel(absPath) {
97
+ const safeBase = typeof absPath === 'string' ? basename(absPath) : '<unknown>'
98
+ let hashPrefix = '00000000'
99
+ try {
100
+ hashPrefix = createHash('sha256').update(String(absPath)).digest('hex').slice(0, 8)
101
+ } catch {
102
+ // Hash failures should never block skill loading — fall back to a fixed
103
+ // sentinel so the label still has a recognisable shape.
104
+ }
105
+ return `${safeBase}#${hashPrefix}`
106
+ }