@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
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Per-client subscriptions to the principal event journal: replay, live fence, held
3
+ * live buffer (docs/security/agent-principals.md section 7.2; #9118).
4
+ *
5
+ * DELIVERY PATH. A subscription is delivered by a DEDICATED DIRECT SEND per subscription
6
+ * (this module calls the server's `send` for the one socket), not through the broadcaster:
7
+ * - fence, hold and release order are inherently per-subscription state, which a
8
+ * broadcast fan-out cannot carry;
9
+ * - the broadcast path would need the principal on the ClientManager index
10
+ * (`subscribe`, `setActiveSession`, `autoSubscribeOtherClients`), which would make it a
11
+ * recipient of every ordinary session broadcast's recipient set. Contract section 3.1
12
+ * item 7 says a principal receives NO ordinary session broadcast, so S2 pinned that
13
+ * index closed and `PRINCIPAL_BROADCAST_ALLOWED` stays EMPTY here. Nothing about the
14
+ * index changes in S3;
15
+ * - every frame still goes through `_send` -> `frameForPrincipal`, which re-checks the
16
+ * grant for the frame's session on every send and rebuilds the frame from the
17
+ * whitelist of `PRINCIPAL_OUTGOING_ALLOWED`, so a grant revoked mid-subscription
18
+ * withholds the next frame, and deny-by-default holds for these types as for any other.
19
+ *
20
+ * ORDER, per session: principal_subscribed (all sessions, once) -> replayed events
21
+ * (`replay: true`) from the cursor up to `headSeq` as it was at subscribe time ->
22
+ * `principal_live_fence { journalSeq: headSeq }` -> the live events that arrived while replaying,
23
+ * held and released in seq order -> live events as they happen.
24
+ *
25
+ * Replay runs in batches with a yield between them, so live traffic really does arrive
26
+ * mid-replay. The held buffer is capped (500 events or 1 MiB); on overflow the
27
+ * subscription ENDS with a `principal_gap { ended: true }` and the client subscribes again
28
+ * from its last cursor. A slow socket (past the backpressure threshold) ends it the same
29
+ * way instead of buffering without bound. An event evicted from the journal between
30
+ * `headSeq` and the fence is reported as a gap by the same read that finds it missing.
31
+ */
32
+ import { createLogger } from './logger.js'
33
+
34
+ const log = createLogger('principal-subscriptions')
35
+
36
+ export const REPLAY_BATCH = 50
37
+ export const HELD_MAX_EVENTS = 500
38
+ export const HELD_MAX_BYTES = 1024 * 1024
39
+ export const DRAIN_WAIT_MS = 20
40
+ export const DRAIN_MAX_WAITS = 250
41
+
42
+ const defaultYield = () => new Promise((resolve) => setImmediate(resolve))
43
+ const defaultSleep = (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.() })
44
+
45
+ export class PrincipalSubscriptions {
46
+ /**
47
+ * @param {object} opts
48
+ * @param {import('./principal-journal.js').PrincipalJournal} opts.journal
49
+ * @param {(ws: object, frame: object) => unknown} opts.send the server's `_send`
50
+ * @param {(client: object, sessionId: string) => boolean} [opts.maySee] the grant, re-checked per batch
51
+ * @param {number} [opts.backpressureBytes]
52
+ * @param {number} [opts.replayBatch]
53
+ * @param {number} [opts.heldMaxEvents]
54
+ * @param {number} [opts.heldMaxBytes]
55
+ * @param {() => Promise<void>} [opts.yieldFn] awaited between replay batches
56
+ * @param {(ms: number) => Promise<void>} [opts.sleepFn]
57
+ */
58
+ constructor({
59
+ journal, send, maySee = () => true, backpressureBytes = 1024 * 1024, replayBatch = REPLAY_BATCH,
60
+ heldMaxEvents = HELD_MAX_EVENTS, heldMaxBytes = HELD_MAX_BYTES, yieldFn = defaultYield, sleepFn = defaultSleep,
61
+ }) {
62
+ this._journal = journal
63
+ this._send = send
64
+ this._maySee = maySee
65
+ this._backpressureBytes = backpressureBytes
66
+ this._replayBatch = replayBatch
67
+ this._heldMaxEvents = heldMaxEvents
68
+ this._heldMaxBytes = heldMaxBytes
69
+ /** The await between replay batches. A test seam: a hook here runs mid-replay. */
70
+ this.yieldFn = yieldFn
71
+ this._sleep = sleepFn
72
+ /** @type {Map<object, Map<string, object>>} client -> sessionId -> subscription */
73
+ this._byClient = new Map()
74
+ }
75
+
76
+ /** How many live subscriptions exist (any state but ended). */
77
+ get size() {
78
+ let n = 0
79
+ for (const subs of this._byClient.values()) n += subs.size
80
+ return n
81
+ }
82
+
83
+ /**
84
+ * Subscribe `client` (on `ws`) to each session. Every id has ALREADY been checked
85
+ * against the grant by the caller (all-or-nothing); a re-subscribe replaces the earlier
86
+ * subscription for that session silently.
87
+ * @param {{ ws: object, client: object, requestId: string, sessions: { sessionId: string, cursor?: object|null }[] }} req
88
+ */
89
+ subscribe({ ws, client, requestId, sessions }) {
90
+ const subs = []
91
+ const infos = []
92
+ for (const { sessionId, cursor } of sessions) {
93
+ this._drop(client, sessionId, false)
94
+ const res = this._journal.resolveCursor(sessionId, cursor ?? null)
95
+ const sub = {
96
+ ws, client, requestId, sessionId, journalId: res.journalId, state: 'replay',
97
+ after: res.afterSeq, snapshotHead: res.headSeq, held: [], heldBytes: 0, unlisten: null,
98
+ }
99
+ sub.unlisten = this._journal.onAppend(sessionId, (evt) => this._onJournal(sub, evt))
100
+ this._register(sub)
101
+ subs.push(sub)
102
+ infos.push({
103
+ sessionId, journalId: res.journalId, headSeq: res.headSeq,
104
+ ...(res.gap ? { gap: res.gap } : {}),
105
+ })
106
+ }
107
+ this._send(ws, { type: 'principal_subscribed', requestId, sessions: infos })
108
+ for (const sub of subs) {
109
+ this._pump(sub).catch((err) => {
110
+ log.warn(`principal replay failed: ${err?.message || err}`)
111
+ this._end(sub, 'backpressure')
112
+ })
113
+ }
114
+ }
115
+
116
+ /** Stop a client's subscriptions (all of them, or the listed sessions). No frame is sent. */
117
+ unsubscribe(client, sessionIds = null) {
118
+ const subs = this._byClient.get(client)
119
+ if (!subs) return
120
+ for (const id of [...subs.keys()]) {
121
+ if (sessionIds === null || sessionIds.includes(id)) this._drop(client, id, false)
122
+ }
123
+ }
124
+
125
+ /** The client is gone (disconnect, revoke, expiry). */
126
+ removeClient(client) {
127
+ this.unsubscribe(client, null)
128
+ }
129
+
130
+ _register(sub) {
131
+ let subs = this._byClient.get(sub.client)
132
+ if (!subs) {
133
+ subs = new Map()
134
+ this._byClient.set(sub.client, subs)
135
+ }
136
+ subs.set(sub.sessionId, sub)
137
+ }
138
+
139
+ /** Forget one subscription. `sendEnd` is false for a silent stop. */
140
+ _drop(client, sessionId, _sendEnd) {
141
+ const subs = this._byClient.get(client)
142
+ const sub = subs?.get(sessionId)
143
+ if (!sub) return
144
+ sub.state = 'ended'
145
+ sub.held = []
146
+ sub.heldBytes = 0
147
+ try { sub.unlisten?.() } catch { /* ignore */ }
148
+ subs.delete(sessionId)
149
+ if (subs.size === 0) this._byClient.delete(client)
150
+ }
151
+
152
+ /** End a subscription and tell the client why (it must subscribe again). */
153
+ _end(sub, reason, range = {}) {
154
+ if (sub.state === 'ended') return
155
+ const { ws, client, sessionId } = sub
156
+ const frame = {
157
+ type: 'principal_gap', requestId: sub.requestId, sessionId, journalId: sub.journalId, reason, ended: true,
158
+ ...(range.fromSeq !== undefined ? { fromSeq: range.fromSeq } : {}),
159
+ ...(range.toSeq !== undefined ? { toSeq: range.toSeq } : {}),
160
+ }
161
+ this._drop(client, sessionId, false)
162
+ try { this._send(ws, frame) } catch { /* the socket is going away */ }
163
+ }
164
+
165
+ _sendGap(sub, gap) {
166
+ this._send(sub.ws, {
167
+ type: 'principal_gap', requestId: sub.requestId, sessionId: sub.sessionId, journalId: sub.journalId,
168
+ reason: gap.reason,
169
+ ...(gap.fromSeq !== undefined ? { fromSeq: gap.fromSeq } : {}),
170
+ ...(gap.toSeq !== undefined ? { toSeq: gap.toSeq } : {}),
171
+ ended: false,
172
+ })
173
+ }
174
+
175
+ _backedUp(sub) {
176
+ return (sub.ws?.bufferedAmount ?? 0) > this._backpressureBytes
177
+ }
178
+
179
+ /** A journal event for `sub`: held while replaying, sent when live. */
180
+ _onJournal(sub, evt) {
181
+ if (sub.state === 'ended') return
182
+ if (evt.kind === 'reset') {
183
+ this._end(sub, evt.reason)
184
+ return
185
+ }
186
+ if (evt.kind === 'removed') {
187
+ this._end(sub, 'removed')
188
+ return
189
+ }
190
+ // A new journal id is a new journal: this subscription's id and cursor mean nothing to it.
191
+ if (evt.journalId !== sub.journalId) {
192
+ this._end(sub, 'restart_loss')
193
+ return
194
+ }
195
+ if (sub.state === 'replay') {
196
+ sub.held.push(evt.entry)
197
+ sub.heldBytes += Buffer.byteLength(JSON.stringify(evt.entry), 'utf8')
198
+ if (sub.held.length > this._heldMaxEvents || sub.heldBytes > this._heldMaxBytes) {
199
+ this._end(sub, 'held_overflow', { fromSeq: sub.after + 1 })
200
+ }
201
+ return
202
+ }
203
+ this._sendLive(sub, evt.entry)
204
+ }
205
+
206
+ /** Put one journal entry on the wire (an object literal, so the frame roster scanner sees the type). */
207
+ _emitEvent(sub, entry, replay) {
208
+ this._send(sub.ws, {
209
+ type: 'principal_event',
210
+ requestId: sub.requestId,
211
+ sessionId: sub.sessionId,
212
+ journalId: sub.journalId,
213
+ // `journalSeq`, not `seq`: the transport stamps its own `seq` on every frame
214
+ journalSeq: entry.seq,
215
+ ts: entry.ts,
216
+ eventType: entry.type,
217
+ data: entry.data,
218
+ ...(entry.truncated === true ? { truncated: true } : {}),
219
+ ...(replay ? { replay: true } : {}),
220
+ })
221
+ }
222
+
223
+ _sendLive(sub, entry) {
224
+ if (sub.state === 'ended') return
225
+ if (!this._maySee(sub.client, sub.sessionId)) {
226
+ this._end(sub, 'scope')
227
+ return
228
+ }
229
+ if (this._backedUp(sub)) {
230
+ this._end(sub, 'backpressure')
231
+ return
232
+ }
233
+ this._emitEvent(sub, entry, false)
234
+ }
235
+
236
+ async _pump(sub) {
237
+ while (sub.state === 'replay') {
238
+ if (!this._maySee(sub.client, sub.sessionId)) {
239
+ this._end(sub, 'scope')
240
+ return
241
+ }
242
+ const read = this._journal.readFrom(sub.sessionId, sub.after, this._replayBatch, sub.snapshotHead)
243
+ if (read.journalId !== sub.journalId) {
244
+ this._end(sub, 'restart_loss') // never leave a replay hung on a journal that is gone
245
+ return
246
+ }
247
+ if (read.gap) this._sendGap(sub, read.gap)
248
+ for (const entry of read.events) this._emitEvent(sub, entry, true)
249
+ const progressed = read.lastSeq > sub.after
250
+ sub.after = read.lastSeq
251
+ if (sub.after >= sub.snapshotHead) break
252
+ if (!progressed) {
253
+ // Nothing to serve and no reason given: report what cannot be served, then fence.
254
+ this._sendGap(sub, { reason: 'evicted', fromSeq: sub.after + 1, toSeq: sub.snapshotHead })
255
+ break
256
+ }
257
+ await this.yieldFn()
258
+ if (sub.state !== 'replay') return
259
+ for (let waits = 0; this._backedUp(sub); waits++) {
260
+ if (waits >= DRAIN_MAX_WAITS) {
261
+ this._end(sub, 'backpressure')
262
+ return
263
+ }
264
+ await this._sleep(DRAIN_WAIT_MS)
265
+ if (sub.state !== 'replay') return
266
+ }
267
+ }
268
+ if (sub.state !== 'replay') return
269
+ this._send(sub.ws, {
270
+ type: 'principal_live_fence', requestId: sub.requestId, sessionId: sub.sessionId,
271
+ journalId: sub.journalId, journalSeq: sub.snapshotHead,
272
+ })
273
+ sub.state = 'live'
274
+ const held = sub.held
275
+ sub.held = []
276
+ sub.heldBytes = 0
277
+ for (const entry of held) {
278
+ if (sub.state !== 'live') return
279
+ // Everything held arrived after `snapshotHead`; nothing at or below it is repeated.
280
+ if (entry.seq > sub.snapshotHead) this._sendLive(sub, entry)
281
+ }
282
+ }
283
+ }
package/src/providers.js CHANGED
@@ -22,6 +22,7 @@ import { ClaudeByokSession } from './byok-session.js'
22
22
  import { DeepSeekSession } from './deepseek-session.js'
23
23
  import { OllamaSession } from './ollama-session.js'
24
24
  import { GeminiSession } from './gemini-session.js'
25
+ import { GeminiByokSession } from './gemini-byok-session.js'
25
26
  import { CodexSession } from './codex-session.js'
26
27
  import { CodexAppServerSession } from './codex-app-server-session.js'
27
28
  import { UserShellSession } from './user-shell-session.js'
@@ -67,6 +68,7 @@ const PROVIDERS = {
67
68
  // whatever the user has pulled locally. See ollama-session.js.
68
69
  'ollama': OllamaSession,
69
70
  'gemini': GeminiSession,
71
+ 'gemini-byok': GeminiByokSession,
70
72
  'codex': CodexSession,
71
73
  // #6605/#6616 — codex via the app-server JSON-RPC protocol (persistent) instead
72
74
  // of one-shot `codex exec`. Hidden (not a user-selectable provider): it's the
package/src/redaction.js CHANGED
@@ -15,17 +15,113 @@
15
15
  * - `SENSITIVE_KEY_NAMES` — the key-NAME set used by the broadcast sanitizer.
16
16
  */
17
17
 
18
+ // Why every loop below has a bound on its ITERATIONS. V8's regular-expression engine pushes one
19
+ // backtrack-stack entry for each iteration of a loop whose body can be of variable length (a group
20
+ // such as `(?:\\.[^"]*)`), and the stack is finite: a value of 3.5 million escapes (`"` followed
21
+ // by backslashes) made an unbounded `(?:\\.[^"]*)*` throw `RangeError: Maximum call stack size
22
+ // exceeded` out of `String.prototype.replace`. A run of one character class (`[^"\\\r\n]*`) pushes
23
+ // one entry for the whole run, whatever its length, so the RUNS stay unbounded and only the number
24
+ // of ITERATIONS is capped: ESC_MAX escapes after the first unit of a quoted value (so ESC_MAX + 1
25
+ // when that first unit is itself an escape, ESC_MAX when it is a plain character),
26
+ // PEM_DASH_ITER_MAX single dashes in one PEM body. At most that many entries are ever live, and a
27
+ // value of any length within the cap is redacted whole. redactValue and the logger's pass catch a
28
+ // throw anyway and mask everything (fail closed), but that is the second line: these bounds are
29
+ // the first.
30
+ const ESC_MAX = 65536
31
+ const PEM_DASH_ITER_MAX = 4096
32
+
33
+ // PEM private-key block (#9396): `-----BEGIN [label ]PRIVATE KEY-----`, a body, and the
34
+ // `-----END …-----` line, which is optional so a truncated block is redacted too. Real
35
+ // newlines and the JSON-escaped `\n` form both match. The body is any run of characters up to a
36
+ // real marker, `-----END ` or `-----BEGIN ` of any label (a certificate that follows ends it too);
37
+ // base64, the legacy `Proc-Type:` / `DEK-Info:` headers and an armor `Comment: a ----- b` line hold
38
+ // dashes and do not end it. A six-dash run before END gives its first dash to the body and
39
+ // ends at the second.
40
+ // The BEGIN marker counts unless a QUOTE follows it directly: `'`, `"` or a backtick (`\x60`). A marker
41
+ // quoted in code or docs (`k.includes('-----BEGIN PRIVATE KEY-----')`, a Markdown span, a grep
42
+ // argument) ends in a quote and is left alone with the text after it. Everything else after the marker
43
+ // matches, so no separator can leak a body: a real or escaped newline of any kind (`\n`, `\r\n`,
44
+ // `\u000a`, doubly escaped), a tab, a space (a key flattened onto one line), or the end of the input.
45
+ // That direction fails closed, on purpose: a whitelist of separators would leak on the one nobody
46
+ // listed. The over-redaction it accepts: a doubly escaped code literal (the marker followed by `\"`)
47
+ // is redacted to the next marker or the end of the input. A marker with nothing after it is replaced
48
+ // on its own, with an empty body: the marker is not a secret, and a body that followed it was
49
+ // discarded with the tail at a scan-window cut. The lookahead is one character.
50
+ // Accepted limit: a literal `-----END ` or `-----BEGIN ` inside an armor header line ends the body
51
+ // there, and the key body after it is then not redacted. A well-formed block never has one.
52
+ // A body with more than PEM_DASH_ITER_MAX dashes outside a marker (no real key has one) is
53
+ // redacted to the end of the input, never partly: the group after the loop takes the rest.
54
+ // Linear: the label run is at most 40 characters, so a start costs a constant; the body is an
55
+ // unrolled loop whose two branches begin with different characters (`[^-]` and `-(?!marker)`, a
56
+ // lookahead of at most nine characters), so there is one way to read it, and it cannot fail, so it
57
+ // is never re-read; a later start lies beyond the marker that ended it, or inside the rest that
58
+ // the swallow group took.
59
+ const PEM_MARKER = String.raw`----(?:END|BEGIN) `
60
+ const PEM_PRIVATE_KEY_SOURCE =
61
+ String.raw`-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----(?!['"\x60])[^-]*(?:-(?!${PEM_MARKER})[^-]*){0,${PEM_DASH_ITER_MAX}}(?:-(?!${PEM_MARKER})[\s\S]*)?(?:-----END [A-Z0-9 ]{0,40}PRIVATE KEY(?: BLOCK)?-----)?`
62
+
63
+ /**
64
+ * The source of one quoted form of the value alternative. `plain` is one character the body takes
65
+ * without ceremony (it excludes the delimiter, the backslash and a line break), `esc` is an
66
+ * escape unit, `close` the closing delimiter.
67
+ *
68
+ * open (plain|esc) plain* ( (esc plain*){0,ESC_MAX} (close|\\?$) | (esc plain*){ESC_MAX} \\[^\r\n]* )
69
+ *
70
+ * First branch: the value ends at its closing delimiter, or at the end of the input, where a lone
71
+ * backslash (which `esc` cannot take: it needs a second character) goes with it. Second branch:
72
+ * a value with more escapes than the first branch takes (ESC_MAX + 1 when its first unit is an
73
+ * escape, ESC_MAX otherwise) is redacted to the end of its line, which is fail-closed: the rest
74
+ * of the line goes with it, closing quote included.
75
+ */
76
+ const quotedForm = (open, plain, esc, close) =>
77
+ String.raw`${open}(?:${plain}|${esc})${plain}*(?:(?:${esc}${plain}*){0,${ESC_MAX}}(?:${close}|\\?$)|(?:${esc}${plain}*){${ESC_MAX}}\\[^\r\n]*)`
78
+
18
79
  // Sensitive patterns to redact from strings.
80
+ //
81
+ // The key-name pattern below redacts the value after a secret-sounding key name. The key may be
82
+ // QUOTED (a JSON property: `{"token":"…"}`, or the same JSON inside a string, where each quote
83
+ // is escaped), and so may the value (#6630, #8416). A quoted value is redacted up to its closing
84
+ // quote, whatever its length and whatever it holds (#9396: a JSON service-account `private_key`
85
+ // is about 1700 characters), as long as it stays on one line: a line break ends the value.
86
+ //
87
+ // There is no bound on the LENGTH of a value, and none is needed for speed. Each form's body
88
+ // excludes its own delimiter (`"`, `'`, or the backslash of `\"`), and every start of that form
89
+ // carries that delimiter right before the body, so a scan that does not find its closing quote
90
+ // stops at the next start, or at a line break, or at the end of the input, and no later start lies
91
+ // inside it; a start's failed scan backtracks over at most ESC_MAX iterations (and over plain
92
+ // runs, one position each), and the scans of the starts of one form never overlap. The body is
93
+ // written as an unrolled loop (`plain* (escape plain*)*`) whose branches begin with different
94
+ // characters: one way to read it, no re-reading. Its iterations are what the stack counts (see
95
+ // ESC_MAX above). tests/redaction-bounded-time.test.js times the hostile shapes.
96
+ //
97
+ // A value that reaches the END OF THE INPUT with no closing quote is redacted to the end (`$`
98
+ // without the `m` flag), and so is one whose last character is a lone backslash (`\\?$`: an
99
+ // escape pair needs a second character, and the cut can fall right after the backslash).
100
+ // That is fail-safe, and it is what keeps the scan-window cut safe
101
+ // (REDACT_SCAN_MARGIN): the cut can land inside a quoted value that holds a space, and the
102
+ // fragment left in front of the cut is then redacted whole, however long it is. A value cut by
103
+ // a line break instead of the end of the input is not redacted past the break (the single-line
104
+ // rule); it falls through to the unquoted form, which needs 8 token characters.
105
+ //
106
+ // A PEM private-key block right after the key (`private_key: -----BEGIN …`, real newlines) is
107
+ // matched here as well, in front of the unquoted form, which would otherwise take only
108
+ // `-----BEGIN`, and the standalone PEM pattern could no longer find a start.
19
109
  const SENSITIVE_PATTERNS = [
20
110
  // Bearer tokens in headers
21
111
  /Bearer\s+[A-Za-z0-9_\-./+=]{8,}/gi,
22
- // API tokens (base64url, UUID, hex) after common key names
23
- // The key may be QUOTED (a JSON property: `{"token":"…"}`, or the same JSON inside
24
- // a string, where each quote is escaped), and so may the value (#6630, #8416). A
25
- // quoted value is redacted up to its closing quote, whatever it holds; it is bounded
26
- // (1024 characters, no line break) so the scan stays linear in the input. A value with
27
- // no closing quote falls through to the unquoted form, which needs 8 token characters.
28
- /(?:token|password|secret|apiKey|api_key|authorization|credential|private_key)(?:\\?["'])?\s*[:=]\s*(?:"(?:[^"\\\r\n]|\\.){1,1024}"|'(?:[^'\\\r\n]|\\.){1,1024}'|\\"(?:[^\\\r\n]|\\(?!")){1,1024}\\"|(?:\\?["'])?[A-Za-z0-9_\-./+=]{8,}(?:\\?["'])?)/gi,
112
+ // API tokens (base64url, UUID, hex) after common key names and the explicit
113
+ // AWS secret environment assignment (#8416). The new alias has a word
114
+ // boundary so a longer identifier ending in that name is not newly matched.
115
+ new RegExp(
116
+ String.raw`(?:token|password|secret|apiKey|api_key|authorization|credential|private_key|aws_secret_access_key|x-api-key)(?:\\?["'])?\s*[:=]\s*(?:` +
117
+ quotedForm('"', String.raw`[^"\\\r\n]`, String.raw`\\.`, '"') +
118
+ '|' + quotedForm(String.raw`\$'`, String.raw`[^'\\\r\n]`, String.raw`\\.`, "'") +
119
+ '|' + quotedForm("'", String.raw`[^'\\\r\n]`, String.raw`\\.`, "'") +
120
+ '|' + quotedForm(String.raw`\\"`, String.raw`[^\\\r\n]`, String.raw`\\(?!")`, String.raw`\\"`) +
121
+ String.raw`|(?:\\?["'])?` + PEM_PRIVATE_KEY_SOURCE +
122
+ String.raw`|(?:\\?["'])?[A-Za-z0-9_\-./+=]{8,}(?:\\?["'])?)`,
123
+ 'gi',
124
+ ),
29
125
  ]
30
126
 
31
127
  // JWT shape: `eyJ` + base64url, a dot, base64url, a dot, base64url, each segment at
@@ -123,16 +219,21 @@ const JWT_PATTERN = {
123
219
  const API_KEY_PATTERNS = [
124
220
  // Anthropic: sk-ant-api03-... (checked before generic sk- so the longer
125
221
  // prefix wins). Real keys are well over 40 trailing chars.
126
- /\bsk-ant-(?:api\d{2}-)?[A-Za-z0-9_-]{40,}/g,
222
+ /sk-ant-(?:api\d{2}-)?[A-Za-z0-9_-]{40,}/g,
127
223
  // OpenAI project-scoped keys: sk-proj-... (typically 40+ chars after prefix)
128
- /\bsk-proj-[A-Za-z0-9_-]{40,}/g,
224
+ /sk-proj-[A-Za-z0-9_-]{40,}/g,
129
225
  // OpenAI legacy secret keys: sk- followed by 40+ chars. Must not match
130
226
  // sk-ant- / sk-proj- (already handled above) — negative lookahead keeps
131
227
  // them from being partially redacted.
132
- /\bsk-(?!ant-|proj-)[A-Za-z0-9]{40,}/g,
228
+ /sk-(?!ant-|proj-)[A-Za-z0-9]{40,}/g,
229
+ // Recognised credential prefixes carry no leading \b (#8416): a token right after a
230
+ // word character or a literal `\n` is still a credential; the length floors keep short identifiers
231
+ // readable. A word ending in `sk-` (`task-`, `disk-`, `risk-`) followed by 40+ alphanumerics IS masked,
232
+ // on purpose: conservative, and edited-input refuses an edit of such text (fail-closed).
133
233
  // Google API keys: AIza + exactly 35 chars of [A-Za-z0-9_-].
134
- // Trailing \b prevents matching into longer alphanumerics (e.g., AIzawa…).
135
- /\bAIza[A-Za-z0-9_-]{35}\b/g,
234
+ // The lookahead stops a match running into a longer alphanumeric run (e.g., AIzawa…).
235
+ // It replaces a trailing \b, which cannot hold after a key whose last char is `-`.
236
+ /AIza[A-Za-z0-9_-]{35}(?![A-Za-z0-9_])/g,
136
237
  // #5358: JWTs (incl. claude/OAuth bearer JWTs printed without a "Bearer"/key
137
238
  // marker). header.payload.signature, each base64url; the header always starts
138
239
  // `eyJ` (base64 of `{"`), which makes this specific enough to avoid matching
@@ -146,7 +247,13 @@ const API_KEY_PATTERNS = [
146
247
  // intact. Real webhook tokens are 60+ chars; the 20 floor keeps doc
147
248
  // placeholders like .../webhooks/123/abc readable while catching any
148
249
  // plausible real token.
149
- /\bhttps:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/\d+\/[A-Za-z0-9_-]{20,}/g,
250
+ /https:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/\d+\/[A-Za-z0-9_-]{20,}/g,
251
+ // #8416: classic GitHub personal access tokens: ghp_ + 36 alphanumeric
252
+ // characters. The trailing boundary rejects longer identifiers; there is no leading one, so a
253
+ // token after a word character or a literal backslash-n is still masked.
254
+ /ghp_[A-Za-z0-9]{36}\b/g,
255
+ // #9396: a PEM private-key block with no key name in front of it (see PEM_PRIVATE_KEY_SOURCE).
256
+ new RegExp(PEM_PRIVATE_KEY_SOURCE, 'g'),
150
257
  ]
151
258
 
152
259
  /**
@@ -157,8 +264,35 @@ const API_KEY_PATTERNS = [
157
264
  const SENSITIVE_KEY_NAMES = new Set([
158
265
  'token', 'password', 'apikey', 'secret', 'authorization',
159
266
  'credential', 'private_key', 'api_key',
267
+ 'anthropic_api_key', 'aws_secret_access_key', 'access_token', 'x-api-key',
160
268
  ])
161
269
 
270
+ let redactionFallbackWarned = false
271
+
272
+ /**
273
+ * Say once per process that a redaction fell back to a full mask: a silent fallback would hide a
274
+ * pattern that now throws on real input. Only the error's NAME goes out, never its message or any
275
+ * part of the input, and the logger is not called (the logger redacts through here, so a log call
276
+ * could recurse); the warning goes to the process.
277
+ *
278
+ * @param {unknown} err
279
+ */
280
+ export function noteRedactionFallback(err) {
281
+ if (redactionFallbackWarned) return
282
+ redactionFallbackWarned = true
283
+ try {
284
+ const name = err && typeof err === 'object' && typeof err.name === 'string' ? err.name : undefined
285
+ process.emitWarning('redaction fell back to a full mask', { code: 'CHROXY_REDACT_FALLBACK', detail: name })
286
+ } catch {
287
+ // A warning must never turn the fallback into a throw.
288
+ }
289
+ }
290
+
291
+ /** TEST ONLY: allow the next fallback to warn again. */
292
+ export function resetRedactionFallbackWarningForTest() {
293
+ redactionFallbackWarned = false
294
+ }
295
+
162
296
  /**
163
297
  * Redact secret-shaped substrings from a string value. This is the logger's
164
298
  * existing redaction behavior, hoisted so the tool-broadcast path reuses the
@@ -171,6 +305,22 @@ const SENSITIVE_KEY_NAMES = new Set([
171
305
  * @returns {string}
172
306
  */
173
307
  export function redactValue(msg) {
308
+ // Fail closed: if applying a pattern throws (the regex engine's stack is finite, and a future
309
+ // pattern could meet an input that exhausts it), an exception out of here would reach callers that
310
+ // are not guarded (the broadcast sanitizer, the logger's write), so the text is masked whole
311
+ // instead. The iteration bounds above are what keep this from ever happening, and the fallback
312
+ // says so once (see noteRedactionFallback).
313
+ // Not a string: there is nothing to scan, and the one warning is kept for a real engine failure.
314
+ if (typeof msg !== 'string') return '[REDACTED]'
315
+ try {
316
+ return applyRedaction(msg)
317
+ } catch (err) {
318
+ noteRedactionFallback(err)
319
+ return '[REDACTED]'
320
+ }
321
+ }
322
+
323
+ function applyRedaction(msg) {
174
324
  let result = msg
175
325
  for (const pattern of SENSITIVE_PATTERNS) {
176
326
  result = result.replace(pattern, (match) => {
@@ -264,15 +414,18 @@ function redactDeep(value, depth, seen, maxChars = MAX_INPUT_CHARS) {
264
414
  * pre-write diff) passes a larger `maxChars` (`PULL_MAX_INPUT_CHARS`) — for an
265
415
  * object input (which every real tool_input is), the secret-stripping passes
266
416
  * (KEY-NAME + VALUE-SHAPE) run on every value regardless of the cap, so a higher
267
- * cap never weakens redaction, only the truncation threshold. A non-object input
268
- * is returned as-is (there is nothing to key/redact); callers always pass the
269
- * tool_input object.
417
+ * cap never weakens redaction, only the truncation threshold. Bare strings also
418
+ * use the bounded per-string path (#8416): they are redacted before truncation,
419
+ * subject to the same admission ceiling and unsafe-tail rule as string properties.
420
+ * This intentionally changes oversized root strings from pass-through to bounded
421
+ * output. Other non-object inputs are returned as-is.
270
422
  *
271
- * @param {object} input
423
+ * @param {*} input
272
424
  * @param {{ maxChars?: number }} [opts]
273
- * @returns {object}
425
+ * @returns {*}
274
426
  */
275
427
  function sanitizeToolInput(input, { maxChars = MAX_INPUT_CHARS } = {}) {
428
+ if (typeof input === 'string') return redactDeep(input, 0, new WeakSet(), maxChars)
276
429
  if (!input || typeof input !== 'object') return input
277
430
 
278
431
  const seen = new WeakSet()
@@ -286,6 +439,9 @@ function sanitizeToolInput(input, { maxChars = MAX_INPUT_CHARS } = {}) {
286
439
  // Final size check on the whole object
287
440
  const serialized = JSON.stringify(result)
288
441
  if (serialized.length > maxChars) {
442
+ // The string VALUES in `result` are already redacted, before serialization, so the clip cannot
443
+ // expose a credential held in a value. Property NAMES are not value-scanned (pre-existing). The serialization is deliberately NOT re-scanned as text: a key like
444
+ // `not_a_token` would then lose a value the broadcast kept (permission-outcome-history P3).
289
445
  return markSanitized({ _truncated: true, summary: serialized.slice(0, maxChars) + '... [truncated]' })
290
446
  }
291
447
  return markSanitized(result)
@@ -356,10 +512,13 @@ export function scanWindow(text, scanMax) {
356
512
 
357
513
  /**
358
514
  * How much of the end of a clipped, redacted result is not kept. A pattern fragment
359
- * that straddled a cut (the front of a key, an unterminated quoted value) is at most
360
- * this far from the end of the kept text: the quoted-value bound is 1024 characters
361
- * and every other pattern needs far less, and replacements before the fragment only
362
- * shorten the text ahead of it.
515
+ * that straddled a cut (the front of a key, the BEGIN line of a PEM block, a token
516
+ * run shorter than the 8 characters that make it a match) is at most this far from
517
+ * the end of the kept text, and replacements before the fragment only shorten the
518
+ * text ahead of it. The margin does NOT depend on the length of a value (#9396): a
519
+ * quoted value or a PEM body that reaches the cut has no closing quote or END line
520
+ * in the kept text, and the patterns redact such a value to the end of the input,
521
+ * however long it is, so no part of its body is a fragment to drop.
363
522
  */
364
523
  export const REDACT_SCAN_MARGIN = 2048
365
524
 
@@ -97,6 +97,18 @@ function requireIdWithinWireCap(id) {
97
97
  }
98
98
  }
99
99
 
100
+ /**
101
+ * #8571 — whether `value` has the shape of a task id this store would accept:
102
+ * a non-empty string, already trimmed (`add` trims before storing) and within the
103
+ * wire cap. Shape only; it does not say the task exists. Used to vet a task id read
104
+ * back from persisted session state before it is trusted as a link.
105
+ * @param {unknown} value
106
+ * @returns {boolean}
107
+ */
108
+ export function isScheduledTaskIdShape(value) {
109
+ return typeof value === 'string' && value.length > 0 && value.length <= MAX_WIRE_ID_LENGTH && value === value.trim()
110
+ }
111
+
100
112
  /**
101
113
  * The largest absolute epoch-ms a JS `Date` can represent (±8.64e15, i.e. ±100M
102
114
  * days around the epoch — year ±275760). Beyond it `new Date(ms)` is an Invalid