@kya-os/mcp-i-runtime 1.3.1 → 1.3.2

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 (62) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +13 -2
  5. package/dist/index.js.map +1 -1
  6. package/dist/proof/generator.d.ts +8 -6
  7. package/dist/proof/generator.d.ts.map +1 -1
  8. package/dist/proof/generator.js +7 -24
  9. package/dist/proof/generator.js.map +1 -1
  10. package/dist/runtime/audit.d.ts.map +1 -1
  11. package/dist/runtime/audit.js +66 -18
  12. package/dist/runtime/audit.js.map +1 -1
  13. package/dist/runtime/base.d.ts +6 -1
  14. package/dist/runtime/base.d.ts.map +1 -1
  15. package/dist/runtime/base.js +65 -17
  16. package/dist/runtime/base.js.map +1 -1
  17. package/dist/services/access-control.service.d.ts.map +1 -1
  18. package/dist/services/access-control.service.js +12 -5
  19. package/dist/services/access-control.service.js.map +1 -1
  20. package/dist/services/proof-verifier.d.ts +13 -35
  21. package/dist/services/proof-verifier.d.ts.map +1 -1
  22. package/dist/services/proof-verifier.js +16 -74
  23. package/dist/services/proof-verifier.js.map +1 -1
  24. package/dist/services/tool-context-builder.d.ts.map +1 -1
  25. package/dist/services/tool-context-builder.js +16 -4
  26. package/dist/services/tool-context-builder.js.map +1 -1
  27. package/dist/services/tool-protection.service.d.ts +7 -0
  28. package/dist/services/tool-protection.service.d.ts.map +1 -1
  29. package/dist/services/tool-protection.service.js +34 -15
  30. package/dist/services/tool-protection.service.js.map +1 -1
  31. package/dist/types/tool-protection.d.ts +94 -0
  32. package/dist/types/tool-protection.d.ts.map +1 -1
  33. package/dist/types/tool-protection.js +113 -1
  34. package/dist/types/tool-protection.js.map +1 -1
  35. package/package.json +2 -2
  36. package/src/__tests__/runtime/amount-limit-enforcement.test.ts +269 -0
  37. package/src/__tests__/runtime/amount-limit-result.test.ts +61 -0
  38. package/src/__tests__/runtime/audit-contracts-compat.test.ts +20 -5
  39. package/src/__tests__/runtime/audit.test.ts +255 -53
  40. package/src/__tests__/runtime/process-tool-call-security.test.ts +97 -13
  41. package/src/__tests__/runtime/provider-selection.test.ts +4 -6
  42. package/src/__tests__/runtime/route-interception.test.ts +215 -214
  43. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +89 -6
  44. package/src/__tests__/services/tool-protection-amount.test.ts +107 -0
  45. package/src/__tests__/services/tool-protection-failsafe.test.ts +71 -4
  46. package/src/__tests__/utils/tool-protection-runtime.ts +3 -0
  47. package/src/index.ts +15 -1
  48. package/src/proof/__tests__/proof-generator.test.ts +35 -12
  49. package/src/proof/generator.ts +18 -27
  50. package/src/runtime/__tests__/ext-apps-consent.test.ts +87 -2
  51. package/src/runtime/audit.ts +155 -62
  52. package/src/runtime/base.ts +95 -31
  53. package/src/services/__tests__/access-control.service.test.ts +44 -0
  54. package/src/services/__tests__/proof-verifier.test.ts +283 -195
  55. package/src/services/__tests__/tool-context-builder-authtype.test.ts +79 -0
  56. package/src/services/__tests__/tool-context-builder.test.ts +4 -7
  57. package/src/services/__tests__/tool-protection-served-revision.test.ts +102 -0
  58. package/src/services/access-control.service.ts +11 -5
  59. package/src/services/proof-verifier.ts +18 -79
  60. package/src/services/tool-context-builder.ts +19 -4
  61. package/src/services/tool-protection.service.ts +62 -19
  62. package/src/types/tool-protection.ts +161 -0
@@ -8,26 +8,26 @@
8
8
  * Test Coverage Requirements: 100% - All security-critical code paths
9
9
  */
10
10
 
11
- import { describe, it, expect, beforeEach, vi } from 'vitest';
12
- import { ProofVerifier } from '../proof-verifier.js';
13
- import { CryptoService, type Ed25519JWK } from '../crypto.service.js';
11
+ import { describe, it, expect, beforeEach, vi } from "vitest";
12
+ import { ProofVerifier } from "../proof-verifier.js";
13
+ import { CryptoService, type Ed25519JWK } from "../crypto.service.js";
14
14
  import type {
15
15
  CryptoProvider,
16
16
  ClockProvider,
17
17
  NonceCacheProvider,
18
18
  FetchProvider,
19
- } from '../../providers/base.js';
20
- import type { DetachedProof } from '@kya-os/contracts/proof';
19
+ } from "../../providers/base.js";
20
+ import type { DetachedProof } from "@kya-os/contracts/proof";
21
21
  import {
22
22
  ProofVerificationError,
23
23
  PROOF_VERIFICATION_ERROR_CODES,
24
- } from '../errors.js';
25
- import { ProofGenerator } from '../../proof/generator.js';
24
+ } from "../errors.js";
25
+ import { ProofGenerator } from "../../proof/generator.js";
26
26
  // Cross-package relative import for a real Node crypto provider in tests —
27
27
  // same pattern already used by proof/__tests__/proof-generator.test.ts.
