@chroxy/server 0.10.0 → 0.11.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 (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -0,0 +1,327 @@
1
+ /**
2
+ * Encrypted-at-rest token store for remote MCP OAuth (#6822).
3
+ *
4
+ * A remote MCP server (BYOK remote transport, #6821) that requires browser-based
5
+ * OAuth (#6822) yields access + refresh tokens the daemon must persist so a
6
+ * previously-authorized server reconnects without re-prompting. Those tokens are
7
+ * CREDENTIALS — this module stores them with the same at-rest protection the
8
+ * credential store uses (#5154 / #6644): a 0600 owner-only JSON file whose whole
9
+ * body is encrypted with a random data key held in the OS keychain (macOS
10
+ * Keychain / Linux libsecret / Windows DPAPI), via credential-cipher.js. Where no
11
+ * keychain is available the store falls back to 0600 plaintext (a key beside the
12
+ * file would be obfuscation, not security) — identical posture to credential-store.
13
+ *
14
+ * File: `~/.chroxy/mcp-oauth-tokens.json`
15
+ * Layout (decrypted): `{ "<serverKey>": <McpOAuthRecord>, ... }` keyed by a
16
+ * normalized form of the server URL (origin + path, no userinfo/query/fragment)
17
+ * so a single server identity survives header/token rotation on the config side.
18
+ *
19
+ * SECURITY: token/secret VALUES never leave this module except through the
20
+ * getters that hand them to the OAuth flow. Nothing here is ever logged — not the
21
+ * record, not the key, not a masked form. The keychain is dependency-injected
22
+ * (mirrors credential-cipher) so tests drive the encrypted path with an in-memory
23
+ * key and NEVER touch the real OS keychain.
24
+ */
25
+ import { readFileSync, statSync, writeFileSync, chmodSync, renameSync, mkdirSync, unlinkSync, existsSync } from 'node:fs'
26
+ import { join, dirname } from 'node:path'
27
+ import { homedir } from 'node:os'
28
+ import { randomBytes } from 'node:crypto'
29
+ import * as realKeychain from './keychain.js'
30
+ import { createLogger } from './logger.js'
31
+ import {
32
+ isEncryptedEnvelope,
33
+ decryptEnvelope,
34
+ encryptJson,
35
+ getMasterKey,
36
+ getOrCreateMasterKey,
37
+ } from './credential-cipher.js'
38
+
39
+ // #6822 review: on Windows an antivirus / Search-indexer held handle on the
40
+ // destination can make an otherwise-atomic renameSync fail transiently with one
41
+ // of these codes. Mirrors session-state-persistence.WINDOWS_LOCK_CODES /
42
+ // credential-store.CRED_WINDOWS_LOCK_CODES; renameWithRetry backs off and retries.
43
+ const WINDOWS_LOCK_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'EEXIST'])
44
+
45
+ /** Synchronous millisecond sleep (Atomics.wait on a throwaway SharedArrayBuffer). */
46
+ function sleepSync(ms) {
47
+ try {
48
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
49
+ } catch {
50
+ // Atomics/SharedArrayBuffer unavailable — skip the backoff; the syscall
51
+ // overhead of the retry still spaces attempts.
52
+ }
53
+ }
54
+
55
+ /**
56
+ * renameSync with a small retry-with-backoff on Windows held-handle locks. On
57
+ * POSIX (or any non-lock error) the first failure throws unchanged. On Windows
58
+ * a transient EPERM/EACCES/EBUSY/EEXIST is retried a few times before giving up.
59
+ */
60
+ function renameWithRetry(tmp, target) {
61
+ const maxAttempts = process.platform === 'win32' ? 5 : 1
62
+ let lastErr
63
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
64
+ try {
65
+ renameSync(tmp, target)
66
+ return
67
+ } catch (err) {
68
+ lastErr = err
69
+ if (process.platform !== 'win32' || !err || !WINDOWS_LOCK_CODES.has(err.code)) throw err
70
+ if (attempt < maxAttempts - 1) sleepSync(20 * (attempt + 1)) // 20/40/60/80ms
71
+ }
72
+ }
73
+ throw lastErr
74
+ }
75
+
76
+ // One-time breadcrumb when an intact encrypted token record exists on disk but
77
+ // its keychain data key is currently unavailable (locked keychain / transient
78
+ // probe failure) — matches credential-store's warnKeychainUnavailableOnce so a
79
+ // silent unauthenticated MCP reconnect is observable. The value is NEVER logged.
80
+ const _log = createLogger('mcp-oauth-store')
81
+ let _keychainUnavailableWarned = false
82
+ function warnKeychainUnavailableOnce() {
83
+ if (_keychainUnavailableWarned) return
84
+ _keychainUnavailableWarned = true
85
+ _log.warn(
86
+ 'an MCP OAuth token is stored (encrypted) but its OS keychain data key is currently unavailable — ' +
87
+ 'resolving as absent; the server may re-prompt for authorization. Unlock the OS keychain and retry.',
88
+ )
89
+ }
90
+
91
+ // A keychain stub reporting "no keychain here" — selects the plaintext fallback.
92
+ const NO_KEYCHAIN = { isKeychainAvailable: () => false }
93
+
94
+ // Explicit test injection (an in-memory keychain), or null to use the resolved
95
+ // default. Mirrors credential-store's `_setCredentialKeychainForTests` seam.
96
+ let _keychainOverride = null
97
+
98
+ /**
99
+ * Resolve the keychain to use for at-rest encryption, evaluated lazily per call
100
+ * (never captured at import). Precedence:
101
+ * 1. explicit test injection wins;
102
+ * 2. `CHROXY_CRED_DISABLE_KEYCHAIN=1` forces the plaintext fallback (the switch
103
+ * the test bootstrap sets so suites never touch the real keychain);
104
+ * 3. the real OS keychain.
105
+ */
106
+ function activeKeychain() {
107
+ if (_keychainOverride) return _keychainOverride
108
+ if (process.env.CHROXY_CRED_DISABLE_KEYCHAIN === '1') return NO_KEYCHAIN
109
+ return realKeychain
110
+ }
111
+
112
+ /** Test seam: inject a keychain (e.g. an in-memory one), or null to reset. */
113
+ export function _setMcpOAuthKeychainForTests(keychain) {
114
+ _keychainOverride = keychain || null
115
+ }
116
+
117
+ // Lazy-resolved per call so tests that mutate process.env.HOME between cases pick
118
+ // up the new home (frozen-at-import would break the CHROXY_*_HOME isolation the
119
+ // provider-oauth-test-isolation memory prescribes).
120
+ function tokensFilePath() {
121
+ return process.env.CHROXY_MCP_OAUTH_TOKENS_PATH || join(homedir(), '.chroxy', 'mcp-oauth-tokens.json')
122
+ }
123
+
124
+ /**
125
+ * Normalize a server URL into the stable per-server storage key: origin + path,
126
+ * lowercased host, no userinfo / query / fragment, no trailing slash. This is the
127
+ * server's OAuth "resource" identity — two configs pointing at the same endpoint
128
+ * with different bearer headers share one token record. Returns null for an
129
+ * unparseable url (caller treats that as "not storable").
130
+ *
131
+ * @param {string} url
132
+ * @returns {string|null}
133
+ */
134
+ export function serverKeyForUrl(url) {
135
+ if (typeof url !== 'string' || url.length === 0) return null
136
+ try {
137
+ const u = new URL(url)
138
+ u.username = ''
139
+ u.password = ''
140
+ u.search = ''
141
+ u.hash = ''
142
+ let s = u.toString()
143
+ if (s.endsWith('/')) s = s.slice(0, -1)
144
+ return s
145
+ } catch {
146
+ return null
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Read + parse the tokens file, enforcing the 0600 mode boundary and decrypting
152
+ * an encrypted envelope. Returns `{ data, fileExists, error }`. On any read error
153
+ * `data` is `{}` and `error` carries a VALUE-FREE reason (never a token). Modeled
154
+ * on credential-store.readStore.
155
+ */
156
+ function readStore() {
157
+ const file = tokensFilePath()
158
+ let stat
159
+ try {
160
+ stat = statSync(file)
161
+ } catch (err) {
162
+ if (err.code === 'ENOENT') return { data: {}, fileExists: false, error: null }
163
+ return { data: {}, fileExists: false, error: `unable to stat ${file}: ${err.message}` }
164
+ }
165
+ if (process.platform !== 'win32') {
166
+ const perms = stat.mode & 0o777
167
+ if (perms !== 0o600) {
168
+ return {
169
+ data: {},
170
+ fileExists: true,
171
+ error: `${file} has mode ${perms.toString(8).padStart(3, '0')}; refusing to read (must be 0600)`,
172
+ }
173
+ }
174
+ }
175
+ let parsed
176
+ try {
177
+ parsed = JSON.parse(readFileSync(file, 'utf8'))
178
+ } catch (err) {
179
+ return { data: {}, fileExists: true, error: `${file} unreadable or not valid JSON: ${err.message}` }
180
+ }
181
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
182
+ return { data: {}, fileExists: true, error: `${file} is not a JSON object` }
183
+ }
184
+ if (isEncryptedEnvelope(parsed)) {
185
+ const key = getMasterKey(activeKeychain())
186
+ if (!key) {
187
+ return { data: {}, fileExists: true, error: `${file} is encrypted but its keychain data key is unavailable`, keychainUnavailable: true }
188
+ }
189
+ try {
190
+ return { data: decryptEnvelope(parsed, key), fileExists: true, error: null, encrypted: true }
191
+ } catch (err) {
192
+ return { data: {}, fileExists: true, error: `${file} could not be decrypted: ${err.message}`, encrypted: true }
193
+ }
194
+ }
195
+ return { data: parsed, fileExists: true, error: null, encrypted: false }
196
+ }
197
+
198
+ /**
199
+ * Serialize + atomically write the store, encrypting when a keychain-backed data
200
+ * key is available and otherwise writing 0600 plaintext (temp → chmod 0600 →
201
+ * rename). Mirrors credential-store.writeStoreAtomically minus the Windows
202
+ * held-handle retry (not load-bearing for this low-churn store).
203
+ */
204
+ function writeStoreAtomically(nextObj) {
205
+ const target = tokensFilePath()
206
+ mkdirSync(dirname(target), { recursive: true, mode: 0o700 })
207
+ const key = getOrCreateMasterKey(activeKeychain())
208
+ const payload = key ? encryptJson(nextObj, key) : nextObj
209
+ const tmp = `${target}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`
210
+ let renamed = false
211
+ try {
212
+ writeFileSync(tmp, JSON.stringify(payload, null, 2), { mode: 0o600 })
213
+ if (process.platform !== 'win32') chmodSync(tmp, 0o600)
214
+ renameWithRetry(tmp, target)
215
+ renamed = true
216
+ // Post-rename mode re-check (POSIX), matching credential-store: if the file
217
+ // landed with anything other than 0600, remove it and fail rather than
218
+ // leaving tokens at a more permissive mode.
219
+ if (process.platform !== 'win32') {
220
+ const perms = statSync(target).mode & 0o777
221
+ if (perms !== 0o600) {
222
+ try { unlinkSync(target) } catch { /* best-effort */ }
223
+ throw new Error(`mcp-oauth-tokens ended up with mode ${perms.toString(8)} after write; refused`)
224
+ }
225
+ }
226
+ } finally {
227
+ if (!renamed && existsSync(tmp)) {
228
+ try { unlinkSync(tmp) } catch { /* best-effort */ }
229
+ }
230
+ }
231
+ }
232
+
233
+ /**
234
+ * @typedef {object} McpOAuthRecord
235
+ * @property {string} accessToken
236
+ * @property {string} [refreshToken]
237
+ * @property {string} [tokenType] - 'Bearer' by default.
238
+ * @property {string} [scope]
239
+ * @property {number} expiresAt - epoch ms; 0 when the server omitted expires_in.
240
+ * @property {string} clientId
241
+ * @property {string} [clientSecret] - present only for confidential DCR clients.
242
+ * @property {string} tokenEndpoint
243
+ * @property {string} [authorizationEndpoint]
244
+ * @property {string} [registrationEndpoint]
245
+ * @property {string} [resource] - canonical resource indicator (RFC 8707).
246
+ */
247
+
248
+ /**
249
+ * Read the stored OAuth record for a server URL, or null when none exists (or on
250
+ * a read error — the caller falls back to the unauthenticated / re-auth path). A
251
+ * read error is intentionally swallowed to null here: a locked keychain must not
252
+ * wedge the connect, and the flow re-authorizes cleanly.
253
+ *
254
+ * @param {string} url
255
+ * @returns {McpOAuthRecord|null}
256
+ */
257
+ export function getStoredToken(url) {
258
+ const serverKey = serverKeyForUrl(url)
259
+ if (!serverKey) return null
260
+ const { data, error, keychainUnavailable } = readStore()
261
+ if (error) {
262
+ // Distinguish the RECOVERABLE keychain-locked case (intact envelope, key
263
+ // temporarily unfetchable) from a corrupt/bad-mode read: only the former
264
+ // gets the one-time breadcrumb, matching credential-store's discipline.
265
+ if (keychainUnavailable) warnKeychainUnavailableOnce()
266
+ return null
267
+ }
268
+ const rec = data[serverKey]
269
+ if (!rec || typeof rec !== 'object' || typeof rec.accessToken !== 'string' || !rec.accessToken) return null
270
+ return rec
271
+ }
272
+
273
+ /**
274
+ * Persist an OAuth record for a server URL (merging into the existing store). A
275
+ * prior read error aborts rather than clobbering sibling records — same
276
+ * discipline as credential-store.setStoredCredential.
277
+ *
278
+ * @param {string} url
279
+ * @param {McpOAuthRecord} record
280
+ */
281
+ export function setStoredToken(url, record) {
282
+ const serverKey = serverKeyForUrl(url)
283
+ if (!serverKey) throw new Error('MCP OAuth store: unstorable server url')
284
+ if (!record || typeof record.accessToken !== 'string' || !record.accessToken) {
285
+ throw new Error('MCP OAuth store: record requires a non-empty accessToken')
286
+ }
287
+ const { data, error } = readStore()
288
+ if (error) throw new Error(error)
289
+ writeStoreAtomically({ ...data, [serverKey]: record })
290
+ }
291
+
292
+ /**
293
+ * Remove the stored record for a server URL (no-op when absent). Deletes the file
294
+ * entirely when it would be left empty. A read error aborts rather than guessing.
295
+ *
296
+ * @param {string} url
297
+ */
298
+ export function deleteStoredToken(url) {
299
+ const serverKey = serverKeyForUrl(url)
300
+ if (!serverKey) return
301
+ const { data, fileExists, error } = readStore()
302
+ if (!fileExists) return
303
+ if (error) throw new Error(error)
304
+ if (!(serverKey in data)) return
305
+ const next = { ...data }
306
+ delete next[serverKey]
307
+ if (Object.keys(next).length === 0) {
308
+ try { unlinkSync(tokensFilePath()) } catch (err) { if (err.code !== 'ENOENT') throw err }
309
+ return
310
+ }
311
+ writeStoreAtomically(next)
312
+ }
313
+
314
+ /**
315
+ * True when a record's access token is expired (or within `skewMs` of expiry).
316
+ * A record with `expiresAt === 0` (server omitted expires_in) is treated as
317
+ * NON-expiring here — the reactive 401 path re-auths it if the server later
318
+ * rejects it.
319
+ *
320
+ * @param {McpOAuthRecord} record
321
+ * @param {number} [skewMs] - refresh-ahead window (default 60s).
322
+ * @returns {boolean}
323
+ */
324
+ export function isTokenExpired(record, skewMs = 60_000) {
325
+ if (!record || typeof record.expiresAt !== 'number' || record.expiresAt <= 0) return false
326
+ return Date.now() >= record.expiresAt - skewMs
327
+ }