@chroxy/server 0.11.10 → 0.11.11

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 (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
@@ -25,7 +25,7 @@
25
25
  // is fully testable against real temp repos without poking the real home dir.
26
26
 
27
27
  import { execFileSync } from 'node:child_process'
28
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
28
+ import { existsSync, lstatSync, readFileSync, readdirSync, statSync } from 'node:fs'
29
29
  import { isAbsolute, join as joinPath, resolve as resolvePath } from 'node:path'
30
30
  import { chroxyWorktreeRepoPath } from '@chroxy/protocol/project'
31
31
  import { GIT } from './git.js'
@@ -49,6 +49,17 @@ import { GIT } from './git.js'
49
49
  // agent-session lifetime); the clean-tree guard remains the hard safety net.
50
50
  const DEFAULT_MAX_LOCK_AGE_MS = 0
51
51
 
52
+ // The removal guard's own runner: a status listing can be large, and a hung git must
53
+ // read as "keep" (the throw lands in isClean's / the caller's catch), not stall the
54
+ // scheduler. Worktree GC keeps defaultGit (1 MB default buffer, no timeout).
55
+ function strictGit(cwd, args) {
56
+ return execFileSync(GIT, ['-C', cwd, ...args], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: 30_000 })
57
+ }
58
+
59
+ function defaultGit(cwd, args) {
60
+ return execFileSync(GIT, ['-C', cwd, ...args], { encoding: 'utf8' })
61
+ }
62
+
52
63
  /**
53
64
  * Existence check for a pid without sending a real signal.
54
65
  * Signal 0 only probes for the process; EPERM means it exists but we can't
@@ -237,6 +248,11 @@ export function planRepoGc(repoPath, deps = {}) {
237
248
  return { repo: repoPath, items }
238
249
  }
239
250
 
251
+ // `--ignored=matching` lists an ignored DIRECTORY once (a populated node_modules
252
+ // is one line, not thousands) while `--untracked-files=all` still enumerates
253
+ // every untracked file; any ignored entry at all still reads as not clean.
254
+ const STRICT_STATUS_ARGS = ['-c', 'status.showUntrackedFiles=all', '-c', 'diff.ignoreSubmodules=none', 'status', '--porcelain', '--ignored=matching', '--untracked-files=all', '--ignore-submodules=none']
255
+
240
256
  /**
241
257
  * `git -C <worktree> status --porcelain --ignored` → clean? null when it can't
242
258
  * be run. The `--ignored` flag is load-bearing (#5244): `git worktree remove`
@@ -246,9 +262,184 @@ export function planRepoGc(repoPath, deps = {}) {
246
262
  * un-versioned files. Treating any ignored entry (`!! ...`) as not-clean keeps
247
263
  * such worktrees in the skip set instead of silently deleting their contents.
248
264
  */