28
- import { NodeCryptoProvider } from '../../../../mcp-i/src/providers/node-providers';
28
+ import { NodeCryptoProvider } from "../../../../mcp-i/src/providers/node-providers";
29
29
 
30
- describe('ProofVerifier Security', () => {
30
+ describe("ProofVerifier Security", () => {
31
31
  let proofVerifier: ProofVerifier;
32
32
  let mockCryptoProvider: CryptoProvider;
33
33
  let mockClockProvider: ClockProvider;
@@ -36,49 +36,55 @@ describe('ProofVerifier Security', () => {
36
36
  let cryptoService: CryptoService;
37
37
 
38
38
  const validJwk: Ed25519JWK = {
39
- kty: 'OKP',
40
- crv: 'Ed25519',
41
- x: 'VCpo2LMLhn6iWku8MKvSLg2ZAoC-nlOyPVQaO3FxVeQ',
42
- kid: 'did:key:z123#key-1',
39
+ kty: "OKP",
40
+ crv: "Ed25519",
41
+ x: "VCpo2LMLhn6iWku8MKvSLg2ZAoC-nlOyPVQaO3FxVeQ",
42
+ kid: "did:key:z123#key-1",
43
43
  };
44
44
 
45
45
  const createValidProof = (): DetachedProof => {
46
46
  const header = {
47
- alg: 'EdDSA',
48
- typ: 'JWT',
49
- kid: 'did:key:z123#key-1',
47
+ alg: "EdDSA",
48
+ typ: "JWT",
49
+ kid: "did:key:z123#key-1",
50
50
  };
51
51
  // Create a proper JSON payload that matches the meta structure
52
52
  const payload = {
53
- aud: 'test-audience',
54
- sub: 'did:key:z123',
55
- iss: 'did:key:z123',
56
- nonce: 'nonce123',
53
+ aud: "test-audience",
54
+ sub: "did:key:z123",
55
+ iss: "did:key:z123",
56
+ nonce: "nonce123",
57
57
  ts: Math.floor(Date.now() / 1000),
58
- sessionId: 'session123',
59
- requestHash: 'sha256:' + 'a'.repeat(64),
60
- responseHash: 'sha256:' + 'b'.repeat(64),
58
+ sessionId: "session123",
59
+ requestHash: "sha256:" + "a".repeat(64),
60
+ responseHash: "sha256:" + "b".repeat(64),
61
61
  };
62
62
  // Use btoa for base64 encoding (available in test environment via polyfill)
63
63
  const headerB64 = btoa(JSON.stringify(header))
64
- .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
64
+ .replace(/\+/g, "-")
65
+ .replace(/\//g, "_")
66
+ .replace(/=/g, "");
65
67
  const payloadB64 = btoa(JSON.stringify(payload))
66
- .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
67
- const signatureB64 = btoa('signature')
68
- .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
68
+ .replace(/\+/g, "-")
69
+ .replace(/\//g, "_")
70
+ .replace(/=/g, "");
71
+ const signatureB64 = btoa("signature")
72
+ .replace(/\+/g, "-")
73
+ .replace(/\//g, "_")
74
+ .replace(/=/g, "");
69
75
  const jws = `${headerB64}.${payloadB64}.${signatureB64}`;
70
76
 
71
77
  return {
72
78
  jws,
73
79
  meta: {
74
- did: 'did:key:z123',
75
- kid: 'did:key:z123#key-1',
80
+ did: "did:key:z123",
81
+ kid: "did:key:z123#key-1",
76
82
  ts: Math.floor(Date.now() / 1000),
77
- nonce: 'nonce123',
78
- audience: 'test-audience',
79
- sessionId: 'session123',
80
- requestHash: 'sha256:' + 'a'.repeat(64),
81
- responseHash: 'sha256:' + 'b'.repeat(64),
83
+ nonce: "nonce123",
84
+ audience: "test-audience",
85
+ sessionId: "session123",
86
+ requestHash: "sha256:" + "a".repeat(64),
87
+ responseHash: "sha256:" + "b".repeat(64),
82
88
  },
83
89
  };
84
90
  };
@@ -98,7 +104,9 @@ describe('ProofVerifier Security', () => {
98
104
  now: vi.fn().mockReturnValue(Date.now()), // Return milliseconds
99
105
  isWithinSkew: vi.fn().mockReturnValue(true),
100
106
  hasExpired: vi.fn(),
101
- calculateExpiry: vi.fn((ttlSeconds: number) => Date.now() + (ttlSeconds * 1000)), // Return milliseconds
107
+ calculateExpiry: vi.fn(
108
+ (ttlSeconds: number) => Date.now() + ttlSeconds * 1000
109
+ ), // Return milliseconds
102
110
  format: vi.fn(),
103
111
  };
104
112
 
@@ -111,10 +119,12 @@ describe('ProofVerifier Security', () => {
111
119
 
112
120
  mockFetchProvider = {
113
121
  resolveDID: vi.fn().mockResolvedValue({
114
- verificationMethod: [{
115
- id: 'did:key:z123#key-1',
116
- publicKeyJwk: validJwk,
117
- }],
122
+ verificationMethod: [
123
+ {
124
+ id: "did:key:z123#key-1",
125
+ publicKeyJwk: validJwk,
126
+ },
127
+ ],
118
128
  }),
119
129
  fetchStatusList: vi.fn(),
120
130
  fetchDelegationChain: vi.fn(),
@@ -131,14 +141,17 @@ describe('ProofVerifier Security', () => {
131
141
  });
132
142
  });
133
143
 
134
- describe('Nonce Replay Protection', () => {
135
- it('should prevent nonce replay attacks', async () => {
144
+ describe("Nonce Replay Protection", () => {
145
+ it("should prevent nonce replay attacks", async () => {
136
146
  const proof = createValidProof();
137
147
 
138
148
  // First verification should succeed
139
149
  const result1 = await proofVerifier.verifyProof(proof, validJwk);
140
150
  expect(result1.valid).toBe(true);
141
- expect(mockNonceCache.has).toHaveBeenCalledWith('nonce123', 'did:key:z123');
151
+ expect(mockNonceCache.has).toHaveBeenCalledWith(
152
+ "nonce123",
153
+ "did:key:z123"
154
+ );
142
155
  expect(mockNonceCache.add).toHaveBeenCalled();
143
156
 
144
157
  // Reset mock to simulate second attempt
@@ -147,24 +160,24 @@ describe('ProofVerifier Security', () => {
147
160
  // Second verification with same nonce should fail
148
161
  const result2 = await proofVerifier.verifyProof(proof, validJwk);
149
162
  expect(result2.valid).toBe(false);
150
- expect(result2.reason).toContain('replay');
163
+ expect(result2.reason).toContain("replay");
151
164
  });
152
165
 
153
- it('should add nonce to cache after successful verification', async () => {
166
+ it("should add nonce to cache after successful verification", async () => {
154
167
  const proof = createValidProof();
155
168
 
156
169
  await proofVerifier.verifyProof(proof, validJwk);
157
170
 
158
171
  expect(mockNonceCache.add).toHaveBeenCalledWith(
159
- 'nonce123',
172
+ "nonce123",
160
173
  expect.any(Number),
161
- 'did:key:z123'
174
+ "did:key:z123"
162
175
  );
163
176
  });
164
177
  });
165
178
 
166
- describe('Timestamp Skew Validation', () => {
167
- it('should enforce timestamp skew limits', async () => {
179
+ describe("Timestamp Skew Validation", () => {
180
+ it("should enforce timestamp skew limits", async () => {
168
181
  const proof = createValidProof();
169
182
  const currentTime = Date.now(); // milliseconds
170
183
 
@@ -175,7 +188,7 @@ describe('ProofVerifier Security', () => {
175
188
  const result = await proofVerifier.verifyProof(proof, validJwk);
176
189
 
177
190
  expect(result.valid).toBe(false);
178
- expect(result.reason).toContain('skew');
191
+ expect(result.reason).toContain("skew");
179
192
  // isWithinSkew is called with timestamp in milliseconds (converted from seconds)
180
193
  expect(mockClockProvider.isWithinSkew).toHaveBeenCalledWith(
181
194
  proof.meta.ts * 1000, // Convert seconds to milliseconds
@@ -183,7 +196,7 @@ describe('ProofVerifier Security', () => {
183
196
  );
184
197
  });
185
198
 
186
- it('should accept timestamps within skew window', async () => {
199
+ it("should accept timestamps within skew window", async () => {
187
200
  const proof = createValidProof();
188
201
  mockClockProvider.isWithinSkew = vi.fn().mockReturnValue(true);
189
202
 
@@ -192,7 +205,7 @@ describe('ProofVerifier Security', () => {
192
205
  expect(result.valid).toBe(true);
193
206
  });
194
207
 
195
- it('should use custom timestamp skew seconds', async () => {
208
+ it("should use custom timestamp skew seconds", async () => {
196
209
  const customProofVerifier = new ProofVerifier({
197
210
  cryptoProvider: mockCryptoProvider,
198
211
  clockProvider: mockClockProvider,
@@ -215,8 +228,8 @@ describe('ProofVerifier Security', () => {
215
228
  });
216
229
  });
217
230
 
218
- describe('Canonical Payload Reconstruction', () => {
219
- it('should reconstruct canonical payload from meta', async () => {
231
+ describe("Canonical Payload Reconstruction", () => {
232
+ it("should reconstruct canonical payload from meta", async () => {
220
233
  const proof = createValidProof();
221
234
 
222
235
  await proofVerifier.verifyProof(proof, validJwk);
@@ -225,110 +238,120 @@ describe('ProofVerifier Security', () => {
225
238
  expect(mockCryptoProvider.verify).toHaveBeenCalled();
226
239
  });
227
240
 
228
- it('should validate canonical payload ordering determinism', () => {
241
+ it("should validate canonical payload ordering determinism", async () => {
229
242
  const meta1 = {
230
243
  z: 1,
231
244
  a: 2,
232
245
  m: 3,
233
- did: 'did:test',
234
- kid: 'kid',
246
+ did: "did:test",
247
+ kid: "kid",
235
248
  ts: 123,
236
- nonce: 'nonce',
237
- audience: 'aud',
238
- sessionId: 'session',
239
- requestHash: 'sha256:' + 'a'.repeat(64),
240
- responseHash: 'sha256:' + 'b'.repeat(64),
249
+ nonce: "nonce",
250
+ audience: "aud",
251
+ sessionId: "session",
252
+ requestHash: "sha256:" + "a".repeat(64),
253
+ responseHash: "sha256:" + "b".repeat(64),
241
254
  };
242
255
  const meta2 = {
243
256
  a: 2,
244
257
  m: 3,
245
258
  z: 1,
246
- did: 'did:test',
247
- kid: 'kid',
259
+ did: "did:test",
260
+ kid: "kid",
248
261
  ts: 123,
249
- nonce: 'nonce',
250
- audience: 'aud',
251
- sessionId: 'session',
252
- requestHash: 'sha256:' + 'a'.repeat(64),
253
- responseHash: 'sha256:' + 'b'.repeat(64),
262
+ nonce: "nonce",
263
+ audience: "aud",
264
+ sessionId: "session",
265
+ requestHash: "sha256:" + "a".repeat(64),
266
+ responseHash: "sha256:" + "b".repeat(64),
254
267
  };
255
268
 
256
- const canonical1 = proofVerifier.buildCanonicalPayload(meta1);
257
- const canonical2 = proofVerifier.buildCanonicalPayload(meta2);
269
+ const canonical1 = await proofVerifier.buildCanonicalPayload(meta1);
270
+ const canonical2 = await proofVerifier.buildCanonicalPayload(meta2);
258
271
 
259
272
  // Should be identical despite different key order
260
273
  expect(canonical1).toBe(canonical2);
261
274
  });
262
275
 
263
- it('omits toolName and outcome from the reconstructed payload when meta carries neither', () => {
276
+ it("omits outcome from the reconstructed payload when meta carries none", async () => {
264
277
  const meta = {
265
- did: 'did:test',
266
- kid: 'kid',
278
+ did: "did:test",
279
+ kid: "kid",
267
280
  ts: 123,
268
- nonce: 'nonce',
269
- audience: 'aud',
270
- sessionId: 'session',
271
- requestHash: 'sha256:' + 'a'.repeat(64),
272
- responseHash: 'sha256:' + 'b'.repeat(64),
281
+ nonce: "nonce",
282
+ audience: "aud",
283
+ sessionId: "session",
284
+ requestHash: "sha256:" + "a".repeat(64),
285
+ responseHash: "sha256:" + "b".repeat(64),
273
286
  };
274
287
 
275
- const canonical = JSON.parse(proofVerifier.buildCanonicalPayload(meta));
288
+ const canonical = JSON.parse(
289
+ await proofVerifier.buildCanonicalPayload(meta)
290
+ );
276
291
 
277
- expect(canonical).not.toHaveProperty('toolName');
278
- expect(canonical).not.toHaveProperty('outcome');
292
+ expect(canonical).not.toHaveProperty("outcome");
293
+ expect(canonical).not.toHaveProperty("toolName");
279
294
  });
280
295
 
281
- it('reconstructs the same fields a real ProofGenerator actually signs — regression guard for generator/verifier payload drift', async () => {
296
+ it("reconstructs byte-for-byte the payload a real ProofGenerator signs — regression guard for generator/verifier payload drift", async () => {
282
297
  const cryptoProvider = new NodeCryptoProvider();
283
298
  const keyPair = await cryptoProvider.generateKeyPair();
284
299
  const identity = {
285
- did: 'did:web:example.com:agents:sync-test',
286
- kid: 'did:web:example.com:agents:sync-test#key-1',
300
+ did: "did:web:example.com:agents:sync-test",
301
+ kid: "did:web:example.com:agents:sync-test#key-1",
287
302
  privateKey: keyPair.privateKey,
288
303
  publicKey: keyPair.publicKey,
289
304
  };
290
305
  const generator = new ProofGenerator(identity, cryptoProvider);
291
306
 
292
307
  const proof = await generator.generateProof(
293
- { method: 'test-tool', params: { input: 'hello' } },
294
- { data: { output: 'world' } },
308
+ { method: "test-tool", params: { input: "hello" } },
309
+ { data: { output: "world" } },
295
310
  {
296
- sessionId: 'sess-sync-test',
297
- audience: 'did:web:business.example',
298
- nonce: 'nonce-sync-test',
311
+ sessionId: "sess-sync-test",
312
+ audience: "did:web:business.example",
313
+ nonce: "nonce-sync-test",
299
314
  timestamp: Math.floor(Date.now() / 1000),
300
315
  createdAt: Math.floor(Date.now() / 1000),
301
316
  lastActivity: Math.floor(Date.now() / 1000),
302
317
  ttlMinutes: 30,
303
- identityState: 'anonymous',
318
+ identityState: "anonymous",
304
319
  } as never,
305
- { toolName: 'test-tool', submissionOutcome: 'success' }
320
+ {
321
+ outcome: "allowed",
322
+ toolName: "test-tool",
323
+ submissionOutcome: "success",
324
+ }
306
325
  );
307
326
 
308
- const actualPayload = JSON.parse(
309
- Buffer.from(proof.jws.split('.')[1]!, 'base64url').toString('utf8')
310
- );
311
- const reconstructedPayload = JSON.parse(
312
- proofVerifier.buildCanonicalPayload(proof.meta)
327
+ const signedPayload = Buffer.from(
328
+ proof.jws.split(".")[1]!,
329
+ "base64url"
330
+ ).toString("utf8");
331
+ const reconstructed = await proofVerifier.buildCanonicalPayload(
332
+ proof.meta
313
333
  );
314
334
 
315
- // Field-level equality (not byte/order equality — canonicalization
316
- // sorts keys, which the signed JWS payload does not). If the
317
- // reconstruction ever drifts from what generator.ts actually signs,
318
- // this fails long before it reaches a live 403. Covers toolName and
319
- // the submissionOutcome -> outcome rename too, since those are the
320
- // two newest fields most likely to drift out of lockstep.
321
- expect(reconstructedPayload).toEqual(actualPayload);
322
- expect(reconstructedPayload.toolName).toBe('test-tool');
323
- expect(reconstructedPayload.outcome).toBe('success');
335
+ // Byte equality (RFC 8785): if the reconstruction ever drifts from
336
+ // what the generator signs, this fails long before it reaches a live
337
+ // 403. toolName and submissionOutcome are xmcp-i-only meta members and
338
+ // must stay out of the signed payload.
339
+ expect(reconstructed).toBe(signedPayload);
340
+ const payload = JSON.parse(signedPayload) as Record<string, unknown>;
341
+ expect(payload.outcome).toBe("allowed");
342
+ expect(payload).not.toHaveProperty("toolName");
324
343
  });
325
344
 
326
- it('should handle detached JWS reconstruction', async () => {
327
- const header = { alg: 'EdDSA', kid: 'did:key:z123#key-1' };
345
+ it("should handle detached JWS reconstruction", async () => {
346
+ const header = { alg: "EdDSA", kid: "did:key:z123#key-1" };
328
347
  const headerB64 = btoa(JSON.stringify(header))
329
- .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
330
- const signatureB64 = btoa('signature')
331
- .replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
348
+ .replace(/\+/g, "-")
349
+ .replace(/\//g, "_")
350
+ .replace(/=/g, "");
351
+ const signatureB64 = btoa("signature")
352
+ .replace(/\+/g, "-")
353
+ .replace(/\//g, "_")
354
+ .replace(/=/g, "");
332
355
  const detachedJws = `${headerB64}..${signatureB64}`;
333
356
 
334
357
  const proof: DetachedProof = {
@@ -344,35 +367,35 @@ describe('ProofVerifier Security', () => {
344
367
  });
345
368
  });
346
369
 
347
- describe('Proof Structure Validation', () => {
348
- it('should reject invalid proof structure', async () => {
370
+ describe("Proof Structure Validation", () => {
371
+ it("should reject invalid proof structure", async () => {
349
372
  const invalidProof = {
350
- jws: 'invalid',
373
+ jws: "invalid",
351
374
  meta: {
352
375
  // Missing required fields
353
- did: 'did:test',
376
+ did: "did:test",
354
377
  },
355
378
  } as any;
356
379
 
357
380
  const result = await proofVerifier.verifyProof(invalidProof, validJwk);
358
381
 
359
382
  expect(result.valid).toBe(false);
360
- expect(result.reason).toContain('Invalid proof structure');
383
+ expect(result.reason).toContain("Invalid proof structure");
361
384
  });
362
385
 
363
- it('should reject proof with missing required meta fields', async () => {
386
+ it("should reject proof with missing required meta fields", async () => {
364
387
  const invalidProof: DetachedProof = {
365
- jws: 'header.payload.signature',
388
+ jws: "header.payload.signature",
366
389
  meta: {
367
- did: 'did:test',
368
- kid: 'kid',
390
+ did: "did:test",
391
+ kid: "kid",
369
392
  ts: 123,
370
- nonce: 'nonce',
371
- audience: 'aud',
372
- sessionId: 'session',
393
+ nonce: "nonce",
394
+ audience: "aud",
395
+ sessionId: "session",
373
396
  // Missing requestHash and responseHash
374
- requestHash: '' as any,
375
- responseHash: '' as any,
397
+ requestHash: "" as any,
398
+ responseHash: "" as any,
376
399
  },
377
400
  };
378
401
 
@@ -382,22 +405,22 @@ describe('ProofVerifier Security', () => {
382
405
  });
383
406
  });
384
407
 
385
- describe('Signature Verification', () => {
386
- it('should reject proof with invalid signature', async () => {
408
+ describe("Signature Verification", () => {
409
+ it("should reject proof with invalid signature", async () => {
387
410
  const proof = createValidProof();
388
411
  mockCryptoProvider.verify = vi.fn().mockResolvedValue(false);
389
412
 
390
413
  const result = await proofVerifier.verifyProof(proof, validJwk);
391
414
 
392
415
  expect(result.valid).toBe(false);
393
- expect(result.reason).toContain('Invalid JWS signature');
416
+ expect(result.reason).toContain("Invalid JWS signature");
394
417
  });
395
418
 
396
- it('should handle signature verification errors gracefully', async () => {
419
+ it("should handle signature verification errors gracefully", async () => {
397
420
  const proof = createValidProof();
398
- mockCryptoProvider.verify = vi.fn().mockRejectedValue(
399
- new Error('Crypto error')
400
- );
421
+ mockCryptoProvider.verify = vi
422
+ .fn()
423
+ .mockRejectedValue(new Error("Crypto error"));
401
424
 
402
425
  const result = await proofVerifier.verifyProof(proof, validJwk);
403
426
 
@@ -407,10 +430,12 @@ describe('ProofVerifier Security', () => {
407
430
  });
408
431
  });
409
432
 
410
- describe('verifyProofDetached', () => {
411
- it('should verify proof with string canonical payload', async () => {
433
+ describe("verifyProofDetached", () => {
434
+ it("should verify proof with string canonical payload", async () => {
412
435
  const proof = createValidProof();
413
- const canonicalPayload = proofVerifier.buildCanonicalPayload(proof.meta);
436
+ const canonicalPayload = await proofVerifier.buildCanonicalPayload(
437
+ proof.meta
438
+ );
414
439
 
415
440
  const result = await proofVerifier.verifyProofDetached(
416
441
  proof,
@@ -421,9 +446,11 @@ describe('ProofVerifier Security', () => {
421
446
  expect(result.valid).toBe(true);
422
447
  });
423
448
 
424
- it('should verify proof with Uint8Array canonical payload', async () => {
449
+ it("should verify proof with Uint8Array canonical payload", async () => {
425
450
  const proof = createValidProof();
426
- const canonicalPayload = proofVerifier.buildCanonicalPayload(proof.meta);
451
+ const canonicalPayload = await proofVerifier.buildCanonicalPayload(
452
+ proof.meta
453
+ );
427
454
  const canonicalPayloadBytes = new TextEncoder().encode(canonicalPayload);
428
455
 
429
456
  const result = await proofVerifier.verifyProofDetached(
@@ -435,9 +462,11 @@ describe('ProofVerifier Security', () => {
435
462
  expect(result.valid).toBe(true);
436
463
  });
437
464
 
438
- it('should prevent nonce replay in verifyProofDetached', async () => {
465
+ it("should prevent nonce replay in verifyProofDetached", async () => {
439
466
  const proof = createValidProof();
440
- const canonicalPayload = proofVerifier.buildCanonicalPayload(proof.meta);
467
+ const canonicalPayload = await proofVerifier.buildCanonicalPayload(
468
+ proof.meta
469
+ );
441
470
 
442
471
  // First verification
443
472
  const result1 = await proofVerifier.verifyProofDetached(
@@ -455,17 +484,17 @@ describe('ProofVerifier Security', () => {
455
484
  validJwk
456
485
  );
457
486
  expect(result2.valid).toBe(false);
458
- expect(result2.reason).toContain('replay');
487
+ expect(result2.reason).toContain("replay");
459
488
  });
460
489
  });
461
490
 
462
- describe('Error Handling', () => {
463
- it('should never throw on verification errors', async () => {
491
+ describe("Error Handling", () => {
492
+ it("should never throw on verification errors", async () => {
464
493
  const proof = createValidProof();
465
-
494
+
466
495
  // Simulate various error conditions
467
- mockNonceCache.has = vi.fn().mockRejectedValue(new Error('Cache error'));
468
-
496
+ mockNonceCache.has = vi.fn().mockRejectedValue(new Error("Cache error"));
497
+
469
498
  const result = await proofVerifier.verifyProof(proof, validJwk);
470
499
 
471
500
  // Should return error result, not throw
@@ -473,10 +502,10 @@ describe('ProofVerifier Security', () => {
473
502
  expect(result.reason).toBeDefined();
474
503
  });
475
504
 
476
- it('should handle clock provider errors gracefully', async () => {
505
+ it("should handle clock provider errors gracefully", async () => {
477
506
  const proof = createValidProof();
478
507
  mockClockProvider.isWithinSkew = vi.fn().mockImplementation(() => {
479
- throw new Error('Clock error');
508
+ throw new Error("Clock error");
480
509
  });
481
510
 
482
511
  const result = await proofVerifier.verifyProof(proof, validJwk);
@@ -486,13 +515,12 @@ describe('ProofVerifier Security', () => {
486
515
  });
487
516
  });
488
517
 
489
- describe('End-to-end verifyProof() with real crypto — regression guard for DIF payload drift', () => {
518
+ describe("End-to-end verifyProof() with real crypto — regression guard for DIF payload drift", () => {
490
519
  // Uses a REAL NodeCryptoProvider (unlike the mocked cryptoProvider used
491
520
  // elsewhere in this file, whose verify() always returns true and so
492
521
  // could never catch a signature mismatch). This is the only way to
493
522
  // prove verifyProof() itself -- not just buildCanonicalPayload() --
494
- // still accepts a proof signed with the literal did/kid/audience/
495
- // toolName/outcome fields once the DIF-delegated verifier is involved.
523
+ // still accepts a proof signed with the canonical @kya-os/mcp payload.
496
524
  function makeRealVerifier() {
497
525
  const cryptoProvider = new NodeCryptoProvider();
498
526
  const clockProvider: ClockProvider = {
@@ -513,7 +541,7 @@ describe('ProofVerifier Security', () => {
513
541
  fetchStatusList: async () => null,
514
542
  fetchDelegationChain: async () => null,
515
543
  fetch: async () => {
516
- throw new Error('not used');
544
+ throw new Error("not used");
517
545
  },
518
546
  };
519
547
  const verifier = new ProofVerifier({
@@ -526,71 +554,126 @@ describe('ProofVerifier Security', () => {
526
554
  }
527
555
 
528
556
  function toJwk(publicKeyBase64: string, kid: string): Ed25519JWK {
529
- const bytes = Buffer.from(publicKeyBase64, 'base64');
557
+ const bytes = Buffer.from(publicKeyBase64, "base64");
530
558
  const x = bytes
531
- .toString('base64')
532
- .replace(/\+/g, '-')
533
- .replace(/\//g, '_')
534
- .replace(/=/g, '');
535
- return { kty: 'OKP', crv: 'Ed25519', x, kid };
559
+ .toString("base64")
560
+ .replace(/\+/g, "-")
561
+ .replace(/\//g, "_")
562
+ .replace(/=/g, "");
563
+ return { kty: "OKP", crv: "Ed25519", x, kid };
536
564
  }
537
565
 
538
- it('accepts a proof signed with the literal did/kid/audience/toolName/outcome fields', async () => {
566
+ it("accepts a proof signed with the canonical @kya-os/mcp payload, with toolName/submissionOutcome riding unsigned on meta", async () => {
539
567
  const { cryptoProvider, verifier } = makeRealVerifier();
540
568
  const keyPair = await cryptoProvider.generateKeyPair();
541
569
  const identity = {
542
- did: 'did:web:example.com:agents:e2e-test',
543
- kid: 'did:web:example.com:agents:e2e-test#key-1',
570
+ did: "did:web:example.com:agents:e2e-test",
571
+ kid: "did:web:example.com:agents:e2e-test#key-1",
544
572
  privateKey: keyPair.privateKey,
545
573
  publicKey: keyPair.publicKey,
546
574
  };
547
575
  const generator = new ProofGenerator(identity, cryptoProvider);
548
576
 
549
577
  const proof = await generator.generateProof(
550
- { method: 'test-tool', params: { input: 'hello' } },
551
- { data: { output: 'world' } },
578
+ { method: "test-tool", params: { input: "hello" } },
579
+ { data: { output: "world" } },
552
580
  {
553
- sessionId: 'sess-e2e-test',
554
- audience: 'did:web:business.example',
555
- nonce: 'nonce-e2e-test',
581
+ sessionId: "sess-e2e-test",
582
+ audience: "did:web:business.example",
583
+ nonce: "nonce-e2e-test",
556
584
  timestamp: Math.floor(Date.now() / 1000),
557
585
  createdAt: Math.floor(Date.now() / 1000),
558
586
  lastActivity: Math.floor(Date.now() / 1000),
559
587
  ttlMinutes: 30,
560
- identityState: 'anonymous',
588
+ identityState: "anonymous",
561
589
  } as never,
562
- { toolName: 'get_weather', submissionOutcome: 'success' }
590
+ {
591
+ outcome: "allowed",
592
+ toolName: "get_weather",
593
+ submissionOutcome: "success",
594
+ }
563
595
  );
564
596
 
565
597
  const publicKeyJwk = toJwk(identity.publicKey, identity.kid);
566
598
  const result = await verifier.verifyProof(proof, publicKeyJwk);
567
599
 
568
600
  expect(result.valid).toBe(true);
601
+
602
+ // The unsigned members can be changed without touching the signature,
603
+ // but a signed claim (the authorization outcome) cannot.
604
+ const retagged = {
605
+ ...proof,
606
+ meta: {
607
+ ...proof.meta,
608
+ toolName: "other_tool",
609
+ submissionOutcome: "failure" as const,
610
+ },
611
+ };
612
+ expect((await verifier.verifyProof(retagged, publicKeyJwk)).valid).toBe(
613
+ true
614
+ );
569
615
  });
570
616
 
571
- it('also accepts a proof signed WITHOUT toolName/outcome (PR651-era fields only)', async () => {
617
+ it("rejects a proof whose signed authorization outcome was altered on meta", async () => {
572
618
  const { cryptoProvider, verifier } = makeRealVerifier();
573
619
  const keyPair = await cryptoProvider.generateKeyPair();
574
620
  const identity = {
575
- did: 'did:web:example.com:agents:e2e-test-2',
576
- kid: 'did:web:example.com:agents:e2e-test-2#key-1',
621
+ did: "did:web:example.com:agents:e2e-test-3",
622
+ kid: "did:web:example.com:agents:e2e-test-3#key-1",
577
623
  privateKey: keyPair.privateKey,
578
624
  publicKey: keyPair.publicKey,
579
625
  };
580
626
  const generator = new ProofGenerator(identity, cryptoProvider);
581
627
 
582
628
  const proof = await generator.generateProof(
583
- { method: 'test-tool', params: { input: 'hello' } },
584
- { data: { output: 'world' } },
629
+ { method: "test-tool", params: { input: "hello" } },
630
+ { data: { output: "world" } },
585
631
  {
586
- sessionId: 'sess-e2e-test-2',
587
- audience: 'did:web:business.example',
588
- nonce: 'nonce-e2e-test-2',
632
+ sessionId: "sess-e2e-test-3",
633
+ audience: "did:web:business.example",
634
+ nonce: "nonce-e2e-test-3",
589
635
  timestamp: Math.floor(Date.now() / 1000),
590
636
  createdAt: Math.floor(Date.now() / 1000),
591
637
  lastActivity: Math.floor(Date.now() / 1000),
592
638
  ttlMinutes: 30,
593
- identityState: 'anonymous',
639
+ identityState: "anonymous",
640
+ } as never,
641
+ { outcome: "allowed" }
642
+ );
643
+
644
+ const publicKeyJwk = toJwk(identity.publicKey, identity.kid);
645
+ const tampered = {
646
+ ...proof,
647
+ meta: { ...proof.meta, outcome: "denied" as const },
648
+ };
649
+ const result = await verifier.verifyProof(tampered, publicKeyJwk);
650
+
651
+ expect(result.valid).toBe(false);
652
+ });
653
+
654
+ it("also accepts a proof signed WITHOUT an outcome, toolName or submissionOutcome", async () => {
655
+ const { cryptoProvider, verifier } = makeRealVerifier();
656
+ const keyPair = await cryptoProvider.generateKeyPair();
657
+ const identity = {
658
+ did: "did:web:example.com:agents:e2e-test-2",
659
+ kid: "did:web:example.com:agents:e2e-test-2#key-1",
660
+ privateKey: keyPair.privateKey,
661
+ publicKey: keyPair.publicKey,
662
+ };
663
+ const generator = new ProofGenerator(identity, cryptoProvider);
664
+
665
+ const proof = await generator.generateProof(
666
+ { method: "test-tool", params: { input: "hello" } },
667
+ { data: { output: "world" } },
668
+ {
669
+ sessionId: "sess-e2e-test-2",
670
+ audience: "did:web:business.example",
671
+ nonce: "nonce-e2e-test-2",
672
+ timestamp: Math.floor(Date.now() / 1000),
673
+ createdAt: Math.floor(Date.now() / 1000),
674
+ lastActivity: Math.floor(Date.now() / 1000),
675
+ ttlMinutes: 30,
676
+ identityState: "anonymous",
594
677
  } as never
595
678
  );
596
679
 
@@ -601,23 +684,26 @@ describe('ProofVerifier Security', () => {
601
684
  });
602
685
  });
603
686
 
604
- describe('fetchPublicKeyFromDID', () => {
605
- it('should fetch public key from DID document', async () => {
606
- const jwk = await proofVerifier.fetchPublicKeyFromDID('did:key:z123', 'key-1');
687
+ describe("fetchPublicKeyFromDID", () => {
688
+ it("should fetch public key from DID document", async () => {
689
+ const jwk = await proofVerifier.fetchPublicKeyFromDID(
690
+ "did:key:z123",
691
+ "key-1"
692
+ );
607
693
 
608
694
  expect(jwk).toEqual(validJwk);
609
- expect(mockFetchProvider.resolveDID).toHaveBeenCalledWith('did:key:z123');
695
+ expect(mockFetchProvider.resolveDID).toHaveBeenCalledWith("did:key:z123");
610
696
  });
611
697
 
612
- it('should throw ProofVerificationError if DID document not found', async () => {
698
+ it("should throw ProofVerificationError if DID document not found", async () => {
613
699
  mockFetchProvider.resolveDID = vi.fn().mockResolvedValue(null);
614
700
 
615
701
  await expect(
616
- proofVerifier.fetchPublicKeyFromDID('did:key:z123')
702
+ proofVerifier.fetchPublicKeyFromDID("did:key:z123")
617
703
  ).rejects.toThrow(ProofVerificationError);
618
704
 
619
705
  try {
620
- await proofVerifier.fetchPublicKeyFromDID('did:key:z123');
706
+ await proofVerifier.fetchPublicKeyFromDID("did:key:z123");
621
707
  } catch (error) {
622
708
  expect(error).toBeInstanceOf(ProofVerificationError);
623
709
  expect((error as ProofVerificationError).code).toBe(
@@ -626,17 +712,17 @@ describe('ProofVerifier Security', () => {
626
712
  }
627
713
  });
628
714
 
629
- it('should throw ProofVerificationError if verification method not found', async () => {
715
+ it("should throw ProofVerificationError if verification method not found", async () => {
630
716
  mockFetchProvider.resolveDID = vi.fn().mockResolvedValue({
631
717
  verificationMethod: [],
632
718
  });
633
719
 
634
720
  await expect(
635
- proofVerifier.fetchPublicKeyFromDID('did:key:z123', 'key-1')
721
+ proofVerifier.fetchPublicKeyFromDID("did:key:z123", "key-1")
636
722
  ).rejects.toThrow(ProofVerificationError);
637
723
 
638
724
  try {
639
- await proofVerifier.fetchPublicKeyFromDID('did:key:z123', 'key-1');
725
+ await proofVerifier.fetchPublicKeyFromDID("did:key:z123", "key-1");
640
726
  } catch (error) {
641
727
  expect(error).toBeInstanceOf(ProofVerificationError);
642
728
  expect((error as ProofVerificationError).code).toBe(
@@ -645,24 +731,26 @@ describe('ProofVerifier Security', () => {
645
731
  }
646
732
  });
647
733
 
648
- it('should throw ProofVerificationError if JWK is not Ed25519', async () => {
734
+ it("should throw ProofVerificationError if JWK is not Ed25519", async () => {
649
735
  mockFetchProvider.resolveDID = vi.fn().mockResolvedValue({
650
- verificationMethod: [{
651
- id: 'did:key:z123#key-1',
652
- publicKeyJwk: {
653
- kty: 'RSA',
654
- crv: 'RS256',
655
- n: 'invalid',
736
+ verificationMethod: [
737
+ {
738
+ id: "did:key:z123#key-1",
739
+ publicKeyJwk: {
740
+ kty: "RSA",
741
+ crv: "RS256",
742
+ n: "invalid",
743
+ },
656
744
  },
657
- }],
745
+ ],
658
746
  });
659
747
 
660
748
  await expect(
661
- proofVerifier.fetchPublicKeyFromDID('did:key:z123')
749
+ proofVerifier.fetchPublicKeyFromDID("did:key:z123")
662
750
  ).rejects.toThrow(ProofVerificationError);
663
751
 
664
752
  try {
665
- await proofVerifier.fetchPublicKeyFromDID('did:key:z123');
753
+ await proofVerifier.fetchPublicKeyFromDID("did:key:z123");
666
754
  } catch (error) {
667
755
  expect(error).toBeInstanceOf(ProofVerificationError);
668
756
  expect((error as ProofVerificationError).code).toBe(