@kya-os/mcp-i-runtime 1.3.1 → 1.3.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 (122) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/auth/handshake.d.ts +23 -43
  3. package/dist/auth/handshake.d.ts.map +1 -1
  4. package/dist/auth/handshake.js +51 -82
  5. package/dist/auth/handshake.js.map +1 -1
  6. package/dist/auth/index.d.ts +1 -1
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js.map +1 -1
  9. package/dist/auth/resume-token.d.ts +52 -0
  10. package/dist/auth/resume-token.d.ts.map +1 -0
  11. package/dist/auth/resume-token.js +89 -0
  12. package/dist/auth/resume-token.js.map +1 -0
  13. package/dist/auth/types.d.ts +15 -0
  14. package/dist/auth/types.d.ts.map +1 -1
  15. package/dist/index.d.ts +7 -3
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +25 -3
  18. package/dist/index.js.map +1 -1
  19. package/dist/proof/companion.d.ts +25 -0
  20. package/dist/proof/companion.d.ts.map +1 -0
  21. package/dist/proof/companion.js +14 -0
  22. package/dist/proof/companion.js.map +1 -0
  23. package/dist/proof/generator.d.ts +22 -9
  24. package/dist/proof/generator.d.ts.map +1 -1
  25. package/dist/proof/generator.js +20 -27
  26. package/dist/proof/generator.js.map +1 -1
  27. package/dist/proof/index.d.ts +2 -1
  28. package/dist/proof/index.d.ts.map +1 -1
  29. package/dist/proof/index.js +3 -1
  30. package/dist/proof/index.js.map +1 -1
  31. package/dist/runtime/audit.d.ts.map +1 -1
  32. package/dist/runtime/audit.js +78 -18
  33. package/dist/runtime/audit.js.map +1 -1
  34. package/dist/runtime/base.d.ts +6 -1
  35. package/dist/runtime/base.d.ts.map +1 -1
  36. package/dist/runtime/base.js +65 -17
  37. package/dist/runtime/base.js.map +1 -1
  38. package/dist/runtime/dif-core.d.ts +8 -0
  39. package/dist/runtime/dif-core.d.ts.map +1 -1
  40. package/dist/runtime/dif-core.js +10 -0
  41. package/dist/runtime/dif-core.js.map +1 -1
  42. package/dist/services/access-control.service.d.ts.map +1 -1
  43. package/dist/services/access-control.service.js +12 -5
  44. package/dist/services/access-control.service.js.map +1 -1
  45. package/dist/services/claims-first-guard.d.ts +33 -0
  46. package/dist/services/claims-first-guard.d.ts.map +1 -0
  47. package/dist/services/claims-first-guard.js +77 -0
  48. package/dist/services/claims-first-guard.js.map +1 -0
  49. package/dist/services/holder-keys.d.ts +95 -0
  50. package/dist/services/holder-keys.d.ts.map +1 -0
  51. package/dist/services/holder-keys.js +281 -0
  52. package/dist/services/holder-keys.js.map +1 -0
  53. package/dist/services/holder-read-slots.d.ts +42 -0
  54. package/dist/services/holder-read-slots.d.ts.map +1 -0
  55. package/dist/services/holder-read-slots.js +82 -0
  56. package/dist/services/holder-read-slots.js.map +1 -0
  57. package/dist/services/proof-verifier.d.ts +13 -35
  58. package/dist/services/proof-verifier.d.ts.map +1 -1
  59. package/dist/services/proof-verifier.js +16 -74
  60. package/dist/services/proof-verifier.js.map +1 -1
  61. package/dist/services/request-holder.d.ts +78 -0
  62. package/dist/services/request-holder.d.ts.map +1 -0
  63. package/dist/services/request-holder.js +81 -0
  64. package/dist/services/request-holder.js.map +1 -0
  65. package/dist/services/tool-context-builder.d.ts.map +1 -1
  66. package/dist/services/tool-context-builder.js +16 -4
  67. package/dist/services/tool-context-builder.js.map +1 -1
  68. package/dist/services/tool-protection.service.d.ts +7 -0
  69. package/dist/services/tool-protection.service.d.ts.map +1 -1
  70. package/dist/services/tool-protection.service.js +34 -15
  71. package/dist/services/tool-protection.service.js.map +1 -1
  72. package/dist/types/tool-protection.d.ts +94 -0
  73. package/dist/types/tool-protection.d.ts.map +1 -1
  74. package/dist/types/tool-protection.js +113 -1
  75. package/dist/types/tool-protection.js.map +1 -1
  76. package/eslint.config.js +20 -0
  77. package/package.json +8 -2
  78. package/src/__tests__/runtime/amount-limit-enforcement.test.ts +269 -0
  79. package/src/__tests__/runtime/amount-limit-result.test.ts +61 -0
  80. package/src/__tests__/runtime/audit-contracts-compat.test.ts +20 -5
  81. package/src/__tests__/runtime/audit.test.ts +363 -53
  82. package/src/__tests__/runtime/process-tool-call-security.test.ts +97 -13
  83. package/src/__tests__/runtime/provider-selection.test.ts +4 -6
  84. package/src/__tests__/runtime/route-interception.test.ts +215 -214
  85. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +89 -6
  86. package/src/__tests__/services/tool-protection-amount.test.ts +107 -0
  87. package/src/__tests__/services/tool-protection-failsafe.test.ts +71 -4
  88. package/src/__tests__/utils/tool-protection-runtime.ts +3 -0
  89. package/src/auth/__tests__/verify-or-hints-presented.test.ts +155 -0
  90. package/src/auth/handshake.ts +80 -125
  91. package/src/auth/index.ts +1 -0
  92. package/src/auth/resume-token.ts +134 -0
  93. package/src/auth/types.ts +20 -2
  94. package/src/index.ts +40 -1
  95. package/src/proof/__tests__/proof-generator.test.ts +80 -13
  96. package/src/proof/companion.ts +35 -0
  97. package/src/proof/generator.ts +51 -33
  98. package/src/proof/index.ts +3 -0
  99. package/src/runtime/__tests__/ext-apps-consent.test.ts +87 -2
  100. package/src/runtime/audit.ts +170 -65
  101. package/src/runtime/base.ts +95 -31
  102. package/src/runtime/dif-core.ts +16 -0
  103. package/src/services/__tests__/access-control.service.test.ts +44 -0
  104. package/src/services/__tests__/claims-first-guard.test.ts +93 -0
  105. package/src/services/__tests__/holder-fixtures.ts +135 -0
  106. package/src/services/__tests__/holder-keys.test.ts +257 -0
  107. package/src/services/__tests__/holder-read-slots.test.ts +117 -0
  108. package/src/services/__tests__/holder-reads.test.ts +284 -0
  109. package/src/services/__tests__/proof-verifier.test.ts +286 -195
  110. package/src/services/__tests__/request-holder.test.ts +210 -0
  111. package/src/services/__tests__/tool-context-builder-authtype.test.ts +79 -0
  112. package/src/services/__tests__/tool-context-builder.test.ts +4 -7
  113. package/src/services/__tests__/tool-protection-served-revision.test.ts +102 -0
  114. package/src/services/access-control.service.ts +11 -5
  115. package/src/services/claims-first-guard.ts +89 -0
  116. package/src/services/holder-keys.ts +379 -0
  117. package/src/services/holder-read-slots.ts +85 -0
  118. package/src/services/proof-verifier.ts +18 -79
  119. package/src/services/request-holder.ts +146 -0
  120. package/src/services/tool-context-builder.ts +19 -4
  121. package/src/services/tool-protection.service.ts +62 -19
  122. package/src/types/tool-protection.ts +161 -0
