@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.3

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 (107) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +333 -9
  3. package/dist/aim-CTp-kJW2.d.ts +139 -0
  4. package/dist/aim.d.ts +1 -116
  5. package/dist/alias-dhhr08Ei.d.ts +88 -0
  6. package/dist/alias.d.ts +2 -73
  7. package/dist/api-miiso81x.d.ts +77 -0
  8. package/dist/api.d.ts +1 -62
  9. package/dist/auth-2-jfgiHn.d.ts +34 -0
  10. package/dist/auth.d.ts +1 -26
  11. package/dist/cli-DLygZLi9.d.ts +450 -0
  12. package/dist/cli.d.ts +6 -309
  13. package/dist/cli.js +192 -63
  14. package/dist/config-BUY7_W2n.d.ts +103 -0
  15. package/dist/config.d.ts +1 -97
  16. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  17. package/dist/errcorrect.d.ts +1 -37
  18. package/dist/error-DISJKeDu.d.ts +144 -0
  19. package/dist/id/index.d.ts +2 -83
  20. package/dist/index-Bc5c7Ty5.d.ts +328 -0
  21. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  22. package/dist/index-MLrRDvEG.d.ts +1073 -0
  23. package/dist/index-QSffbLnj.d.ts +94 -0
  24. package/dist/index.d.ts +28 -0
  25. package/dist/index.js +6794 -0
  26. package/dist/llm-B5XUWH8T.d.ts +231 -0
  27. package/dist/llm.d.ts +1 -188
  28. package/dist/mcp/index.d.ts +2 -0
  29. package/dist/mcp/index.js +1453 -0
  30. package/dist/netpolicy-asvCfwi8.d.ts +138 -0
  31. package/dist/netpolicy.d.ts +1 -0
  32. package/dist/netpolicy.js +118 -0
  33. package/dist/output-4aXs91GY.d.ts +396 -0
  34. package/dist/output.d.ts +3 -213
  35. package/dist/output.js +567 -43
  36. package/dist/progress-CAzyxeWl.d.ts +38 -0
  37. package/dist/progress.d.ts +1 -30
  38. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  39. package/dist/provenance.d.ts +1 -24
  40. package/dist/routellm-PGSt2D1y.d.ts +75 -0
  41. package/dist/routellm.d.ts +2 -64
  42. package/dist/rpc-D5xLEf8V.d.ts +32 -0
  43. package/dist/rpc.d.ts +2 -25
  44. package/dist/safety-CUaYEjZc.d.ts +30 -0
  45. package/dist/safety.d.ts +1 -24
  46. package/dist/scope-BrhYB4ij.d.ts +141 -0
  47. package/dist/scope.d.ts +1 -121
  48. package/dist/serve-DE-jscpb.d.ts +646 -0
  49. package/dist/serve.d.ts +3 -0
  50. package/dist/serve.js +1019 -0
  51. package/dist/stream-CrjeCp0M.d.ts +44 -0
  52. package/dist/stream.d.ts +1 -35
  53. package/dist/telemetry/index.d.ts +1 -315
  54. package/dist/telemetry/index.js +12 -1
  55. package/dist/tui/index.d.ts +5 -298
  56. package/dist/tui/index.js +3 -10
  57. package/dist/upgrade-p_zh3pvV.d.ts +102 -0
  58. package/dist/upgrade.d.ts +1 -95
  59. package/dist/xdg-DB7Shoib.d.ts +179 -0
  60. package/dist/xdg.d.ts +1 -169
  61. package/package.json +26 -3
  62. package/src/cli.offline.test.ts +93 -0
  63. package/src/cli.parity.test.ts +192 -0
  64. package/src/cli.ts +112 -12
  65. package/src/index.test.ts +58 -0
  66. package/src/index.ts +37 -0
  67. package/src/log.parity.test.ts +105 -0
  68. package/src/log.ts +64 -13
  69. package/src/mcp/bridge.test.ts +150 -0
  70. package/src/mcp/bridge.ts +246 -0
  71. package/src/mcp/conformance.test.ts +336 -0
  72. package/src/mcp/dispatch.ts +313 -0
  73. package/src/mcp/index.ts +138 -0
  74. package/src/mcp/legacy.ts +314 -0
  75. package/src/mcp/mcp.test.ts +697 -0
  76. package/src/mcp/modern-confirm.test.ts +520 -0
  77. package/src/mcp/modern-confirm.ts +452 -0
  78. package/src/mcp/modern.ts +723 -0
  79. package/src/mcp/tasks.ts +82 -0
  80. package/src/mcp/testtree.ts +250 -0
  81. package/src/mcp/types.ts +504 -0
  82. package/src/netpolicy.test.ts +202 -0
  83. package/src/netpolicy.ts +231 -0
  84. package/src/output/dispatch.ts +10 -2
  85. package/src/output/error.ts +316 -0
  86. package/src/output/formatter.ts +29 -5
  87. package/src/output/formatters/csv.ts +48 -12
  88. package/src/output/formatters/json.ts +4 -25
  89. package/src/output/formatters/project.ts +34 -0
  90. package/src/output/formatters/table.ts +8 -6
  91. package/src/output/formatters/text.ts +7 -3
  92. package/src/output/formatters/yaml.ts +5 -22
  93. package/src/output/projection.test.ts +298 -0
  94. package/src/output/projection.ts +33 -59
  95. package/src/output/template.ts +11 -21
  96. package/src/output.surface.test.ts +41 -0
  97. package/src/output.ts +41 -3
  98. package/src/serve.test.ts +1257 -0
  99. package/src/serve.ts +1665 -0
  100. package/src/telemetry/client.test.ts +31 -0
  101. package/src/telemetry/client.ts +7 -1
  102. package/src/telemetry/offline.test.ts +64 -0
  103. package/src/tui/parity.test.ts +120 -31
  104. package/src/tui/parity.ts +58 -7
  105. package/test/output/csv.test.ts +164 -0
  106. package/test/output/error.test.ts +246 -0
  107. package/src/tui/parity.json +0 -74