249
- function isClean(git, worktreePath) {
265
+ function isClean(git, worktreePath, { strict = false } = {}) {
250
266
  try {
251
- return git(worktreePath, ['status', '--porcelain', '--ignored']).trim().length === 0
267
+ // #9242 (strict): the removal guard must not depend on the user's or repo's git
268
+ // configuration. `status.showUntrackedFiles=no` hides untracked AND ignored
269
+ // entries, and `diff.ignoreSubmodules` hides a dirty submodule; each would read
270
+ // a worktree holding real work as clean. The GC callers keep their historical
271
+ // command (strict=false) unchanged.
272
+ const args = strict ? STRICT_STATUS_ARGS : ['status', '--porcelain', '--ignored']
273
+ return git(worktreePath, args).trim().length === 0
274
+ } catch {
275
+ return null
276
+ }
277
+ }
278
+
279
+
280
+ /**
281
+ * #9242: could removing this worktree lose work? True when its working tree is
282
+ * not clean (tracked edits, untracked files, and gitignored ones — see isClean),
283
+ * when HEAD holds a commit no branch, tag or remote ref reaches (a session
284
+ * worktree is DETACHED, so a commit made in it is reachable from nothing else and
285
+ * `git worktree remove` makes it unreachable), or when either question cannot be
286
+ * answered. Fails SAFE: unknown reads as "has work".
287
+ *
288
+ * Deliberately conservative, and accepted: in a SPARSE checkout every skip-worktree file
289
+ * carries the `S` tag, so such a session always reads as having work and is kept.
290
+ *
291
+ * @param {string} worktreePath
292
+ * @param {{ git?: (cwd: string, args: string[]) => string }} [deps]
293
+ * @returns {boolean}
294
+ */
295
+ export function worktreeHasUnsavedWork(worktreePath, deps = {}) {
296
+ return scanUnsavedWork(worktreePath, deps, true).has
297
+ }
298
+
299
+ /** Most sample paths reported per kind (#9286). */
300
+ const UNSAVED_SAMPLE_PER_KIND = 5
301
+
302
+ /**
303
+ * #9286: WHAT would be lost, not just whether anything would. Same checks, same
304
+ * order and same fail-safe as worktreeHasUnsavedWork (which is this scan stopped at
305
+ * the first finding), but every kind is collected so a person can see why a session
306
+ * was kept.
307
+ *
308
+ * kinds (each present once, in discovery order): `modified` (tracked edits),
309
+ * `untracked`, `ignored` (a `.env`, `node_modules`...), `hidden-index`
310
+ * (assume-unchanged / skip-worktree tracked files), `submodule` (a populated gitlink
311
+ * directory), `unreachable-commits` (HEAD holds a commit no ref reaches),
312
+ * `unreadable` (a question git or the filesystem could not answer: kept, fail safe).
313
+ * `samples` maps a kind to at most 5 paths (none for `unreachable-commits`/`unreadable`).
314
+ *
315
+ * @param {string} worktreePath
316
+ * @param {{ git?: Function, lstat?: Function, readdir?: Function }} [deps]
317
+ * @returns {{ has: boolean, kinds: string[], samples: Record<string, string[]> }}
318
+ */
319
+ export function worktreeUnsavedWorkReport(worktreePath, deps = {}) {
320
+ return scanUnsavedWork(worktreePath, deps, false)
321
+ }
322
+
323
+ function scanUnsavedWork(worktreePath, deps, firstOnly) {
324
+ const { git = strictGit, lstat = lstatSync, readdir = readdirSync } = deps
325
+ const kinds = []
326
+ const samples = {}
327
+ const found = (kind, path) => {
328
+ if (!kinds.includes(kind)) kinds.push(kind)
329
+ if (path === undefined) return
330
+ const list = (samples[kind] ||= [])
331
+ if (list.length < UNSAVED_SAMPLE_PER_KIND) list.push(path)
332
+ }
333
+ const done = () => ({ has: kinds.length > 0, kinds, samples })
334
+ // A directory that is already gone (ENOENT, and only ENOENT) holds nothing that
335
+ // removal could lose. Any other stat error (EACCES, EIO, an unmounted volume) is
336
+ // "cannot tell", which is "keep".
337
+ try {
338
+ lstat(worktreePath)
339
+ } catch (err) {
340
+ if (err?.code !== 'ENOENT') found('unreadable')
341
+ return done()
342
+ }
343
+ const status = readStatus(git, worktreePath)
344
+ if (status === null) {
345
+ found('unreadable')
346
+ return done()
347
+ }
348
+ if (status.trim().length > 0) {
349
+ for (const line of status.split('\n')) {
350
+ if (!line) continue
351
+ const code = line.slice(0, 2)
352
+ const kind = code === '??' ? 'untracked' : code === '!!' ? 'ignored' : 'modified'
353
+ found(kind, line.slice(3))
354
+ }
355
+ // An unparseable non-empty status is still unsaved work.
356
+ if (kinds.length === 0) found('modified')
357
+ if (firstOnly) return done()
358
+ }
359
+ try {
360
+ if (git(worktreePath, ['rev-list', '-n', '1', 'HEAD', '--not', '--branches', '--tags', '--remotes']).trim().length > 0) {
361
+ found('unreachable-commits')
362
+ if (firstOnly) return done()
363
+ }
364
+ // Work `status` cannot see. (1) A tracked file flagged assume-unchanged (lowercase
365
+ // tag; also what `core.ignoreStat` effectively does) or skip-worktree (`S`) can be
366
+ // edited without any status line. (2) A submodule's own status probe runs without
367
+ // `--ignored`, so a populated submodule can hold ignored files (a `.env`) while the
368
+ // parent reads clean. An UNINITIALISED submodule directory is not a submodule at all
369
+ // to git: a hand-made file in it is invisible to status. So ANY gitlink whose
370
+ // directory has any entry is kept, initialised or not. Both are the simple fail-safe
371
+ // (keep) rather than recursing into each submodule.
372
+ for (const rec of git(worktreePath, ['ls-files', '-v', '-z']).split('\0')) {
373
+ if (/^[a-zS] /.test(rec)) {
374
+ found('hidden-index', rec.slice(2))
375
+ if (firstOnly) return done()
376
+ }
377
+ }
378
+ for (const rec of git(worktreePath, ['ls-files', '-s', '-z']).split('\0')) {
379
+ const m = /^160000 [0-9a-f]+ \d\t(.+)$/s.exec(rec)
380
+ if (!m) continue
381
+ let entries
382
+ try {
383
+ entries = readdir(joinPath(worktreePath, m[1]))
384
+ } catch (err) {
385
+ if (err?.code === 'ENOENT') continue // the gitlink's directory is absent: nothing there
386
+ found('unreadable') // cannot tell (EACCES, ENOTDIR, ...): keep
387
+ if (firstOnly) return done()
388
+ continue
389
+ }
390
+ if (entries.length > 0) {
391
+ found('submodule', m[1])
392
+ if (firstOnly) return done()
393
+ }
394
+ }
395
+ } catch {
396
+ found('unreadable')
397
+ }
398
+ return done()
399
+ }
400
+
401
+ const UNSAVED_KIND_LABELS = {
402
+ modified: 'uncommitted changes to tracked files',
403
+ untracked: 'untracked files',
404
+ ignored: 'ignored files (build output, node_modules, a local .env...)',
405
+ 'hidden-index': 'tracked files hidden from status (assume-unchanged / skip-worktree)',
406
+ submodule: 'a populated submodule directory',
407
+ 'unreachable-commits': 'commits no branch, tag or remote reaches',
408
+ unreadable: 'state that could not be read (kept to be safe)',
409
+ }
410
+
411
+ // Control characters, bidi overrides/isolates and zero-width characters: text from git
412
+ // or the filesystem must not be able to reorder or hide what the notice shows.
413
+ // eslint-disable-next-line no-control-regex
414
+ const NOTICE_STRIP = /[\u0000-\u001f\u007f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g
415
+
416
+ /** Strip spoofing characters, then cap at `max` code points (never splitting a surrogate pair). */
417
+ export function sanitizeNoticeText(text, max) {
418
+ const chars = Array.from(String(text).replace(NOTICE_STRIP, ''))
419
+ return chars.length > max ? `${chars.slice(0, max - 3).join('')}...` : chars.join('')
420
+ }
421
+
422
+ /**
423
+ * #9286: one human-readable line for a worktreeUnsavedWorkReport(), kinds in the
424
+ * report's order, each with its sample paths. Paths come from git and the
425
+ * filesystem, so control characters are stripped and each is length-capped.
426
+ * @param {{ kinds: string[], samples: Record<string, string[]> }} report
427
+ * @returns {string}
428
+ */
429
+ export function describeUnsavedWork(report) {
430
+ const kinds = Array.isArray(report?.kinds) ? report.kinds : []
431
+ return kinds.map((kind) => {
432
+ const label = UNSAVED_KIND_LABELS[kind] || kind
433
+ const paths = (report.samples?.[kind] || []).map((p) => sanitizeNoticeText(p, 120))
434
+ return paths.length > 0 ? `${label}: ${paths.join(', ')}` : label
435
+ }).join('; ')
436
+ }
437
+
438
+ /** The strict status output (raw, untrimmed), or null when it cannot be run. */
439
+ function readStatus(git, worktreePath) {
440
+ try {
441
+ const out = git(worktreePath, STRICT_STATUS_ARGS)
442
+ return typeof out === 'string' ? out : null
252
443
  } catch {
253
444
  return null
254
445
  }
@@ -288,7 +479,7 @@ function isClean(git, worktreePath) {
288
479
  */
289
480
  export function sweepOrphanChroxyWorktrees({ worktreeBase, liveSessionIds, deps = {} } = {}) {
290
481
  const {
291
- git = (cwd, args) => execFileSync(GIT, ['-C', cwd, ...args], { encoding: 'utf8' }),
482
+ git = defaultGit,
292
483
  readdir = (p) => readdirSync(p, { withFileTypes: true }),
293
484
  exists = existsSync,
294
485
  } = deps
package/src/ws-auth.js CHANGED
@@ -7,6 +7,9 @@
7
7
  import { createKeyPair, deriveSharedKey, deriveConnectionKey, signExchangeKey } from '@chroxy/store-core/crypto'
8
8
  import { AuthSchema, KeyExchangeSchema, PairSchema, PairRequestSchema } from './ws-schemas.js'
9
9
  import { createLogger, loggableValue } from './logger.js'
10
+ import { sendRawTransport } from './principal-policy.js'
11
+ import { PRINCIPAL_BINDING_SENTINEL } from './principal-binding.js'
12
+ import { isLoopbackPeer } from './connection-locality.js'
10
13
  import { metrics } from './metrics.js'
11
14
 
12
15
  const log = createLogger('ws')
@@ -89,6 +92,64 @@ export function recordBenignPairAttempt(map, key, now) {
89
92
  return false
90
93
  }
91
94
 
95
+
96
+ /**
97
+ * Is this connection's upgrade a loopback peer with no proxy hint, at upgrade time AND
98
+ * now? `client.loopbackAtUpgrade` is the verdict taken when the socket was upgraded;
99
+ * the retained upgrade request is classified again here, so a hint that appears on the
100
+ * retained request later still refuses. Fail closed: no retained request, no loopback.
101
+ * @param {object} client
102
+ * @returns {boolean}
103
+ */
104
+ export function isLoopbackConnection(client) {
105
+ return client?.loopbackAtUpgrade === true && isLoopbackPeer(client._upgradeReq)
106
+ }
107
+
108
+ /**
109
+ * Resolve a presented token to a live agent principal, or null. The store compares the
110
+ * token's hash with every stored hash in constant time. A valid principal token
111
+ * presented from any peer that is not loopback is refused exactly like an invalid one:
112
+ * the caller cannot tell the cases apart. The token is never logged.
113
+ * @param {object} ctx
114
+ * @param {object} client
115
+ * @param {unknown} token
116
+ * @returns {object|null}
117
+ */
118
+ function resolvePrincipalCredential(ctx, client, token) {
119
+ const store = ctx.principalStore
120
+ if (!store || typeof token !== 'string') return null
121
+ // Loopback FIRST: a remote peer never reaches the store, so it cannot make the daemon
122
+ // read it (a 256 KB file) or log an invalid store on every attempt. The reply is the
123
+ // same opaque failure either way.
124
+ if (!isLoopbackConnection(client)) return null
125
+ return store.validate(token)
126
+ }
127
+
128
+ /**
129
+ * Stamp a principal connection (contract section 3.1 item 1-2) BEFORE it is marked
130
+ * authenticated or registered anywhere: `principal`, `isPrimaryToken = false` and the
131
+ * fixed binding sentinel, which every host gate that branches on `boundSessionId` then
132
+ * refuses. The sentinel is non-enumerable so a spread or a JSON dump of the record can
133
+ * never carry it onto the wire.
134
+ * @param {object} client
135
+ * @param {{ principalId: string, label: string, tier: string, scope: string, constraints: object, expiresAt: number }} principal
136
+ */
137
+ export function stampPrincipal(client, principal) {
138
+ client.principal = {
139
+ principalId: principal.principalId,
140
+ label: principal.label,
141
+ tier: principal.tier,
142
+ scope: principal.scope,
143
+ constraints: principal.constraints,
144
+ expiresAt: principal.expiresAt,
145
+ }
146
+ client.isPrimaryToken = false
147
+ client.pairingCredential = null
148
+ Object.defineProperty(client, 'boundSessionId', {
149
+ value: PRINCIPAL_BINDING_SENTINEL, enumerable: false, writable: true, configurable: true,
150
+ })
151
+ }
152
+
92
153
  /**
93
154
  * Handle an auth message from an unauthenticated client.
94
155
  * Returns true if the message was consumed (caller should return).
@@ -138,7 +199,17 @@ export function handleAuthMessage(ctx, ws, msg) {
138
199
  return true
139
200
  }
140
201
 
141
- if (!authRequired || isTokenValid(msg.token)) {
202
+ // An agent principal is recognised ONLY here, ONLY when the token is not one of the
203
+ // existing classes, and ONLY from a loopback peer. Resolved before anything else so the
204
+ // success path stamps it before any state is touched.
205
+ const tokenIsKnown = !authRequired || isTokenValid(msg.token)
206
+ const principal = tokenIsKnown ? null : resolvePrincipalCredential(ctx, client, msg.token)
207
+
208
+ if (tokenIsKnown || principal !== null) {
209
+ // Stamp a principal before it is marked authenticated, before any registration and
210
+ // before any other assignment below can default it to a host-level connection.
211
+ if (principal !== null) stampPrincipal(client, principal)
212
+
142
213
  // Refuse an unsupported protocol version BEFORE the connection is marked
143
214
  // authenticated, so a connection that is being closed never carries an
144
215
  // authenticated-but-unscoped state.
@@ -151,8 +222,9 @@ export function handleAuthMessage(ctx, ws, msg) {
151
222
  return true
152
223
  }
153
224
 
154
- // Scope and authenticate together (scope first), before anything else runs.
155
- if (!applySessionScope(client, pairingManager, msg.token)) {
225
+ // Scope and authenticate together (scope first), before anything else runs. A
226
+ // principal's binding is the sentinel stamped above; no pairing scope applies.
227
+ if (principal === null && !applySessionScope(client, pairingManager, msg.token)) {
156
228
  log.warn(`Auth refused for ${rateLimitKey}: token's session binding cannot be applied`)
157
229
  send(ws, { type: 'auth_fail', reason: 'session_unavailable' })
158
230
  ws.close()
@@ -166,14 +238,21 @@ export function handleAuthMessage(ctx, ws, msg) {
166
238
  // connection lifetime — the client already holds the E2E shared key, so
167
239
  // this is comparable exposure. Undefined in --no-auth (no token), where the
168
240
  // shell gate's current-token check is skipped (no TokenManager).
169
- client.authToken = msg.token
170
- authFailures.delete(rateLimitKey)
241
+ // A principal token is never retained on the connection record.
242
+ client.authToken = principal === null ? msg.token : undefined
243
+ // A principal's loopback key is the same bucket local primary-token guessers fail into:
244
+ // its success must not reset their backoff.
245
+ if (principal === null) authFailures.delete(rateLimitKey)
171
246
 
172
247
  client.protocolVersion = clientVersion !== null
173
248
  ? Math.min(clientVersion, serverProtocolVersion)
174
249
  : minProtocolVersion
175
250
 
176
- if (msg.deviceInfo && typeof msg.deviceInfo === 'object') {
251
+ if (principal !== null) {
252
+ // The operator-authored label, never the connection's own claim: the principal's
253
+ // self-description is attacker-influenceable text that humans would read.
254
+ client.deviceInfo = { deviceId: null, deviceName: principal.label, deviceType: 'unknown', platform: 'agent' }
255
+ } else if (msg.deviceInfo && typeof msg.deviceInfo === 'object') {
177
256
  client.deviceInfo = {
178
257
  deviceId: typeof msg.deviceInfo.deviceId === 'string' ? msg.deviceInfo.deviceId : null,
179
258
  deviceName: typeof msg.deviceInfo.deviceName === 'string' ? msg.deviceInfo.deviceName : null,
@@ -197,12 +276,17 @@ export function handleAuthMessage(ctx, ws, msg) {
197
276
  // `!authRequired` short-circuit. The `pair`-message path never sets this, so
198
277
  // paired clients default to undefined (non-primary) — gates use strict
199
278
  // `=== true`. Consumed by the user-shell create + terminal_* gates.
200
- const isPairingCredential = authRequired && !!pairingManager?.isSessionTokenValid(msg.token)
201
- client.isPrimaryToken = !isPairingCredential
202
- // Remember which stored credential this connection holds, so the connection
203
- // ends when that credential is removed (revoked, expired, evicted). The
204
- // primary token has its own lifecycle (rotation / revoke) and records none.
205
- client.pairingCredential = isPairingCredential ? msg.token : null
279
+ //
280
+ // A principal is NEVER the primary class and holds no pairing credential: its stamps
281
+ // (above) are final, so neither line below may touch them.
282
+ if (principal === null) {
283
+ const isPairingCredential = authRequired && !!pairingManager?.isSessionTokenValid(msg.token)
284
+ client.isPrimaryToken = !isPairingCredential
285
+ // Remember which stored credential this connection holds, so the connection
286
+ // ends when that credential is removed (revoked, expired, evicted). The
287
+ // primary token has its own lifecycle (rotation / revoke) and records none.
288
+ client.pairingCredential = isPairingCredential ? msg.token : null
289
+ }
206
290
 
207
291
  client.clientCapabilities = new Set(authData.capabilities ?? [])
208
292
 
@@ -595,12 +679,12 @@ export function handleKeyExchange(ctx, ws, msg) {
595
679
  if (typeof msg.publicKey === 'string' && !msg.salt) {
596
680
  log.warn(`key_exchange from ${client.id} missing required 'salt' field; client likely predates 600612649 (chroxy >= v0.6.8). Rejecting to avoid nonce reuse on reconnect.`)
597
681
  try {
598
- ws.send(JSON.stringify({
682
+ sendRawTransport(ws, client, {
599
683
  type: 'error',
600
684
  code: 'KEY_EXCHANGE_SALT_REQUIRED',
601
685
  message: 'key_exchange requires a client-supplied salt. Please upgrade your Chroxy client to v0.6.8 or later.',
602
686
  details: 'key_exchange requires a client-supplied salt for per-connection key derivation. Older clients that omit salt would fall back to the raw DH shared key with nonce=0 on reconnect, re-introducing a nonce-reuse vulnerability. Upgrade the client to a build that includes commit 600612649 (Chroxy v0.6.8 or later).',
603
- }))
687
+ })
604
688
  } catch (err) {
605
689
  log.error(`Failed to send salt-required error: ${err.message}`)
606
690
  }
@@ -613,12 +697,12 @@ export function handleKeyExchange(ctx, ws, msg) {
613
697
  const details = keParsed.error.issues.map(i => i.message).join(', ')
614
698
  log.warn(`Invalid key_exchange message from ${client.id}: ${details}`)
615
699
  try {
616
- ws.send(JSON.stringify({
700
+ sendRawTransport(ws, client, {
617
701
  type: 'error',
618
702
  code: 'INVALID_MESSAGE',
619
703
  message: 'Invalid key_exchange message.',
620
704
  details,
621
- }))
705
+ })
622
706
  } catch (err) {
623
707
  log.error(`Failed to send key_exchange error: ${err.message}`)
624
708
  }
@@ -647,7 +731,7 @@ export function handleKeyExchange(ctx, ws, msg) {
647
731
  }
648
732
  }
649
733
  try {
650
- ws.send(JSON.stringify({
734
+ sendRawTransport(ws, client, {
651
735
  type: 'key_exchange_ok',
652
736
  publicKey: serverKp.publicKey,
653
737
  ...(serverKeySig ? { serverKeySig } : {}),
@@ -658,7 +742,7 @@ export function handleKeyExchange(ctx, ws, msg) {
658
742
  ...(serverKeySig && serverIdentity?.rotationCert
659
743
  ? { newIdentityKey: serverIdentity.publicKey, rotationCert: serverIdentity.rotationCert }
660
744
  : {}),
661
- }))
745
+ })
662
746
  } catch (err) {
663
747
  // #5702 (8b): the client never received the exchange key, so we must NOT
664
748
  // mark E2E established or flush the post-auth queue. `encryptionState` was
@@ -686,7 +770,7 @@ export function handleKeyExchange(ctx, ws, msg) {
686
770
  client.encryptionPending = false
687
771
  client.postAuthQueue = null
688
772
  try {
689
- ws.send(JSON.stringify({ type: 'server_error', message: 'Encryption required but client did not initiate key exchange.', recoverable: false }))
773
+ sendRawTransport(ws, client, { type: 'server_error', message: 'Encryption required but client did not initiate key exchange.', recoverable: false })
690
774
  } catch (_) {}
691
775
  ws.close(1008, 'Key exchange required')
692
776
  return true
@@ -2,6 +2,7 @@ import { createLogger } from './logger.js'
2
2
  import { metrics } from './metrics.js'
3
3
  import { isSessionViewer } from './handler-utils.js'
4
4
  import { isBoundToOtherSession, canSeePeer } from './environments/authority.js'
5
+ import { isPrincipalClient, frameForPrincipalBroadcast } from './principal-policy.js'
5
6
 
6
7
  const log = createLogger('ws')
7
8
 
@@ -21,6 +22,12 @@ const log = createLogger('ws')
21
22
  * @param {object} opts
22
23
  * @param {Map} opts.clients ws → client Map (shared reference with WsServer)
23
24
  * @param {function} opts.sendFn (ws, message) => void — handles encryption, seq, etc.
25
+ * @param {function} [opts.journalTap] (message) => void — fed every outgoing session-tagged broadcast ONCE, before
26
+ * delivery and whoever the recipients are, so the agent-principal event journal
27
+ * (principal-journal.js) records what happened independent of who watches. Must
28
+ * not throw; a throw is swallowed so it can never break a broadcast.
29
+ * @param {function} [opts.principalOpts] () => PrincipalPolicyOpts — session lookups for an agent principal's
30
+ * delivery decision (principal-policy.js); optional, defaults to no lookups
24
31
  * @param {object} [opts.clientManager] WsClientManager owning the sessionId→clients reverse
25
32
  * index (#5563). When present, session-scoped broadcasts
26
33
  * and subscriber counts iterate the index Set instead of
@@ -31,8 +38,10 @@ const log = createLogger('ws')
31
38
  * @param {number} [opts.backpressureMaxDrops] close connection after this many consecutive drops
32
39
  */
33
40
  export class WsBroadcaster {
34
- constructor({ clients, clientManager, sendFn, backpressureThreshold, backpressureMaxDrops } = {}) {
41
+ constructor({ clients, clientManager, sendFn, principalOpts, journalTap, backpressureThreshold, backpressureMaxDrops } = {}) {
35
42
  this._clients = clients
43
+ this._journalTap = typeof journalTap === 'function' ? journalTap : null
44
+ this._principalOpts = typeof principalOpts === 'function' ? principalOpts : () => ({})
36
45
  this._clientManager = clientManager ?? null
37
46
  this._sendFn = sendFn
38
47
  this._backpressureThreshold = backpressureThreshold ?? 1024 * 1024
@@ -44,6 +53,12 @@ export class WsBroadcaster {
44
53
  this._assertIndexIntegrity = process.env.CHROXY_WS_INDEX_ASSERT === '1'
45
54
  }
46
55
 
56
+ /** Hand one outgoing message to the journal tap, once. Never throws. */
57
+ _tapJournal(message) {
58
+ if (this._journalTap === null) return
59
+ try { this._journalTap(message) } catch (err) { log.warn(`Journal tap failed: ${err?.message || err}`) }
60
+ }
61
+
47
62
  /** Public broadcast: send a message to all authenticated clients */
48
63
  broadcast(message) {
49
64
  log.info(`Broadcasting ${message.type || 'unknown'} to all clients`)
@@ -97,7 +112,18 @@ export class WsBroadcaster {
97
112
  // Checked here, the single delivery point every broadcast path ends in, so
98
113
  // an unfiltered `_broadcast` and both `_broadcastToSession` paths agree.
99
114
  // Frames without a string `sessionId` are not session-scoped and pass.
100
- if (typeof message?.sessionId === 'string' && isBoundToOtherSession(client, message.sessionId)) {
115
+ //
116
+ // An agent principal is decided FIRST: it carries a sentinel binding, so the
117
+ // drop below would discard every frame it may legitimately receive. It gets
118
+ // `frameForPrincipal` (deny by default, session frames only inside the grant)
119
+ // and never reaches the bound drop. This is the BROADCAST path: it applies
120
+ // `frameForPrincipalBroadcast` (empty in S2, so a principal receives no ordinary
121
+ // broadcast of any type), never the direct-reply allowlist of `_send`.
122
+ if (isPrincipalClient(client)) {
123
+ const frame = frameForPrincipalBroadcast(client, message, this._principalOpts())
124
+ if (frame === null) return false
125
+ message = frame
126
+ } else if (typeof message?.sessionId === 'string' && isBoundToOtherSession(client, message.sessionId)) {
101
127
  return false
102
128
  }
103
129
  if (ws.bufferedAmount > this._backpressureThreshold) {
@@ -129,7 +155,8 @@ export class WsBroadcaster {
129
155
  * continue. (No shipping filter throws today — the #4799 fix hardened the
130
156
  * default — but this is the resilient invariant the fast path already has.)
131
157
  */
132
- _broadcast(message, filter = () => true) {
158
+ _broadcast(message, filter = () => true, skipJournal = false) {
159
+ if (!skipJournal) this._tapJournal(message)
133
160
  for (const [ws, client] of this._clients) {
134
161
  if (!client.authenticated || ws.readyState !== 1) continue
135
162
  let matched
@@ -161,8 +188,11 @@ export class WsBroadcaster {
161
188
  */
162
189
  _matchesSession(client, sessionId) {
163
190
  // A client bound to another session is never a recipient, whatever its
164
- // active/subscribed sets say (same rule as the delivery point above).
165
- if (isBoundToOtherSession(client, sessionId)) return false
191
+ // active/subscribed sets say (same rule as the delivery point above). An
192
+ // agent principal is the exception that is decided first: its sentinel binding
193
+ // must not exclude it here, and `frameForPrincipal` at the delivery point
194
+ // withholds every frame outside its grant.
195
+ if (!isPrincipalClient(client) && isBoundToOtherSession(client, sessionId)) return false
166
196
  return isSessionViewer(client, sessionId)
167
197
  }
168
198
 
@@ -178,7 +208,7 @@ export class WsBroadcaster {
178
208
  if (!this._clientManager) return
179
209
  for (const client of this._clientManager.getSessionSubscribers(sessionId)) {
180
210
  if (!client.authenticated) continue
181
- if (isBoundToOtherSession(client, sessionId)) continue
211
+ if (!isPrincipalClient(client) && isBoundToOtherSession(client, sessionId)) continue
182
212
  const sock = client._ws
183
213
  if (!sock || sock.readyState !== 1) continue
184
214
  yield { client, sock }
@@ -203,6 +233,7 @@ export class WsBroadcaster {
203
233
  */
204
234
  _broadcastToSession(sessionId, message, filter) {
205
235
  const tagged = { ...message, sessionId }
236
+ this._tapJournal(tagged)
206
237
 
207
238
  if (this._assertIndexIntegrity && this._clientManager) {
208
239
  // Throws on drift, naming the offending session/client — surfaces the
@@ -242,7 +273,8 @@ export class WsBroadcaster {
242
273
  }
243
274
  return false
244
275
  })
245
- this._broadcast(tagged, effectiveFilter)
276
+ // already journaled above: the generic path must not record it a second time
277
+ this._broadcast(tagged, effectiveFilter, true)
246
278
  }
247
279
 
248
280
  /**
@@ -226,6 +226,10 @@ export class WsClientManager extends EventEmitter {
226
226
  */
227
227
  subscribe(client, sessionId) {
228
228
  if (!sessionId) return
229
+ // S2 (agent principals): this refusal also keeps a principal OFF the subscription index (it carries a
230
+ // sentinel binding, so every session is 'another session'). That is deliberate and fail-closed;
231
+ // S3 keeps it on purpose: the principal journal is delivered by its own per-subscription direct send
232
+ // (principal-subscriptions.js), not through this index. tests/principal-dispatch-wiring.test.js pins it.
229
233
  // A session-bound client is never subscribed (nor indexed) on a session
230
234
  // other than its binding, so the reverse index cannot stream one to it.
231
235
  if (isBoundToOtherSession(client, sessionId)) {
@@ -261,6 +265,10 @@ export class WsClientManager extends EventEmitter {
261
265
  * @param {string|null} sessionId
262
266
  */
263
267
  setActiveSession(client, sessionId) {
268
+ // S2 (agent principals): this refusal also keeps a principal OFF the subscription index (it carries a
269
+ // sentinel binding, so every session is 'another session'). That is deliberate and fail-closed;
270
+ // S3 keeps it on purpose: the principal journal is delivered by its own per-subscription direct send
271
+ // (principal-subscriptions.js), not through this index. tests/principal-dispatch-wiring.test.js pins it.
264
272
  // A session-bound client's active session is its binding or null (cleared
265
273
  // when the bound session is gone); any other session is ignored.
266
274
  if (sessionId && isBoundToOtherSession(client, sessionId)) {
@@ -18,6 +18,11 @@ const log = createLogger('ws')
18
18
  // #8972 — max distinct check_git_repo probes in flight per socket.
19
19
  const MAX_GIT_CHECKS_PER_CLIENT = 4
20
20
 
21
+ // #8998 — bound on the WHOLE check_git_repo probe (realpath + stat + git spawn).
22
+ // A hung network mount can stall realpath/stat forever; without this the probe
23
+ // never settles and its per-socket slot is never freed.
24
+ const GIT_PROBE_TIMEOUT_MS = 5000
25
+
21
26
  // #8012 — the message list_directory / browse_files send when `realpath()`
22
27
  // failed with one of these codes for a path INSIDE their boundary. Any other
23
28
  // code, or any path outside it, gets the handler's generic denial instead
@@ -145,12 +150,20 @@ function isBrowsable(realPath, homeReal, opts = {}) {
145
150
  * @param {Function} sendFn - (ws, message) => void
146
151
  * @param {Function} resolveSessionCwd - shared CWD resolver
147
152
  * @param {Function} validatePathWithinCwd - shared path validator
148
- * @param {{ realpath?: Function, readdir?: Function }} [deps] test seam for the catalog directory scans
153
+ * @param {{ realpath?: Function, readdir?: Function, gitProbeRealpath?: Function, gitProbeTimeoutMs?: number|(() => number) }} [deps]
154
+ * test seam: realpath/readdir for the catalog directory scans; gitProbeRealpath/gitProbeTimeoutMs
155
+ * for the check_git_repo probe only (#8998); gitProbeTimeoutMs may be a getter so a test can change
156
+ * the bound between probes (test-only, production uses the constant)
149
157
  * @returns {Object} browser operation methods
150
158
  */
151
159
  export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCwd, deps = {}) {
152
160
  const catalogRealpath = deps.realpath ?? realpath
153
161
  const catalogReaddir = deps.readdir ?? readdir
162
+ const gitProbeRealpath = deps.gitProbeRealpath ?? realpath
163
+ const gitProbeTimeoutMs = () => {
164
+ const t = deps.gitProbeTimeoutMs ?? GIT_PROBE_TIMEOUT_MS
165
+ return typeof t === 'function' ? t() : t
166
+ }
154
167
 
155
168
  /** List directories at a given path, sending a directory_listing response */
156
169
  async function listDirectory(ws, requestedPath, opts = {}) {
@@ -840,6 +853,8 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
840
853
  * Spawn budget: identical in-flight paths from one socket share one probe,
841
854
  * and a socket may have at most MAX_GIT_CHECKS_PER_CLIENT distinct probes in
842
855
  * flight; beyond that the reply is `null` without touching the filesystem.
856
+ * The whole probe (realpath, stat and the git spawn) is bounded at
857
+ * GIT_PROBE_TIMEOUT_MS: past it the reply is `null` and the slot is freed.
843
858
  */
844
859
  const inFlightChecks = new WeakMap() // ws -> Map<trimmed path, Promise<boolean|null>>
845
860
 
@@ -849,11 +864,11 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
849
864
  sendFn(ws, msg)
850
865
  }
851
866
 
852
- async function probeGitRepo(trimmed, opts) {
867
+ async function probeGitRepoUnbounded(trimmed, opts) {
853
868
  try {
854
869
  const home = homedir()
855
870
  // Same form New Session validates (kernel-resolved `..`), see kernelForm.
856
- const [realAbs, homeReal] = await Promise.all([realpath(kernelForm(trimmed, home)), realpath(home)])
871
+ const [realAbs, homeReal] = await Promise.all([gitProbeRealpath(kernelForm(trimmed, home)), gitProbeRealpath(home)])
857
872
  if (!isBrowsable(realAbs, homeReal, opts)) return null
858
873
  if (!(await stat(realAbs)).isDirectory()) return null
859
874
  return await isGitRepo(realAbs)
@@ -862,6 +877,23 @@ export function createBrowserOps(sendFn, resolveSessionCwd, validatePathWithinCw
862
877
  }
863
878
  }
864
879
 
880
+ // #8998 — race the whole probe against a timer that answers null. The timer
881
+ // is cleared when the work wins; the abandoned work never rejects (it catches
882
+ // internally), so a late result is simply dropped. git's own spawn timeout is
883
+ // also 5 s and starts later, so a slow git now answers null ("cannot tell")
884
+ // rather than false; that is intended, null leaves the worktree switch enabled.
885
+ async function probeGitRepo(trimmed, opts) {
886
+ let timer
887
+ const bound = new Promise((resolveBound) => {
888
+ timer = setTimeout(() => resolveBound(null), gitProbeTimeoutMs())
889
+ })
890
+ try {
891
+ return await Promise.race([probeGitRepoUnbounded(trimmed, opts), bound])
892
+ } finally {
893
+ clearTimeout(timer)
894
+ }
895
+ }
896
+
865
897
  /** Refuse without any path resolution or filesystem access (bound clients). */
866
898
  function refuseGitRepoCheck(ws, requestedPath, requestId) {
867
899
  replyGitRepoCheck(ws, requestedPath, requestId, null)