@@ -23,8 +23,14 @@ import {
23
23
  import { DelegationRecord } from "@kya-os/contracts/delegation";
24
24
  import { logger } from "../logging";
25
25
  import { DelegationVerifier, VerifyDelegationResult } from "./types";
26
+ import type { ResumeTokenStore } from "./resume-token";
26
27
 
27
28
  export type { DelegationVerifier, VerifyDelegationResult };
29
+ export {
30
+ generateResumeToken,
31
+ MemoryResumeTokenStore,
32
+ type ResumeTokenStore,
33
+ } from "./resume-token";
28
34
 
29
35
  /**
30
36
  * Agent reputation data from KTA
@@ -95,147 +101,57 @@ export interface VerifyOrHintsResult {
95
101
  authError?: NeedsAuthorizationError;
96
102
  reputation?: AgentReputation;
97
103
  reason?: string;
104
+ /** The code the delegation verifier refused with, when it names one. */
105
+ code?: string;
98
106
  }
99
107
 
100
108
  /**
101
- * Resume token store interface
109
+ * Options for {@link verifyOrHints}.
102
110
  */
103
- export interface ResumeTokenStore {
104
- create(
105
- agentDid: string,
106
- scopes: string[],
107
- metadata?: Record<string, unknown>
108
- ): Promise<string>;
109
-
110
- get(token: string): Promise<{
111
- agentDid: string;
112
- scopes: string[];
113
- createdAt: number;
114
- expiresAt: number;
115
- metadata?: Record<string, unknown>;
116
- } | null>;
117
-
118
- fulfill(token: string): Promise<void>;
119
- }
120
-
121
- /**
122
- * Mint a capability-bearing resume token with CSPRNG entropy.
123
- *
124
- * Format: `${prefix}_${hex(16 random bytes)}` (128 bits). Uses Web Crypto
125
- * `getRandomValues` (Node 18+, Cloudflare Workers, browsers), falling back to
126
- * `randomUUID` — both CSPRNG. Replaces the prior `Date.now()_Math.random()`
127
- * form, which leaked creation time and had weak uniqueness/guessability for a
128
- * token that grants delegated access. No Node-specific imports (Buffer-free),
129
- * so it stays safe on every fetch-capable runtime.
130
- */
131
- export function generateResumeToken(prefix = "rt"): string {
132
- if (typeof crypto !== "undefined" && crypto.getRandomValues) {
133
- const bytes = new Uint8Array(16);
134
- crypto.getRandomValues(bytes);
135
- let hex = "";
136
- for (let i = 0; i < bytes.length; i++) {
137
- hex += bytes[i].toString(16).padStart(2, "0");
138
- }
139
- return `${prefix}_${hex}`;
140
- }
141
- if (typeof crypto !== "undefined" && crypto.randomUUID) {
142
- return `${prefix}_${crypto.randomUUID().replace(/-/g, "")}`;
143
- }
144
- throw new Error("CSPRNG unavailable: cannot mint resume token");
111
+ export interface VerifyOrHintsOptions {
112
+ /**
113
+ * Authorize on a presented delegation only. `agentDid` is then the holder
114
+ * the call proved it holds the key of, never a DID the caller merely
115
+ * named, and `credential` the delegation credential the call presents
116
+ * (absent when it presents none, which asks for authorization). The
117
+ * verifier's `verifyPresented` decides; nothing is looked up for the agent.
118
+ */
119
+ presented?: { credential?: string };
145
120
  }
146
121
 
147
- /**
148
- * Simple in-memory resume token store (for testing/development).
149
- * Not suitable for multi-instance deployments.
150
- */
151
- export class MemoryResumeTokenStore implements ResumeTokenStore {
152
- private tokens = new Map<
153
- string,
154
- {
155
- agentDid: string;
156
- scopes: string[];
157
- createdAt: number;
158
- expiresAt: number;
159
- metadata?: Record<string, unknown>;
160
- fulfilled: boolean;
161
- }
162
- >();
163
- private ttl: number;
164
-
165
- constructor(ttlMs = 600_000) {
166
- this.ttl = ttlMs;
167
- }
168
-
169
- async create(
170
- agentDid: string,
171
- scopes: string[],
172
- metadata?: Record<string, unknown>
173
- ): Promise<string> {
174
- const token = generateResumeToken("rt");
175
- const now = Date.now();
176
-
177
- this.tokens.set(token, {
178
- agentDid,
179
- scopes,
180
- createdAt: now,
181
- expiresAt: now + this.ttl,
182
- metadata,
183
- fulfilled: false,
184
- });
185
-
186
- return token;
187
- }
188
-
189
- async get(token: string): Promise<{
190
- agentDid: string;
191
- scopes: string[];
192
- createdAt: number;
193
- expiresAt: number;
194
- metadata?: Record<string, unknown>;
195
- } | null> {
196
- const data = this.tokens.get(token);
197
- if (!data) return null;
198
-
199
- if (Date.now() > data.expiresAt) {
200
- this.tokens.delete(token);
201
- return null;
202
- }
203
-
204
- if (data.fulfilled) return null;
205
-
206
- return {
207
- agentDid: data.agentDid,
208
- scopes: data.scopes,
209
- createdAt: data.createdAt,
210
- expiresAt: data.expiresAt,
211
- metadata: data.metadata,
212
- };
213
- }
214
-
215
- async fulfill(token: string): Promise<void> {
216
- const data = this.tokens.get(token);
217
- if (data) {
218
- data.fulfilled = true;
219
- }
220
- }
221
-
222
- clear(): void {
223
- this.tokens.clear();
224
- }
122
+ let warnedOfNamedDid = false;
123
+
124
+ /** Say once that a delegation is being looked up for a DID nothing proved here. */
125
+ function warnOfNamedDid(): void {
126
+ if (warnedOfNamedDid) return;
127
+ warnedOfNamedDid = true;
128
+ logger.warn(
129
+ "[AuthHandshake] verifyOrHints was called without options.presented, so it authorizes on a " +
130
+ "delegation looked up for the DID it was given, which nothing here proved. Pass the " +
131
+ "holder a call's request proof shows as agentDid and the delegation the call presents as " +
132
+ "options.presented."
133
+ );
225
134
  }
226
135
 
227
136
  /**
228
137
  * Main auth handshake function.
229
138
  *
230
- * Verifies agent authorization or returns authorization hints.
139
+ * Verifies agent authorization or returns authorization hints. With
140
+ * `options.presented` it authorizes only on the delegation a call presents,
141
+ * for the holder the call proved, which is how every protected call is
142
+ * checked. Without it, it looks a delegation up for `agentDid`: the caller
143
+ * must have established that DID itself, a DID a client only names
144
+ * authorizes whoever names it, and the first such call logs a warning.
231
145
  */
232
146
  export async function verifyOrHints(
233
147
  agentDid: string,
234
148
  scopes: string[],
235
149
  config: AuthHandshakeConfig,
236
- _resumeToken?: string
150
+ _resumeToken?: string,
151
+ options: VerifyOrHintsOptions = {}
237
152
  ): Promise<VerifyOrHintsResult> {
238
153
  const startTime = Date.now();
154
+ if (!options.presented) warnOfNamedDid();
239
155
 
240
156
  if (config.debug) {
241
157
  logger.debug(
@@ -281,7 +197,14 @@ export async function verifyOrHints(
281
197
  let delegationResult: VerifyDelegationResult;
282
198
 
283
199
  try {
284
- delegationResult = await config.delegationVerifier.verify(agentDid, scopes);
200
+ delegationResult = options.presented
201
+ ? await verifyPresentedDelegation(
202
+ config.delegationVerifier,
203
+ options.presented.credential,
204
+ agentDid,
205
+ scopes
206
+ )
207
+ : await config.delegationVerifier.verify(agentDid, scopes);
285
208
  } catch (error) {
286
209
  logger.error("[AuthHandshake] Delegation verification failed:", error);
287
210
  const errorMessage = `Delegation verification error: ${error instanceof Error ? error.message : "Unknown error"}`;
@@ -300,7 +223,15 @@ export async function verifyOrHints(
300
223
  };
301
224
  }
302
225
 
303
- if (delegationResult.valid && delegationResult.delegation) {
226
+ // A presented credential the verifier accepted is authority even when no
227
+ // stored record stands behind it (a credential-only decision).
228
+ const accepted =
229
+ delegationResult.valid &&
230
+ (delegationResult.delegation !== undefined ||
231
+ (options.presented !== undefined &&
232
+ delegationResult.credential !== undefined));
233
+
234
+ if (accepted) {
304
235
  if (config.debug) {
305
236
  logger.debug(
306
237
  `[AuthHandshake] Delegation valid, authorized (${Date.now() - startTime}ms)`
@@ -334,9 +265,33 @@ export async function verifyOrHints(
334
265
  authError,
335
266
  reputation,
336
267
  reason: delegationResult.reason ?? "No delegation",
268
+ ...(delegationResult.code ? { code: delegationResult.code } : {}),
337
269
  };
338
270
  }
339
271
 
272
+ /**
273
+ * Verify the delegation a call presents, for the holder it proved. Refused,
274
+ * never looked up, when the call presents none or the verifier cannot check
275
+ * a presented credential.
276
+ */
277
+ async function verifyPresentedDelegation(
278
+ verifier: DelegationVerifier,
279
+ credential: string | undefined,
280
+ holderDid: string,
281
+ scopes: string[]
282
+ ): Promise<VerifyDelegationResult> {
283
+ if (!credential) {
284
+ return { valid: false, reason: "No delegation presented" };
285
+ }
286
+ if (!verifier.verifyPresented) {
287
+ return {
288
+ valid: false,
289
+ reason: "The delegation verifier cannot verify a presented delegation",
290
+ };
291
+ }
292
+ return verifier.verifyPresented(credential, holderDid, scopes);
293
+ }
294
+
340
295
  /**
341
296
  * Fetch agent reputation from KTA.
342
297
  */
package/src/auth/index.ts CHANGED
@@ -7,6 +7,7 @@ export {
7
7
  MemoryResumeTokenStore,
8
8
  generateResumeToken,
9
9
  type AuthHandshakeConfig,
10
+ type VerifyOrHintsOptions,
10
11
  type VerifyOrHintsResult,
11
12
  type AgentReputation,
12
13
  type ResumeTokenStore,
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Resume tokens: what a needs-authorization answer carries for the client
3
+ * to resume with once the user has authorized, and the store that keeps
4
+ * them. Platform-agnostic, like ./handshake, which mints them.
5
+ *
6
+ * @module auth/resume-token
7
+ */
8
+
9
+ /**
10
+ * Resume token store interface
11
+ */
12
+ export interface ResumeTokenStore {
13
+ create(
14
+ agentDid: string,
15
+ scopes: string[],
16
+ metadata?: Record<string, unknown>
17
+ ): Promise<string>;
18
+
19
+ get(token: string): Promise<{
20
+ agentDid: string;
21
+ scopes: string[];
22
+ createdAt: number;
23
+ expiresAt: number;
24
+ metadata?: Record<string, unknown>;
25
+ } | null>;
26
+
27
+ fulfill(token: string): Promise<void>;
28
+ }
29
+
30
+ /**
31
+ * Mint a capability-bearing resume token with CSPRNG entropy.
32
+ *
33
+ * Format: `${prefix}_${hex(16 random bytes)}` (128 bits). Uses Web Crypto
34
+ * `getRandomValues` (Node 18+, Cloudflare Workers, browsers), falling back to
35
+ * `randomUUID`: both CSPRNG. Replaces the prior `Date.now()_Math.random()`
36
+ * form, which leaked creation time and had weak uniqueness/guessability for a
37
+ * token that grants delegated access. No Node-specific imports (Buffer-free),
38
+ * so it stays safe on every fetch-capable runtime.
39
+ */
40
+ export function generateResumeToken(prefix = "rt"): string {
41
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
42
+ const bytes = new Uint8Array(16);
43
+ crypto.getRandomValues(bytes);
44
+ let hex = "";
45
+ for (let i = 0; i < bytes.length; i++) {
46
+ hex += bytes[i].toString(16).padStart(2, "0");
47
+ }
48
+ return `${prefix}_${hex}`;
49
+ }
50
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
51
+ return `${prefix}_${crypto.randomUUID().replace(/-/g, "")}`;
52
+ }
53
+ throw new Error("CSPRNG unavailable: cannot mint resume token");
54
+ }
55
+
56
+ /**
57
+ * Simple in-memory resume token store (for testing/development).
58
+ * Not suitable for multi-instance deployments.
59
+ */
60
+ export class MemoryResumeTokenStore implements ResumeTokenStore {
61
+ private tokens = new Map<
62
+ string,
63
+ {
64
+ agentDid: string;
65
+ scopes: string[];
66
+ createdAt: number;
67
+ expiresAt: number;
68
+ metadata?: Record<string, unknown>;
69
+ fulfilled: boolean;
70
+ }
71
+ >();
72
+ private ttl: number;
73
+
74
+ constructor(ttlMs = 600_000) {
75
+ this.ttl = ttlMs;
76
+ }
77
+
78
+ async create(
79
+ agentDid: string,
80
+ scopes: string[],
81
+ metadata?: Record<string, unknown>
82
+ ): Promise<string> {
83
+ const token = generateResumeToken("rt");
84
+ const now = Date.now();
85
+
86
+ this.tokens.set(token, {
87
+ agentDid,
88
+ scopes,
89
+ createdAt: now,
90
+ expiresAt: now + this.ttl,
91
+ metadata,
92
+ fulfilled: false,
93
+ });
94
+
95
+ return token;
96
+ }
97
+
98
+ async get(token: string): Promise<{
99
+ agentDid: string;
100
+ scopes: string[];
101
+ createdAt: number;
102
+ expiresAt: number;
103
+ metadata?: Record<string, unknown>;
104
+ } | null> {
105
+ const data = this.tokens.get(token);
106
+ if (!data) return null;
107
+
108
+ if (Date.now() > data.expiresAt) {
109
+ this.tokens.delete(token);
110
+ return null;
111
+ }
112
+
113
+ if (data.fulfilled) return null;
114
+
115
+ return {
116
+ agentDid: data.agentDid,
117
+ scopes: data.scopes,
118
+ createdAt: data.createdAt,
119
+ expiresAt: data.expiresAt,
120
+ metadata: data.metadata,
121
+ };
122
+ }
123
+
124
+ async fulfill(token: string): Promise<void> {
125
+ const data = this.tokens.get(token);
126
+ if (data) {
127
+ data.fulfilled = true;
128
+ }
129
+ }
130
+
131
+ clear(): void {
132
+ this.tokens.clear();
133
+ }
134
+ }
package/src/auth/types.ts CHANGED
@@ -52,6 +52,12 @@ export interface VerifyDelegationResult {
52
52
  /** Reason for invalid result */
53
53
  reason?: string;
54
54
 
55
+ /**
56
+ * The code the verifier refused with, when it names one (Checkpoint's
57
+ * `error.code`, such as `holder_proof_required`).
58
+ */
59
+ code?: string;
60
+
55
61
  /** Whether result came from cache */
56
62
  cached?: boolean;
57
63
  }
@@ -61,8 +67,20 @@ export interface VerifyDelegationResult {
61
67
  * Concrete implementations live in packages/mcp-i (CheckpointAPIDelegationVerifier, etc.).
62
68
  */
63
69
  export interface DelegationVerifier {
64
- verify(
65
- agentDid: string,
70
+ verify(agentDid: string, scopes: string[]): Promise<VerifyDelegationResult>;
71
+
72
+ /**
73
+ * Verify the delegation credential a call presents, for the holder that
74
+ * call proved it holds the key of. Valid only when the credential is
75
+ * authority this verifier accepts, names `holderDid` as its subject and
76
+ * grants every scope in `scopes`. Nothing is looked up for the agent.
77
+ *
78
+ * Optional so existing verifiers still compile; verifyOrHints refuses a
79
+ * presented delegation a verifier without it cannot check.
80
+ */
81
+ verifyPresented?(
82
+ credential: string,
83
+ holderDid: string,
66
84
  scopes: string[]
67
85
  ): Promise<VerifyDelegationResult>;
68
86
  }
package/src/index.ts CHANGED
@@ -108,6 +108,27 @@ export type { Ed25519JWK, ParsedJWS } from "./services/crypto.service";
108
108
  // Proof Verifier Service
109
109
  export { ProofVerifier } from "./services/proof-verifier";
110
110
 
111
+ // Request holder: the DID whose key a tools/call proves its caller holds
112
+ export {
113
+ didWebHolderKeys,
114
+ withDidWebHolders,
115
+ type DidWebHolderOptions,
116
+ type HolderKeySeams,
117
+ type ProofPublicJwk,
118
+ } from "./services/holder-keys";
119
+ export { claimsFirstGuard } from "./services/claims-first-guard";
120
+ export {
121
+ createRequestHolderVerifier,
122
+ resolveDidKeyHolder,
123
+ REQUEST_PROOF_SKEW_SEC,
124
+ type HolderRequest,
125
+ type RequestHolderOptions,
126
+ type RequestHolderRefusal,
127
+ type RequestProofOptions,
128
+ type RequestHolderResult,
129
+ type RequestHolderVerifier,
130
+ } from "./services/request-holder";
131
+
111
132
  export type {
112
133
  ProofVerificationResult,
113
134
  ProofVerifierConfig,
@@ -229,7 +250,21 @@ export type {
229
250
  ToolProtectionServiceConfig,
230
251
  } from "./types/tool-protection";
231
252
 
232
- export { DelegationRequiredError } from "./types/tool-protection";
253
+ export {
254
+ AmountLimitError,
255
+ amountLimitToolResult,
256
+ amountRefusalCode,
257
+ DelegationRequiredError,
258
+ isToolProtectionUnenforceableError,
259
+ isUnavailableToolProtection,
260
+ namesRequiredScope,
261
+ TOOL_PROTECTION_UNENFORCEABLE,
262
+ ToolProtectionUnenforceableError,
263
+ unavailableToolProtection,
264
+ unavailableToolProtectionError,
265
+ unscopedToolProtectionError,
266
+ } from "./types/tool-protection";
267
+ export type { UnavailableToolProtection } from "./types/tool-protection";
233
268
  export { OAuthRequiredError } from "./types/oauth-required-error";
234
269
  export type { OAuthRequiredErrorOptions } from "./types/oauth-required-error";
235
270
 
@@ -356,6 +391,9 @@ export {
356
391
  type ToolRequest,
357
392
  type ToolResponse,
358
393
  type ProofOptions,
394
+ type ProofCompanion,
395
+ type GeneratedProof,
396
+ presentValues,
359
397
  } from "./proof";
360
398
 
361
399
  // Session management (platform-agnostic protocol reference — Phase 2)
@@ -374,6 +412,7 @@ export {
374
412
  MemoryResumeTokenStore,
375
413
  generateResumeToken,
376
414
  type AuthHandshakeConfig,
415
+ type VerifyOrHintsOptions,
377
416
  type VerifyOrHintsResult,
378
417
  type AgentReputation,
379
418
  type ResumeTokenStore,
@@ -17,6 +17,7 @@ import {
17
17
  } from "../generator";
18
18
  import type { ProofAgentIdentity } from "../generator";
19
19
  import { SessionContext } from "@kya-os/contracts/handshake";
20
+ import { loadDifCore } from "../../runtime/dif-core";
20
21
 
21
22
  // NodeCryptoProvider is imported from mcp-i (test environment — Node.js)
22
23
  import { NodeCryptoProvider } from "../../../../mcp-i/src/providers/node-providers";
@@ -178,13 +179,31 @@ describe("ProofGenerator", () => {
178
179
  expect(proof.meta.did).toBe(mockIdentity.did);
179
180
  expect(proof.meta.kid).toBe(mockIdentity.kid);
180
181
  expect(proof.meta.ts).toBeTypeOf("number");
181
- expect(proof.meta.nonce).toBe(mockSession.nonce);
182
+ expect(proof.meta.nonce).toMatch(/^[A-Za-z0-9_-]{22}$/);
182
183
  expect(proof.meta.audience).toBe(mockSession.audience);
183
184
  expect(proof.meta.sessionId).toBe(mockSession.sessionId);
184
185
  expect(proof.meta.requestHash).toBeTruthy();
185
186
  expect(proof.meta.responseHash).toBeTruthy();
186
187
  });
187
188
 
189
+ it("signs each proof in a session with a nonce of its own", async () => {
190
+ // A replay check (Checkpoint's, KTA's, @kya-os/mcp's ProofVerifier)
191
+ // spends a proof's nonce once per signer, so a nonce a session shares
192
+ // would refuse every proof after the session's first.
193
+ const request: ToolRequest = { method: "test-tool", params: {} };
194
+ const response: ToolResponse = { data: "ok" };
195
+
196
+ const proofs = await Promise.all(
197
+ [1, 2, 3].map(() =>
198
+ proofGenerator.generateProof(request, response, mockSession)
199
+ )
200
+ );
201
+
202
+ const nonces = proofs.map((proof) => proof.meta.nonce);
203
+ expect(new Set(nonces).size).toBe(3);
204
+ expect(nonces).not.toContain(mockSession.nonce);
205
+ });
206
+
188
207
  it("should include optional fields when provided", async () => {
189
208
  const request: ToolRequest = {
190
209
  method: "test-tool",
@@ -273,7 +292,7 @@ describe("ProofGenerator", () => {
273
292
  expect(payload.clientDid).toBe("did:key:zClientPayload");
274
293
  });
275
294
 
276
- it("encodes did, kid, and audience as literal payload fields, since verifiers check those exact property names, not the JWT-standard sub/iss/aud aliases", async () => {
295
+ it("signs exactly @kya-os/mcp's buildProofJwsPayload(meta), RFC 8785 serialized, with no did/kid/audience literals", async () => {
277
296
  const request: ToolRequest = {
278
297
  method: "test-tool",
279
298
  params: { input: "hello" },
@@ -286,13 +305,29 @@ describe("ProofGenerator", () => {
286
305
  mockSession
287
306
  );
288
307
 
289
- const payload = JSON.parse(
290
- Buffer.from(proof.jws.split(".")[1], "base64url").toString()
291
- ) as { did?: string; kid?: string; audience?: string };
308
+ const { buildProofJwsPayload, canonicalizeJSON } = await loadDifCore();
309
+ const signedPayload = Buffer.from(
310
+ proof.jws.split(".")[1],
311
+ "base64url"
312
+ ).toString("utf8");
313
+
314
+ expect(signedPayload).toBe(
315
+ canonicalizeJSON(buildProofJwsPayload(proof.meta))
316
+ );
317
+
318
+ const payload = JSON.parse(signedPayload) as Record<string, unknown>;
319
+ expect(payload.iss).toBe(mockIdentity.did);
320
+ expect(payload.sub).toBe(mockIdentity.did);
321
+ expect(payload.aud).toBe(mockSession.audience);
322
+ expect(payload).not.toHaveProperty("did");
323
+ expect(payload).not.toHaveProperty("kid");
324
+ expect(payload).not.toHaveProperty("audience");
292
325
 
293
- expect(payload.did).toBe(mockIdentity.did);
294
- expect(payload.kid).toBe(mockIdentity.kid);
295
- expect(payload.audience).toBe(mockSession.audience);
326
+ // kid lives in the protected header only.
327
+ const header = JSON.parse(
328
+ Buffer.from(proof.jws.split(".")[0], "base64url").toString()
329
+ ) as { kid: string };
330
+ expect(header.kid).toBe(mockIdentity.kid);
296
331
  });
297
332
 
298
333
  it("omits toolName and outcome from the JWS payload when not provided", async () => {
@@ -316,7 +351,7 @@ describe("ProofGenerator", () => {
316
351
  expect(payload).not.toHaveProperty("outcome");
317
352
  });
318
353
 
319
- it("encodes toolName as a literal payload field, and renames submissionOutcome to the literal payload key outcome, since know-that-ai's verifier checks those exact property names", async () => {
354
+ it("signs the authorization outcome and returns toolName/submissionOutcome beside the proof, never on meta", async () => {
320
355
  const request: ToolRequest = {
321
356
  method: "test-tool",
322
357
  params: { input: "hello" },
@@ -327,15 +362,47 @@ describe("ProofGenerator", () => {
327
362
  request,
328
363
  response,
329
364
  mockSession,
330
- { toolName: "get_weather", submissionOutcome: "success" }
365
+ {
366
+ outcome: "allowed",
367
+ toolName: "get_weather",
368
+ submissionOutcome: "failure",
369
+ }
331
370
  );
332
371
 
333
372
  const payload = JSON.parse(
334
373
  Buffer.from(proof.jws.split(".")[1], "base64url").toString()
335
- ) as { toolName?: string; outcome?: string };
374
+ ) as Record<string, unknown>;
375
+
376
+ expect(payload.outcome).toBe("allowed");
377
+ expect(payload).not.toHaveProperty("toolName");
378
+ expect(payload).not.toHaveProperty("submissionOutcome");
379
+ expect(proof.meta).not.toHaveProperty("toolName");
380
+ expect(proof.meta).not.toHaveProperty("submissionOutcome");
381
+ expect(proof.toolName).toBe("get_weather");
382
+ expect(proof.submissionOutcome).toBe("failure");
383
+ });
384
+
385
+ it("returns a bare { jws, meta } when nothing rides beside it", async () => {
386
+ const proof = await proofGenerator.generateProof(
387
+ { method: "test-tool", params: {} },
388
+ { data: {} },
389
+ mockSession
390
+ );
391
+
392
+ expect(Object.keys(proof).sort()).toEqual(["jws", "meta"]);
393
+ });
394
+
395
+ it("never writes an empty optional claim to meta", async () => {
396
+ const proof = await proofGenerator.generateProof(
397
+ { method: "test-tool", params: {} },
398
+ { data: {} },
399
+ mockSession,
400
+ { scopeId: "", clientDid: "", delegationRef: undefined }
401
+ );
336
402
 
337
- expect(payload.toolName).toBe("get_weather");
338
- expect(payload.outcome).toBe("success");
403
+ expect(proof.meta).not.toHaveProperty("scopeId");
404
+ expect(proof.meta).not.toHaveProperty("clientDid");
405
+ expect(proof.meta).not.toHaveProperty("delegationRef");
339
406
  });
340
407
  });
341
408
 
@@ -0,0 +1,35 @@
1
+ /**
2
+ * What rides beside a generated proof, unsigned: shared by every runtime's
3
+ * proof generator, the reference one here (./generator) and Cloudflare's.
4
+ *
5
+ * @module proof/companion
6
+ */
7
+
8
+ import type { DetachedProof } from "@kya-os/contracts/proof";
9
+
10
+ /**
11
+ * Values that ride beside a proof, unsigned. They are never written to
12
+ * `meta`, whose members a reader takes for the signed claims they mirror.
13
+ */
14
+ export interface ProofCompanion {
15
+ /** The tool the proof is for, as a proof submission names it. */
16
+ toolName?: string;
17
+ /** Whether the tool call itself succeeded, as a proof submission says. */
18
+ submissionOutcome?: "success" | "failure" | "denied";
19
+ }
20
+
21
+ /**
22
+ * A detached proof as the generator returns it: `{ jws, meta }`, plus any
23
+ * {@link ProofCompanion} values the caller passed, beside `meta`.
24
+ */
25
+ export type GeneratedProof<P extends object = DetachedProof> = P &
26
+ ProofCompanion;
27
+
28
+ /** The members of `values` that have one: an empty value is never written. */
29
+ export function presentValues<T extends object>(values: T): Partial<T> {
30
+ return Object.fromEntries(
31
+ Object.entries(values).filter(
32
+ ([, value]) => value !== undefined && value !== null && value !== ""
33
+ )
34
+ ) as Partial<T>;
35
+ }