@@ -0,0 +1,452 @@
1
+ /**
2
+ * @module mcp/modern-confirm
3
+ * @package @hop-top/kit
4
+ *
5
+ * MRTR (multi round-trip requests) confirmation for the modern
6
+ * (2026-07-28) `tools/call` path: the elicitation-based strategy that
7
+ * fills the confirmation-gate slot when a mount is given key material
8
+ * via `confirmationKey`.
9
+ *
10
+ * Flow (spec: basic/patterns/mrtr + client/elicitation): the first
11
+ * call on a `kit/requires-confirmation` leaf returns `resultType`
12
+ * "input_required" carrying a single `elicitation/create` form request
13
+ * under the reserved `inputRequests` key "confirm" plus an
14
+ * integrity-protected `requestState`. The client gathers the user's
15
+ * decision and retries the original call (new JSON-RPC id) with
16
+ * `params.inputResponses` and the echoed `params.requestState`; the
17
+ * gate verifies the state and lets the invocation proceed only when the
18
+ * confirm response's action is "accept". Decline/cancel refuse the call
19
+ * with an isError complete result.
20
+ *
21
+ * Statelessness: everything a retry needs lives inside `requestState`.
22
+ * There is no server-side pending-request storage of any kind, so any
23
+ * instance holding the same key verifies state minted by any other —
24
+ * which is exactly why the key must be adopter-supplied and shared, and
25
+ * why there is deliberately no generated-at-mount default. The
26
+ * corollary (spec: replay warning) is that an accepted state remains
27
+ * honorable for identical (leaf, arguments, principal) until its TTL
28
+ * lapses; single-use redemption would require the server-side state
29
+ * this surface deliberately does not keep, so the short TTL bounds the
30
+ * window instead.
31
+ *
32
+ * Two verification failures are deliberately distinct (ADR 0004): an
33
+ * expired-but-authentic state is a routine re-prompt; a state failing
34
+ * HMAC verification is never honored — the rejection is recorded as a
35
+ * security-relevant audit event first, and only then is a fresh prompt
36
+ * (with newly minted state) issued. Tampering can therefore cost a
37
+ * request, but is never silently treated as a re-prompt.
38
+ *
39
+ * MRTR confirmation is an alternative way to SATISFY confirmation,
40
+ * never a way to bypass the destructive ceiling: the policy gate runs
41
+ * inside `bridge.invoke` after this gate, exactly as on every other
42
+ * path.
43
+ */
44
+
45
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
46
+
47
+ import {
48
+ canonicalJSONStringify,
49
+ errorResultBlock,
50
+ META_KEY_CLIENT_CAPABILITIES,
51
+ RESULT_TYPE_INPUT_REQUIRED,
52
+ toolName,
53
+ type Leaf,
54
+ } from './types.js';
55
+ import { headerValue } from './legacy.js';
56
+ import type { McpHttpRequest } from './dispatch.js';
57
+
58
+ /**
59
+ * The single reserved `inputRequests` key the confirmation flow uses;
60
+ * the retry's answer is read from the same key in
61
+ * `params.inputResponses`.
62
+ */
63
+ export const MCP_CONFIRM_KEY = 'confirm';
64
+
65
+ /**
66
+ * Lifetime of a minted `requestState`, in seconds. Long enough for a
67
+ * human to read and answer the prompt; short enough to bound the replay
68
+ * window the stateless design cannot otherwise close (see the module
69
+ * comment).
70
+ */
71
+ export const MCP_CONFIRM_STATE_TTL_SECONDS = 5 * 60;
72
+
73
+ /**
74
+ * Tags the `requestState` wire format so a future format change
75
+ * invalidates (rather than misparses) old state.
76
+ */
77
+ export const MCP_CONFIRM_STATE_VERSION = 'v1';
78
+
79
+ /**
80
+ * Domain separation for the MAC, so this tag can never be confused with
81
+ * any other HMAC minted under a shared key.
82
+ */
83
+ const MAC_DOMAIN = `cmdsurface-mcp-confirm-${MCP_CONFIRM_STATE_VERSION}`;
84
+
85
+ /**
86
+ * The request context a `requestState` is bound to. The HMAC covers
87
+ * every field plus the expiry, so state presented for a different leaf,
88
+ * different arguments, or by a different principal fails verification
89
+ * outright (spec: reject state presented on a request that does not
90
+ * match / by a different principal).
91
+ */
92
+ export interface McpConfirmBinding {
93
+ /** The leaf path key, space-joined, e.g. "widget purge". */
94
+ tool: string;
95
+ /** Hex SHA-256 of the canonically serialized `params.arguments`. */
96
+ argsDigest: string;
97
+ /**
98
+ * Hex SHA-256 of the `Authorization` header value, or "" when the
99
+ * request carried none. Hashed so the MAC input never embeds
100
+ * credential material.
101
+ */
102
+ principal: string;
103
+ }
104
+
105
+ /** The outcome of verifying a presented `requestState`. */
106
+ export type McpConfirmStateStatus = 'valid' | 'expired' | 'invalid';
107
+
108
+ /** One recorded rejection of a state that failed integrity verification. */
109
+ export interface McpConfirmRejection {
110
+ path: string;
111
+ mcpConfirmRejection: string;
112
+ }
113
+
114
+ /** A gate decision: the result body to write plus its HTTP status. */
115
+ export type McpConfirmDecision = { result: Record<string, unknown>; status: number };
116
+
117
+ /**
118
+ * The MRTR confirmation gate for mounts configured with a
119
+ * `confirmationKey`.
120
+ *
121
+ * Clients that did not declare form-mode elicitation keep the
122
+ * `X-Confirm-Token` header gate: the spec forbids sending
123
+ * `inputRequests` for a capability the client never declared, and the
124
+ * capability stays optional precisely because this fallback exists — so
125
+ * a missing elicitation capability is never -32021 here.
126
+ */
127
+ export class ElicitationConfirmGate {
128
+ private readonly key: Buffer;
129
+
130
+ /**
131
+ * Audit records of rejected states, standing in for Go's bridge sink
132
+ * fan-out, which this port does not carry.
133
+ */
134
+ readonly rejections: McpConfirmRejection[] = [];
135
+
136
+ constructor(key: Uint8Array) {
137
+ if (key.length === 0) {
138
+ throw new Error('cmdsurface: confirmationKey: empty key');
139
+ }
140
+ this.key = Buffer.from(key);
141
+ }
142
+
143
+ /**
144
+ * Runs the gate for one `tools/call`. Returns `undefined` to proceed
145
+ * with the invocation, or the refusal / interim result plus its HTTP
146
+ * status. The caller stamps the modern envelope onto whatever is
147
+ * returned.
148
+ */
149
+ evaluate(
150
+ req: McpHttpRequest,
151
+ leaf: Leaf,
152
+ params: unknown,
153
+ ): McpConfirmDecision | undefined {
154
+ if (!leaf.class?.requiresConfirmation) return undefined;
155
+ if (!clientSupportsFormElicitation(params)) {
156
+ return headerConfirmationGate(req);
157
+ }
158
+
159
+ const binding: McpConfirmBinding = {
160
+ tool: leaf.path.join(' '),
161
+ argsDigest: mcpConfirmArgsDigest(params),
162
+ principal: mcpConfirmPrincipal(req),
163
+ };
164
+ const retry = parseMcpConfirmRetry(params);
165
+
166
+ if (retry.state === '') {
167
+ // A first call — or a retry that dropped the state it was
168
+ // required to echo, which is indistinguishable from one and
169
+ // equally unverifiable. Prompt (again).
170
+ return { result: this.inputRequired(leaf, binding), status: 200 };
171
+ }
172
+
173
+ const status = verifyMcpConfirmState(
174
+ this.key,
175
+ retry.state,
176
+ binding,
177
+ nowSeconds(),
178
+ );
179
+ if (status === 'invalid') {
180
+ // Tampered, malformed, or presented for a different request /
181
+ // principal than it was minted for: never honored, audited, then
182
+ // re-prompted with fresh state (see the module comment).
183
+ this.auditRejection(leaf);
184
+ return { result: this.inputRequired(leaf, binding), status: 200 };
185
+ }
186
+ if (status === 'expired') {
187
+ // Authentic but past its TTL: a routine re-prompt (spec:
188
+ // re-request missing information rather than error), no audit.
189
+ return { result: this.inputRequired(leaf, binding), status: 200 };
190
+ }
191
+
192
+ if (retry.action === 'accept') return undefined;
193
+ if (retry.action === 'decline' || retry.action === 'cancel') {
194
+ return { result: errorResultBlock('confirmation declined'), status: 200 };
195
+ }
196
+ // The confirm answer is missing or unusable (absent inputResponses,
197
+ // non-object entry, unknown action): the requested information was
198
+ // not provided, so re-request it rather than erroring (spec SHOULD).
199
+ return { result: this.inputRequired(leaf, binding), status: 200 };
200
+ }
201
+
202
+ /**
203
+ * Builds the `input_required` result envelope for one confirmation
204
+ * prompt: the reserved "confirm" `elicitation/create` form request
205
+ * plus freshly minted `requestState` (satisfying the spec MUST of
206
+ * carrying at least one of `inputRequests` / `requestState` — this
207
+ * flow always carries both). The caller stamps the envelope (_meta
208
+ * serverInfo; `resultType` stays "input_required") and writes it at
209
+ * HTTP 200. Interim `input_required` results are never cacheable: no
210
+ * `ttlMs` / `cacheScope` members, ever.
211
+ */
212
+ inputRequired(
213
+ leaf: Leaf,
214
+ binding: McpConfirmBinding,
215
+ ): Record<string, unknown> {
216
+ const expiry = nowSeconds() + MCP_CONFIRM_STATE_TTL_SECONDS;
217
+ return {
218
+ resultType: RESULT_TYPE_INPUT_REQUIRED,
219
+ inputRequests: {
220
+ [MCP_CONFIRM_KEY]: {
221
+ method: 'elicitation/create',
222
+ params: {
223
+ mode: 'form',
224
+ message: `Approve execution of ${JSON.stringify(toolName(leaf.path))}?`,
225
+ // No form fields: the approval rides the elicit action
226
+ // (accept / decline / cancel), so the requested schema is
227
+ // the empty object.
228
+ requestedSchema: { type: 'object', properties: {} },
229
+ },
230
+ },
231
+ },
232
+ requestState: mintMcpConfirmState(this.key, binding, expiry),
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Records a failed `requestState` verification as a
238
+ * security-relevant audit event. Go emits this on the bridge's
239
+ * registered sinks; this port has no sink fan-out, so the records
240
+ * accumulate here for adopters and tests to read. Best-effort by the
241
+ * same contract: recording never affects the response.
242
+ */
243
+ private auditRejection(leaf: Leaf): void {
244
+ this.rejections.push({
245
+ path: leaf.path.join(' '),
246
+ mcpConfirmRejection: 'request_state_verification_failed',
247
+ });
248
+ }
249
+ }
250
+
251
+ /**
252
+ * The default gate: a `requiresConfirmation` leaf needs the
253
+ * `X-Confirm-Token` header, exactly as on the legacy path. This is the
254
+ * fallback for clients without form elicitation and the whole gate for
255
+ * mounts without a confirmation key.
256
+ */
257
+ export function headerConfirmationGate(
258
+ req: McpHttpRequest,
259
+ ): McpConfirmDecision | undefined {
260
+ if (headerValue(req, 'x-confirm-token')) return undefined;
261
+ return { result: errorResultBlock('confirmation required'), status: 428 };
262
+ }
263
+
264
+ /**
265
+ * Reports whether the request's
266
+ * `io.modelcontextprotocol/clientCapabilities` declares form-mode
267
+ * elicitation. Per spec, an empty `elicitation` object (`{}`) declares
268
+ * form-only support; a non-empty object must name "form" among its
269
+ * modes (a url-only client cannot receive this flow's form request).
270
+ * Anything that is not a conforming object declaration — key absent,
271
+ * value null or non-object — counts as undeclared, failing toward the
272
+ * header fallback rather than toward sending a request the client never
273
+ * said it could handle.
274
+ */
275
+ export function clientSupportsFormElicitation(params: unknown): boolean {
276
+ const meta = plainObject(plainObject(params)?._meta);
277
+ if (meta === undefined) return false;
278
+ const caps = plainObject(meta[META_KEY_CLIENT_CAPABILITIES]);
279
+ if (caps === undefined) return false;
280
+ const modes = plainObject(caps.elicitation);
281
+ if (modes === undefined) return false;
282
+ if (Object.keys(modes).length === 0) return true;
283
+ return 'form' in modes;
284
+ }
285
+
286
+ /**
287
+ * The tolerant read of the MRTR retry members of a `tools/call`
288
+ * request. Members that are absent or of the wrong JSON type simply
289
+ * stay empty — the gate treats a missing state as "prompt" and a
290
+ * missing/unusable action as "re-prompt", so malformed retries converge
291
+ * on a fresh `input_required` rather than a decode error.
292
+ */
293
+ export function parseMcpConfirmRetry(params: unknown): {
294
+ state: string;
295
+ action: string;
296
+ } {
297
+ const obj = plainObject(params);
298
+ if (obj === undefined) return { state: '', action: '' };
299
+
300
+ const state = typeof obj.requestState === 'string' ? obj.requestState : '';
301
+
302
+ let action = '';
303
+ const entry = plainObject(plainObject(obj.inputResponses)?.[MCP_CONFIRM_KEY]);
304
+ if (entry !== undefined && typeof entry.action === 'string') {
305
+ action = entry.action;
306
+ }
307
+ return { state, action };
308
+ }
309
+
310
+ /**
311
+ * Derives the principal component of the state binding: hex SHA-256 of
312
+ * the `Authorization` value, "" when the header is absent.
313
+ * Presence-only bearer checking is all this surface does for auth
314
+ * (`class.authRequired`), so the raw header value is the closest stable
315
+ * principal identifier available; hashing keeps credential material out
316
+ * of the MAC input.
317
+ */
318
+ export function mcpConfirmPrincipal(req: McpHttpRequest): string {
319
+ const auth = headerValue(req, 'authorization');
320
+ if (!auth) return '';
321
+ return createHash('sha256').update(auth, 'utf8').digest('hex');
322
+ }
323
+
324
+ /**
325
+ * Returns the hex SHA-256 of the canonically serialized
326
+ * `params.arguments`. Canonical form sorts object keys at every nesting
327
+ * level, so equal argument sets digest identically regardless of the
328
+ * client's key order; absent arguments canonicalize to "null". Only the
329
+ * arguments participate: `_meta`, `inputResponses`, and `requestState`
330
+ * all legitimately differ between the first call and its retry, and the
331
+ * tool name is bound separately via the leaf path key.
332
+ */
333
+ export function mcpConfirmArgsDigest(params: unknown): string {
334
+ // Go decodes params.arguments into map[string]any, so a non-object
335
+ // value (array, string, number) decodes as absent and canonicalizes
336
+ // to "null" — matched here rather than digesting the raw value.
337
+ const args = plainObject(plainObject(params)?.arguments) ?? null;
338
+ const canonical = canonicalJSONStringify(args);
339
+ return createHash('sha256').update(canonical, 'utf8').digest('hex');
340
+ }
341
+
342
+ /**
343
+ * Computes the HMAC-SHA-256 tag binding a state to its expiry and
344
+ * request context. Each component is written length-prefixed so the
345
+ * concatenation is unambiguous whatever the component contents (no
346
+ * delimiter-injection ambiguity), with a leading domain-separation
347
+ * constant so the tag can never be confused with any other HMAC minted
348
+ * under a shared key.
349
+ */
350
+ function mcpConfirmStateMac(
351
+ key: Buffer,
352
+ binding: McpConfirmBinding,
353
+ expiry: number,
354
+ ): Buffer {
355
+ const mac = createHmac('sha256', key);
356
+ for (const part of [
357
+ MAC_DOMAIN,
358
+ String(expiry),
359
+ binding.tool,
360
+ binding.argsDigest,
361
+ binding.principal,
362
+ ]) {
363
+ // Length-prefixed by BYTE length, matching Go's len(part) over a
364
+ // string's bytes rather than JS's UTF-16 code-unit count.
365
+ mac.update(`${Buffer.byteLength(part, 'utf8')}:${part}`, 'utf8');
366
+ }
367
+ return mac.digest();
368
+ }
369
+
370
+ /**
371
+ * Renders an opaque-to-clients `requestState`:
372
+ * `v1.<expiry-unix>.<base64url(mac)>`. Only the version and expiry
373
+ * travel in the clear; the full binding is reconstructed from the retry
374
+ * request itself at verification time, which is what keeps the state
375
+ * small and the flow stateless.
376
+ */
377
+ export function mintMcpConfirmState(
378
+ key: Uint8Array,
379
+ binding: McpConfirmBinding,
380
+ expiry: number,
381
+ ): string {
382
+ const mac = mcpConfirmStateMac(Buffer.from(key), binding, expiry);
383
+ return `${MCP_CONFIRM_STATE_VERSION}.${expiry}.${mac.toString('base64url')}`;
384
+ }
385
+
386
+ /**
387
+ * Checks a presented state against the current request's binding.
388
+ * Authenticity is decided BEFORE expiry, so "expired" is only ever
389
+ * reported for a state that verifiably came from this key and this
390
+ * exact binding — a tampered expiry fails the MAC and lands in
391
+ * "invalid", never in "expired". Any structural defect (wrong part
392
+ * count, unknown version, non-decimal expiry, undecodable tag) is a
393
+ * verification failure too: a state that cannot be verified is never
394
+ * honored.
395
+ */
396
+ export function verifyMcpConfirmState(
397
+ key: Uint8Array,
398
+ state: string,
399
+ binding: McpConfirmBinding,
400
+ now: number,
401
+ ): McpConfirmStateStatus {
402
+ const parts = state.split('.');
403
+ if (parts.length !== 3 || parts[0] !== MCP_CONFIRM_STATE_VERSION) {
404
+ return 'invalid';
405
+ }
406
+ // Go's strconv.ParseInt is strict decimal: reject anything that is
407
+ // not an optionally-signed run of digits, which JS's Number() would
408
+ // otherwise accept as hex, exponent, or whitespace-padded.
409
+ if (!/^-?\d+$/.test(parts[1])) return 'invalid';
410
+ const expiry = Number(parts[1]);
411
+ if (!Number.isSafeInteger(expiry)) return 'invalid';
412
+
413
+ const tag = decodeBase64Url(parts[2]);
414
+ if (tag === undefined) return 'invalid';
415
+
416
+ const want = mcpConfirmStateMac(Buffer.from(key), binding, expiry);
417
+ if (tag.length !== want.length || !timingSafeEqual(tag, want)) {
418
+ return 'invalid';
419
+ }
420
+ if (expiry < now) return 'expired';
421
+ return 'valid';
422
+ }
423
+
424
+ /**
425
+ * Strict, canonical base64url decode. Node's `Buffer.from(s,
426
+ * 'base64url')` is lenient — it silently drops non-alphabet bytes —
427
+ * whereas Go's `base64.RawURLEncoding.DecodeString` errors, so the
428
+ * round-trip check rejects anything Go would refuse.
429
+ */
430
+ function decodeBase64Url(s: string): Buffer | undefined {
431
+ if (!/^[A-Za-z0-9_-]*$/.test(s)) return undefined;
432
+ const buf = Buffer.from(s, 'base64url');
433
+ if (buf.toString('base64url') !== s) return undefined;
434
+ return buf;
435
+ }
436
+
437
+ /** Whole seconds since the Unix epoch. */
438
+ function nowSeconds(): number {
439
+ return Math.floor(Date.now() / 1000);
440
+ }
441
+
442
+ /**
443
+ * Narrows a value to a plain JSON object, the shape every tolerant read
444
+ * above expects. Arrays and null are not objects for this purpose:
445
+ * treating them as absent is what makes malformed input converge on a
446
+ * fresh prompt rather than on a decode error.
447
+ */
448
+ function plainObject(v: unknown): Record<string, unknown> | undefined {
449
+ if (v === null || v === undefined || typeof v !== 'object') return undefined;
450
+ if (Array.isArray(v)) return undefined;
451
+ return v as Record<string, unknown>;
452
+ }