@kya-os/mcp-i-core 1.3.12 → 1.3.14

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 (254) hide show
  1. package/dist/config/remote-config.js +9 -12
  2. package/dist/runtime/base.js +11 -0
  3. package/dist/services/access-control.service.js +5 -0
  4. package/dist/services/tool-protection.service.js +17 -8
  5. package/package.json +2 -2
  6. package/.turbo/turbo-build.log +0 -4
  7. package/.turbo/turbo-test$colon$coverage.log +0 -4586
  8. package/.turbo/turbo-test.log +0 -3169
  9. package/COMPLIANCE_IMPROVEMENT_REPORT.md +0 -483
  10. package/Composer 3.md +0 -615
  11. package/GPT-5.md +0 -1169
  12. package/OPUS-plan.md +0 -352
  13. package/PHASE_3_AND_4.1_SUMMARY.md +0 -585
  14. package/PHASE_3_SUMMARY.md +0 -317
  15. package/PHASE_4.1.3_SUMMARY.md +0 -428
  16. package/PHASE_4.1_COMPLETE.md +0 -525
  17. package/PHASE_4_USER_DID_IDENTITY_LINKING_PLAN.md +0 -1240
  18. package/SCHEMA_COMPLIANCE_REPORT.md +0 -275
  19. package/TEST_PLAN.md +0 -571
  20. package/coverage/coverage-final.json +0 -60
  21. package/dist/cache/oauth-config-cache.d.ts.map +0 -1
  22. package/dist/cache/oauth-config-cache.js.map +0 -1
  23. package/dist/cache/tool-protection-cache.d.ts.map +0 -1
  24. package/dist/cache/tool-protection-cache.js.map +0 -1
  25. package/dist/compliance/index.d.ts.map +0 -1
  26. package/dist/compliance/index.js.map +0 -1
  27. package/dist/compliance/schema-registry.d.ts.map +0 -1
  28. package/dist/compliance/schema-registry.js.map +0 -1
  29. package/dist/compliance/schema-verifier.d.ts.map +0 -1
  30. package/dist/compliance/schema-verifier.js.map +0 -1
  31. package/dist/config/remote-config.d.ts.map +0 -1
  32. package/dist/config/remote-config.js.map +0 -1
  33. package/dist/config.d.ts.map +0 -1
  34. package/dist/config.js.map +0 -1
  35. package/dist/delegation/audience-validator.d.ts.map +0 -1
  36. package/dist/delegation/audience-validator.js.map +0 -1
  37. package/dist/delegation/bitstring.d.ts.map +0 -1
  38. package/dist/delegation/bitstring.js.map +0 -1
  39. package/dist/delegation/cascading-revocation.d.ts.map +0 -1
  40. package/dist/delegation/cascading-revocation.js.map +0 -1
  41. package/dist/delegation/delegation-graph.d.ts.map +0 -1
  42. package/dist/delegation/delegation-graph.js.map +0 -1
  43. package/dist/delegation/did-key-resolver.d.ts.map +0 -1
  44. package/dist/delegation/did-key-resolver.js.map +0 -1
  45. package/dist/delegation/index.d.ts.map +0 -1
  46. package/dist/delegation/index.js.map +0 -1
  47. package/dist/delegation/statuslist-manager.d.ts.map +0 -1
  48. package/dist/delegation/statuslist-manager.js.map +0 -1
  49. package/dist/delegation/storage/index.d.ts.map +0 -1
  50. package/dist/delegation/storage/index.js.map +0 -1
  51. package/dist/delegation/storage/memory-graph-storage.d.ts.map +0 -1
  52. package/dist/delegation/storage/memory-graph-storage.js.map +0 -1
  53. package/dist/delegation/storage/memory-statuslist-storage.d.ts.map +0 -1
  54. package/dist/delegation/storage/memory-statuslist-storage.js.map +0 -1
  55. package/dist/delegation/utils.d.ts.map +0 -1
  56. package/dist/delegation/utils.js.map +0 -1
  57. package/dist/delegation/vc-issuer.d.ts.map +0 -1
  58. package/dist/delegation/vc-issuer.js.map +0 -1
  59. package/dist/delegation/vc-verifier.d.ts.map +0 -1
  60. package/dist/delegation/vc-verifier.js.map +0 -1
  61. package/dist/identity/idp-token-resolver.d.ts.map +0 -1
  62. package/dist/identity/idp-token-resolver.js.map +0 -1
  63. package/dist/identity/idp-token-storage.interface.d.ts.map +0 -1
  64. package/dist/identity/idp-token-storage.interface.js.map +0 -1
  65. package/dist/identity/user-did-manager.d.ts.map +0 -1
  66. package/dist/identity/user-did-manager.js.map +0 -1
  67. package/dist/index.d.ts.map +0 -1
  68. package/dist/index.js.map +0 -1
  69. package/dist/providers/base.d.ts.map +0 -1
  70. package/dist/providers/base.js.map +0 -1
  71. package/dist/providers/memory.d.ts.map +0 -1
  72. package/dist/providers/memory.js.map +0 -1
  73. package/dist/runtime/audit-logger.d.ts.map +0 -1
  74. package/dist/runtime/audit-logger.js.map +0 -1
  75. package/dist/runtime/base.d.ts.map +0 -1
  76. package/dist/runtime/base.js.map +0 -1
  77. package/dist/services/access-control.service.d.ts.map +0 -1
  78. package/dist/services/access-control.service.js.map +0 -1
  79. package/dist/services/authorization/authorization-registry.d.ts.map +0 -1
  80. package/dist/services/authorization/authorization-registry.js.map +0 -1
  81. package/dist/services/authorization/types.d.ts.map +0 -1
  82. package/dist/services/authorization/types.js.map +0 -1
  83. package/dist/services/batch-delegation.service.d.ts.map +0 -1
  84. package/dist/services/batch-delegation.service.js.map +0 -1
  85. package/dist/services/crypto.service.d.ts.map +0 -1
  86. package/dist/services/crypto.service.js.map +0 -1
  87. package/dist/services/errors.d.ts.map +0 -1
  88. package/dist/services/errors.js.map +0 -1
  89. package/dist/services/index.d.ts.map +0 -1
  90. package/dist/services/index.js.map +0 -1
  91. package/dist/services/oauth-config.service.d.ts.map +0 -1
  92. package/dist/services/oauth-config.service.js.map +0 -1
  93. package/dist/services/oauth-provider-registry.d.ts.map +0 -1
  94. package/dist/services/oauth-provider-registry.js.map +0 -1
  95. package/dist/services/oauth-service.d.ts.map +0 -1
  96. package/dist/services/oauth-service.js.map +0 -1
  97. package/dist/services/oauth-token-retrieval.service.d.ts.map +0 -1
  98. package/dist/services/oauth-token-retrieval.service.js.map +0 -1
  99. package/dist/services/proof-verifier.d.ts.map +0 -1
  100. package/dist/services/proof-verifier.js.map +0 -1
  101. package/dist/services/provider-resolver.d.ts.map +0 -1
  102. package/dist/services/provider-resolver.js.map +0 -1
  103. package/dist/services/provider-validator.d.ts.map +0 -1
  104. package/dist/services/provider-validator.js.map +0 -1
  105. package/dist/services/session-registration.service.d.ts.map +0 -1
  106. package/dist/services/session-registration.service.js.map +0 -1
  107. package/dist/services/storage.service.d.ts.map +0 -1
  108. package/dist/services/storage.service.js.map +0 -1
  109. package/dist/services/tool-context-builder.d.ts.map +0 -1
  110. package/dist/services/tool-context-builder.js.map +0 -1
  111. package/dist/services/tool-protection.service.d.ts.map +0 -1
  112. package/dist/services/tool-protection.service.js.map +0 -1
  113. package/dist/types/oauth-required-error.d.ts.map +0 -1
  114. package/dist/types/oauth-required-error.js.map +0 -1
  115. package/dist/types/tool-protection.d.ts.map +0 -1
  116. package/dist/types/tool-protection.js.map +0 -1
  117. package/dist/utils/base58.d.ts.map +0 -1
  118. package/dist/utils/base58.js.map +0 -1
  119. package/dist/utils/base64.d.ts.map +0 -1
  120. package/dist/utils/base64.js.map +0 -1
  121. package/dist/utils/cors.d.ts.map +0 -1
  122. package/dist/utils/cors.js.map +0 -1
  123. package/dist/utils/did-helpers.d.ts.map +0 -1
  124. package/dist/utils/did-helpers.js.map +0 -1
  125. package/dist/utils/index.d.ts.map +0 -1
  126. package/dist/utils/index.js.map +0 -1
  127. package/dist/utils/storage-keys.d.ts.map +0 -1
  128. package/dist/utils/storage-keys.js.map +0 -1
  129. package/docs/API_REFERENCE.md +0 -1362
  130. package/docs/COMPLIANCE_MATRIX.md +0 -691
  131. package/docs/STATUSLIST2021_GUIDE.md +0 -696
  132. package/docs/W3C_VC_DELEGATION_GUIDE.md +0 -710
  133. package/src/__tests__/cache/tool-protection-cache.test.ts +0 -640
  134. package/src/__tests__/config/provider-runtime-config.test.ts +0 -309
  135. package/src/__tests__/delegation-e2e.test.ts +0 -690
  136. package/src/__tests__/identity/user-did-manager.test.ts +0 -232
  137. package/src/__tests__/index.test.ts +0 -56
  138. package/src/__tests__/integration/full-flow.test.ts +0 -789
  139. package/src/__tests__/integration.test.ts +0 -281
  140. package/src/__tests__/providers/base.test.ts +0 -173
  141. package/src/__tests__/providers/memory.test.ts +0 -319
  142. package/src/__tests__/regression/phase2-regression.test.ts +0 -429
  143. package/src/__tests__/runtime/audit-logger.test.ts +0 -154
  144. package/src/__tests__/runtime/base-extensions.test.ts +0 -595
  145. package/src/__tests__/runtime/base.test.ts +0 -869
  146. package/src/__tests__/runtime/delegation-flow.test.ts +0 -164
  147. package/src/__tests__/runtime/proof-client-did.test.ts +0 -376
  148. package/src/__tests__/runtime/route-interception.test.ts +0 -686
  149. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +0 -908
  150. package/src/__tests__/services/agentshield-integration.test.ts +0 -791
  151. package/src/__tests__/services/cache-busting.test.ts +0 -125
  152. package/src/__tests__/services/oauth-service-pkce.test.ts +0 -556
  153. package/src/__tests__/services/provider-resolver-edge-cases.test.ts +0 -591
  154. package/src/__tests__/services/tool-protection-merged-config.test.ts +0 -485
  155. package/src/__tests__/services/tool-protection-oauth-provider.test.ts +0 -480
  156. package/src/__tests__/services/tool-protection.service.test.ts +0 -1373
  157. package/src/__tests__/utils/mock-providers.ts +0 -340
  158. package/src/cache/oauth-config-cache.d.ts +0 -69
  159. package/src/cache/oauth-config-cache.d.ts.map +0 -1
  160. package/src/cache/oauth-config-cache.js.map +0 -1
  161. package/src/cache/oauth-config-cache.ts +0 -123
  162. package/src/cache/tool-protection-cache.ts +0 -171
  163. package/src/compliance/EXAMPLE.md +0 -412
  164. package/src/compliance/__tests__/schema-verifier.test.ts +0 -797
  165. package/src/compliance/index.ts +0 -8
  166. package/src/compliance/schema-registry.ts +0 -460
  167. package/src/compliance/schema-verifier.ts +0 -708
  168. package/src/config/__tests__/merged-config.spec.ts +0 -445
  169. package/src/config/__tests__/remote-config.spec.ts +0 -268
  170. package/src/config/remote-config.ts +0 -264
  171. package/src/config.ts +0 -312
  172. package/src/delegation/__tests__/audience-validator.test.ts +0 -112
  173. package/src/delegation/__tests__/bitstring.test.ts +0 -346
  174. package/src/delegation/__tests__/cascading-revocation.test.ts +0 -628
  175. package/src/delegation/__tests__/delegation-graph.test.ts +0 -584
  176. package/src/delegation/__tests__/did-key-resolver.test.ts +0 -265
  177. package/src/delegation/__tests__/utils.test.ts +0 -152
  178. package/src/delegation/__tests__/vc-issuer.test.ts +0 -442
  179. package/src/delegation/__tests__/vc-verifier.test.ts +0 -922
  180. package/src/delegation/audience-validator.ts +0 -52
  181. package/src/delegation/bitstring.ts +0 -278
  182. package/src/delegation/cascading-revocation.ts +0 -370
  183. package/src/delegation/delegation-graph.ts +0 -299
  184. package/src/delegation/did-key-resolver.ts +0 -179
  185. package/src/delegation/index.ts +0 -14
  186. package/src/delegation/statuslist-manager.ts +0 -353
  187. package/src/delegation/storage/__tests__/memory-graph-storage.test.ts +0 -366
  188. package/src/delegation/storage/__tests__/memory-statuslist-storage.test.ts +0 -228
  189. package/src/delegation/storage/index.ts +0 -9
  190. package/src/delegation/storage/memory-graph-storage.ts +0 -178
  191. package/src/delegation/storage/memory-statuslist-storage.ts +0 -77
  192. package/src/delegation/utils.ts +0 -221
  193. package/src/delegation/vc-issuer.ts +0 -232
  194. package/src/delegation/vc-verifier.ts +0 -568
  195. package/src/identity/idp-token-resolver.ts +0 -181
  196. package/src/identity/idp-token-storage.interface.ts +0 -94
  197. package/src/identity/user-did-manager.ts +0 -526
  198. package/src/index.ts +0 -310
  199. package/src/providers/base.d.ts +0 -91
  200. package/src/providers/base.d.ts.map +0 -1
  201. package/src/providers/base.js.map +0 -1
  202. package/src/providers/base.ts +0 -96
  203. package/src/providers/memory.ts +0 -142
  204. package/src/runtime/audit-logger.ts +0 -39
  205. package/src/runtime/base.ts +0 -1392
  206. package/src/services/__tests__/access-control.integration.test.ts +0 -443
  207. package/src/services/__tests__/access-control.proof-response-validation.test.ts +0 -578
  208. package/src/services/__tests__/access-control.service.test.ts +0 -970
  209. package/src/services/__tests__/batch-delegation.service.test.ts +0 -351
  210. package/src/services/__tests__/crypto.service.test.ts +0 -531
  211. package/src/services/__tests__/oauth-provider-registry.test.ts +0 -142
  212. package/src/services/__tests__/proof-verifier.integration.test.ts +0 -485
  213. package/src/services/__tests__/proof-verifier.test.ts +0 -489
  214. package/src/services/__tests__/provider-resolution.integration.test.ts +0 -202
  215. package/src/services/__tests__/provider-resolver.test.ts +0 -213
  216. package/src/services/__tests__/storage.service.test.ts +0 -358
  217. package/src/services/access-control.service.ts +0 -990
  218. package/src/services/authorization/authorization-registry.ts +0 -66
  219. package/src/services/authorization/types.ts +0 -71
  220. package/src/services/batch-delegation.service.ts +0 -137
  221. package/src/services/crypto.service.ts +0 -302
  222. package/src/services/errors.ts +0 -76
  223. package/src/services/index.ts +0 -18
  224. package/src/services/oauth-config.service.d.ts +0 -53
  225. package/src/services/oauth-config.service.d.ts.map +0 -1
  226. package/src/services/oauth-config.service.js.map +0 -1
  227. package/src/services/oauth-config.service.ts +0 -192
  228. package/src/services/oauth-provider-registry.d.ts +0 -57
  229. package/src/services/oauth-provider-registry.d.ts.map +0 -1
  230. package/src/services/oauth-provider-registry.js.map +0 -1
  231. package/src/services/oauth-provider-registry.ts +0 -141
  232. package/src/services/oauth-service.ts +0 -544
  233. package/src/services/oauth-token-retrieval.service.ts +0 -245
  234. package/src/services/proof-verifier.ts +0 -478
  235. package/src/services/provider-resolver.d.ts +0 -48
  236. package/src/services/provider-resolver.d.ts.map +0 -1
  237. package/src/services/provider-resolver.js.map +0 -1
  238. package/src/services/provider-resolver.ts +0 -146
  239. package/src/services/provider-validator.ts +0 -170
  240. package/src/services/session-registration.service.ts +0 -251
  241. package/src/services/storage.service.ts +0 -566
  242. package/src/services/tool-context-builder.ts +0 -237
  243. package/src/services/tool-protection.service.ts +0 -1070
  244. package/src/types/oauth-required-error.ts +0 -63
  245. package/src/types/tool-protection.ts +0 -155
  246. package/src/utils/__tests__/did-helpers.test.ts +0 -156
  247. package/src/utils/base58.ts +0 -109
  248. package/src/utils/base64.ts +0 -148
  249. package/src/utils/cors.ts +0 -83
  250. package/src/utils/did-helpers.ts +0 -210
  251. package/src/utils/index.ts +0 -8
  252. package/src/utils/storage-keys.ts +0 -278
  253. package/tsconfig.json +0 -21
  254. package/vitest.config.ts +0 -56
@@ -1,245 +0,0 @@
1
- /**
2
- * OAuth Token Retrieval Service
3
- *
4
- * Retrieves OAuth tokens from AgentShield after receiving delegation token.
5
- * Implements the two-step token flow for Phase 3 custom IDP support.
6
- *
7
- * @package @kya-os/mcp-i-core
8
- */
9
-
10
- import type { IdpTokens } from "@kya-os/contracts/config";
11
-
12
- /**
13
- * Configuration for OAuthTokenRetrievalService
14
- */
15
- export interface OAuthTokenRetrievalServiceConfig {
16
- /** AgentShield API base URL */
17
- baseUrl: string;
18
- /** Fetch implementation */
19
- fetchProvider: typeof fetch;
20
- /** Optional logger callback */
21
- logger?: (message: string, data?: any) => void;
22
- /** Optional retry configuration */
23
- retryConfig?: {
24
- maxRetries?: number;
25
- retryDelay?: number; // milliseconds
26
- retryBackoff?: number; // multiplier for exponential backoff
27
- };
28
- }
29
-
30
- /**
31
- * Response from AgentShield token retrieval endpoint
32
- */
33
- interface OAuthTokenRetrievalResponse {
34
- success: true;
35
- data: {
36
- oauth_access_token: string;
37
- oauth_refresh_token: string | null;
38
- oauth_expires_at: string | null; // ISO 8601 datetime string
39
- oauth_expires_in: number | null; // seconds
40
- oauth_token_type: string;
41
- oauth_scope: string | null;
42
- };
43
- metadata?: {
44
- requestId?: string;
45
- timestamp?: string; // ISO 8601
46
- };
47
- }
48
-
49
- /**
50
- * Error response from AgentShield
51
- */
52
- interface OAuthTokenRetrievalErrorResponse {
53
- success: false;
54
- error: {
55
- code: string;
56
- message: string;
57
- details?: any;
58
- };
59
- }
60
-
61
- /**
62
- * Service for retrieving OAuth tokens from AgentShield
63
- */
64
- export class OAuthTokenRetrievalService {
65
- private config: Required<OAuthTokenRetrievalServiceConfig> & {
66
- retryConfig: Required<NonNullable<OAuthTokenRetrievalServiceConfig["retryConfig"]>>;
67
- };
68
-
69
- constructor(config: OAuthTokenRetrievalServiceConfig) {
70
- const defaultRetryConfig = {
71
- maxRetries: 3,
72
- retryDelay: 1000,
73
- retryBackoff: 2,
74
- };
75
-
76
- this.config = {
77
- ...config,
78
- logger: config.logger || (() => {}),
79
- retryConfig: {
80
- ...defaultRetryConfig,
81
- ...config.retryConfig,
82
- },
83
- } as Required<OAuthTokenRetrievalServiceConfig> & {
84
- retryConfig: Required<NonNullable<OAuthTokenRetrievalServiceConfig["retryConfig"]>>;
85
- };
86
- }
87
-
88
- /**
89
- * Retrieve OAuth tokens from AgentShield
90
- *
91
- * @param delegationId - Delegation ID from token exchange response
92
- * @param delegationToken - Delegation token (JWT) for authorization
93
- * @returns OAuth tokens mapped to IdpTokens format, or null if unavailable
94
- */
95
- async retrieveTokens(
96
- delegationId: string,
97
- delegationToken: string
98
- ): Promise<IdpTokens | null> {
99
- const endpoint = `${this.config.baseUrl}/api/v1/bouncer/delegations/${delegationId}/tokens`;
100
-
101
- this.config.logger("[OAuthTokenRetrievalService] Retrieving OAuth tokens", {
102
- delegationId,
103
- endpoint,
104
- });
105
-
106
- let lastError: Error | null = null;
107
- let attempt = 0;
108
-
109
- // Retry logic for transient failures
110
- while (attempt <= this.config.retryConfig.maxRetries) {
111
- try {
112
- const response = await this.config.fetchProvider(endpoint, {
113
- method: "GET",
114
- headers: {
115
- Authorization: `Bearer ${delegationToken}`,
116
- Accept: "application/json",
117
- },
118
- });
119
-
120
- if (!response.ok) {
121
- const errorData = await response.json().catch(() => ({})) as
122
- | OAuthTokenRetrievalErrorResponse
123
- | { error?: string; message?: string };
124
-
125
- if (response.status === 404 || response.status === 401) {
126
- // Token unavailable or unauthorized - don't retry
127
- this.config.logger(
128
- "[OAuthTokenRetrievalService] Tokens unavailable",
129
- {
130
- status: response.status,
131
- delegationId,
132
- error: errorData,
133
- }
134
- );
135
- return null;
136
- }
137
-
138
- // Transient error - retry
139
- const errorMessage =
140
- (errorData as OAuthTokenRetrievalErrorResponse).error?.message ||
141
- (errorData as any).error ||
142
- (errorData as any).message ||
143
- `HTTP ${response.status}`;
144
-
145
- throw new Error(`Token retrieval failed: ${errorMessage}`);
146
- }
147
-
148
- const result = (await response.json()) as
149
- | OAuthTokenRetrievalResponse
150
- | OAuthTokenRetrievalErrorResponse;
151
-
152
- if (!result.success) {
153
- this.config.logger(
154
- "[OAuthTokenRetrievalService] Token retrieval error response",
155
- {
156
- delegationId,
157
- error: result.error,
158
- }
159
- );
160
- return null;
161
- }
162
-
163
- // Map response to IdpTokens format
164
- const tokens = this.mapToIdpTokens(result.data);
165
-
166
- this.config.logger(
167
- "[OAuthTokenRetrievalService] OAuth tokens retrieved successfully",
168
- {
169
- delegationId,
170
- expiresAt: new Date(tokens.expires_at).toISOString(),
171
- hasRefreshToken: !!tokens.refresh_token,
172
- }
173
- );
174
-
175
- return tokens;
176
- } catch (error) {
177
- lastError = error instanceof Error ? error : new Error(String(error));
178
-
179
- if (attempt < this.config.retryConfig.maxRetries) {
180
- const delay =
181
- this.config.retryConfig.retryDelay *
182
- Math.pow(this.config.retryConfig.retryBackoff, attempt);
183
-
184
- this.config.logger(
185
- "[OAuthTokenRetrievalService] Retry attempt failed, retrying",
186
- {
187
- attempt: attempt + 1,
188
- maxRetries: this.config.retryConfig.maxRetries,
189
- delay,
190
- error: lastError.message,
191
- }
192
- );
193
-
194
- await new Promise((resolve) => setTimeout(resolve, delay));
195
- attempt++;
196
- } else {
197
- // Max retries exceeded
198
- this.config.logger(
199
- "[OAuthTokenRetrievalService] Max retries exceeded",
200
- {
201
- delegationId,
202
- error: lastError.message,
203
- attempts: attempt + 1,
204
- }
205
- );
206
- // Return null instead of throwing - delegation token still valid
207
- return null;
208
- }
209
- }
210
- }
211
-
212
- return null;
213
- }
214
-
215
- /**
216
- * Map AgentShield response to IdpTokens format
217
- *
218
- * @param data - Response data from AgentShield
219
- * @returns IdpTokens object
220
- */
221
- private mapToIdpTokens(
222
- data: OAuthTokenRetrievalResponse["data"]
223
- ): IdpTokens {
224
- // Convert ISO 8601 string to milliseconds timestamp
225
- let expiresAt: number;
226
- if (data.oauth_expires_at) {
227
- expiresAt = new Date(data.oauth_expires_at).getTime();
228
- } else if (data.oauth_expires_in) {
229
- expiresAt = Date.now() + data.oauth_expires_in * 1000;
230
- } else {
231
- // Default to 1 hour if neither provided
232
- expiresAt = Date.now() + 3600 * 1000;
233
- }
234
-
235
- return {
236
- access_token: data.oauth_access_token,
237
- refresh_token: data.oauth_refresh_token || undefined,
238
- expires_in: data.oauth_expires_in || undefined,
239
- expires_at: expiresAt,
240
- token_type: data.oauth_token_type || "Bearer",
241
- scope: data.oauth_scope || undefined,
242
- };
243
- }
244
- }
245
-
@@ -1,478 +0,0 @@
1
- /**
2
- * ProofVerifier
3
- *
4
- * Centralized proof verification service that validates DetachedProof
5
- * signatures, enforces nonce replay protection, and checks timestamp skew.
6
- */
7
-
8
- import { CryptoService, type Ed25519JWK } from "./crypto.service.js";
9
- import { CryptoProvider } from "../providers/base.js";
10
- import { ClockProvider } from "../providers/base.js";
11
- import { NonceCacheProvider } from "../providers/base.js";
12
- import { FetchProvider } from "../providers/base.js";
13
- import {
14
- DetachedProofSchema,
15
- type DetachedProof,
16
- } from "@kya-os/contracts/proof";
17
- import { canonicalize } from "json-canonicalize";
18
- import {
19
- ProofVerificationError,
20
- PROOF_VERIFICATION_ERROR_CODES,
21
- type ProofVerificationErrorCode,
22
- } from "./errors.js";
23
-
24
- export interface ProofVerificationResult {
25
- valid: boolean;
26
- reason?: string;
27
- error?: Error;
28
- errorCode?: ProofVerificationErrorCode;
29
- details?: Record<string, unknown>;
30
- }
31
-
32
- export interface ProofVerifierConfig {
33
- cryptoProvider: CryptoProvider;
34
- clockProvider: ClockProvider;
35
- nonceCacheProvider: NonceCacheProvider;
36
- fetchProvider: FetchProvider;
37
- timestampSkewSeconds?: number;
38
- nonceTtlSeconds?: number;
39
- }
40
-
41
- export class ProofVerifier {
42
- private cryptoService: CryptoService;
43
- private clock: ClockProvider;
44
- private nonceCache: NonceCacheProvider;
45
- private fetch: FetchProvider;
46
- private timestampSkewSeconds: number;
47
- private nonceTtlSeconds: number;
48
-
49
- constructor(config: ProofVerifierConfig) {
50
- this.cryptoService = new CryptoService(config.cryptoProvider);
51
- this.clock = config.clockProvider;
52
- this.nonceCache = config.nonceCacheProvider;
53
- this.fetch = config.fetchProvider;
54
- this.timestampSkewSeconds = config.timestampSkewSeconds ?? 120; // Default 2 minutes
55
- this.nonceTtlSeconds = config.nonceTtlSeconds ?? 300; // Default 5 minutes
56
- }
57
-
58
- /**
59
- * Verify a DetachedProof
60
- * Automatically reconstructs canonical payload from proof.meta for signature verification
61
- * @param proof - The proof to verify
62
- * @param publicKeyJwk - Ed25519 public key in JWK format (from DID document)
63
- * @returns Verification result
64
- */
65
- async verifyProof(
66
- proof: DetachedProof,
67
- publicKeyJwk: Ed25519JWK
68
- ): Promise<ProofVerificationResult> {
69
- try {
70
- // 1. Validate proof structure
71
- const structureValidation = await this.validateProofStructure(proof);
72
- if (!structureValidation.valid) {
73
- return structureValidation;
74
- }
75
- const validatedProof = structureValidation.proof!;
76
-
77
- // 2. Check nonce replay protection (scoped to agent DID to prevent cross-agent replay attacks)
78
- const nonceValidation = await this.validateNonce(
79
- validatedProof.meta.nonce,
80
- validatedProof.meta.did
81
- );
82
- if (!nonceValidation.valid) {
83
- return nonceValidation;
84
- }
85
-
86
- // 3. Check timestamp skew
87
- const timestampValidation = await this.validateTimestamp(
88
- validatedProof.meta.ts
89
- );
90
- if (!timestampValidation.valid) {
91
- return timestampValidation;
92
- }
93
-
94
- // 4. Reconstruct canonical payload from proof meta
95
- const canonicalPayloadString = this.buildCanonicalPayload(
96
- validatedProof.meta
97
- );
98
- const canonicalPayloadBytes = new TextEncoder().encode(
99
- canonicalPayloadString
100
- );
101
-
102
- // 5. Verify JWS signature with detached canonical payload
103
- const signatureValidation = await this.verifySignature(
104
- validatedProof.jws,
105
- publicKeyJwk,
106
- canonicalPayloadBytes,
107
- validatedProof.meta.kid
108
- );
109
- if (!signatureValidation.valid) {
110
- return signatureValidation;
111
- }
112
-
113
- // 6. Add nonce to cache to prevent replay (scoped to agent DID)
114
- await this.addNonceToCache(
115
- validatedProof.meta.nonce,
116
- validatedProof.meta.did
117
- );
118
-
119
- return {
120
- valid: true,
121
- };
122
- } catch (error) {
123
- // Security-safe failure: never throw, always return error result
124
- return {
125
- valid: false,
126
- reason: "Proof verification error",
127
- errorCode: PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,
128
- error: error instanceof Error ? error : new Error(String(error)),
129
- details: {
130
- errorMessage: error instanceof Error ? error.message : String(error),
131
- },
132
- };
133
- }
134
- }
135
-
136
- /**
137
- * Verify proof with detached payload (for CLI/verifier compatibility)
138
- * @param proof - The proof to verify
139
- * @param canonicalPayload - Canonical JSON payload (for detached JWS) as string or Uint8Array
140
- * @param publicKeyJwk - Ed25519 public key in JWK format
141
- * @returns Verification result
142
- */
143
- async verifyProofDetached(
144
- proof: DetachedProof,
145
- canonicalPayload: string | Uint8Array,
146
- publicKeyJwk: Ed25519JWK
147
- ): Promise<ProofVerificationResult> {
148
- try {
149
- // 1. Validate proof structure
150
- const structureValidation = await this.validateProofStructure(proof);
151
- if (!structureValidation.valid) {
152
- return structureValidation;
153
- }
154
- const validatedProof = structureValidation.proof!;
155
-
156
- // 2. Check nonce replay protection (scoped to agent DID to prevent cross-agent replay attacks)
157
- const nonceValidation = await this.validateNonce(
158
- validatedProof.meta.nonce,
159
- validatedProof.meta.did
160
- );
161
- if (!nonceValidation.valid) {
162
- return nonceValidation;
163
- }
164
-
165
- // 3. Check timestamp skew
166
- const timestampValidation = await this.validateTimestamp(
167
- validatedProof.meta.ts
168
- );
169
- if (!timestampValidation.valid) {
170
- return timestampValidation;
171
- }
172
-
173
- // 4. Convert canonical payload to Uint8Array if needed
174
- const canonicalPayloadBytes =
175
- canonicalPayload instanceof Uint8Array
176
- ? canonicalPayload
177
- : new TextEncoder().encode(canonicalPayload);
178
-
179
- // 5. Verify JWS signature with detached payload
180
- const signatureValidation = await this.verifySignature(
181
- validatedProof.jws,
182
- publicKeyJwk,
183
- canonicalPayloadBytes,
184
- validatedProof.meta.kid
185
- );
186
- if (!signatureValidation.valid) {
187
- return signatureValidation;
188
- }
189
-
190
- // 6. Add nonce to cache (scoped to agent DID)
191
- await this.addNonceToCache(
192
- validatedProof.meta.nonce,
193
- validatedProof.meta.did
194
- );
195
-
196
- return {
197
- valid: true,
198
- };
199
- } catch (error) {
200
- // Security-safe failure: never throw, always return error result
201
- return {
202
- valid: false,
203
- reason: "Proof verification error",
204
- errorCode: PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,
205
- error: error instanceof Error ? error : new Error(String(error)),
206
- details: {
207
- errorMessage: error instanceof Error ? error.message : String(error),
208
- },
209
- };
210
- }
211
- }
212
-
213
- /**
214
- * Validate proof structure using Zod schema
215
- * @private
216
- */
217
- private async validateProofStructure(
218
- proof: DetachedProof
219
- ): Promise<ProofVerificationResult & { proof?: DetachedProof }> {
220
- const validationResult = DetachedProofSchema.safeParse(proof);
221
- if (!validationResult.success) {
222
- return {
223
- valid: false,
224
- reason: "Invalid proof structure",
225
- errorCode: PROOF_VERIFICATION_ERROR_CODES.INVALID_PROOF_STRUCTURE,
226
- error: new Error(
227
- `Proof validation failed: ${validationResult.error.message}`
228
- ),
229
- details: {
230
- zodErrors: validationResult.error.errors,
231
- },
232
- };
233
- }
234
- return {
235
- valid: true,
236
- proof: validationResult.data,
237
- };
238
- }
239
-
240
- /**
241
- * Validate nonce replay protection
242
- * @private
243
- */
244
- private async validateNonce(
245
- nonce: string,
246
- agentDid?: string
247
- ): Promise<ProofVerificationResult> {
248
- const nonceUsed = await this.nonceCache.has(nonce, agentDid);
249
- if (nonceUsed) {
250
- return {
251
- valid: false,
252
- reason: "Nonce already used (replay attack detected)",
253
- errorCode: PROOF_VERIFICATION_ERROR_CODES.NONCE_REPLAY_DETECTED,
254
- details: {
255
- nonce,
256
- agentDid,
257
- },
258
- };
259
- }
260
- return { valid: true };
261
- }
262
-
263
- /**
264
- * Validate timestamp skew
265
- * @private
266
- */
267
- private async validateTimestamp(
268
- timestamp: number
269
- ): Promise<ProofVerificationResult> {
270
- // Convert seconds to milliseconds for clock provider (which uses Date.now())
271
- const timestampMs = timestamp * 1000;
272
- if (!this.clock.isWithinSkew(timestampMs, this.timestampSkewSeconds)) {
273
- return {
274
- valid: false,
275
- reason: `Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,
276
- errorCode: PROOF_VERIFICATION_ERROR_CODES.TIMESTAMP_SKEW_EXCEEDED,
277
- details: {
278
- timestamp,
279
- timestampMs,
280
- skewSeconds: this.timestampSkewSeconds,
281
- currentTime: this.clock.now(),
282
- },
283
- };
284
- }
285
- return { valid: true };
286
- }
287
-
288
- /**
289
- * Verify JWS signature
290
- * @private
291
- */
292
- private async verifySignature(
293
- jws: string,
294
- publicKeyJwk: Ed25519JWK,
295
- canonicalPayloadBytes: Uint8Array,
296
- expectedKid?: string
297
- ): Promise<ProofVerificationResult> {
298
- const signatureValid = await this.cryptoService.verifyJWS(
299
- jws,
300
- publicKeyJwk,
301
- {
302
- detachedPayload: canonicalPayloadBytes,
303
- expectedKid,
304
- alg: "EdDSA",
305
- }
306
- );
307
-
308
- if (!signatureValid) {
309
- return {
310
- valid: false,
311
- reason: "Invalid JWS signature",
312
- errorCode: PROOF_VERIFICATION_ERROR_CODES.INVALID_JWS_SIGNATURE,
313
- details: {
314
- jwsLength: jws.length,
315
- expectedKid,
316
- actualKid: publicKeyJwk.kid,
317
- },
318
- };
319
- }
320
-
321
- return { valid: true };
322
- }
323
-
324
- /**
325
- * Add nonce to cache to prevent replay (scoped to agent DID)
326
- * @private
327
- */
328
- private async addNonceToCache(
329
- nonce: string,
330
- agentDid: string
331
- ): Promise<void> {
332
- // Pass TTL in seconds, not absolute timestamp
333
- await this.nonceCache.add(nonce, this.nonceTtlSeconds, agentDid);
334
- }
335
-
336
- /**
337
- * Fetch public key from DID document
338
- * @param did - DID to resolve
339
- * @param kid - Key ID (optional, defaults to first verification method)
340
- * @returns Ed25519 JWK or null if not found
341
- * @throws {ProofVerificationError} If DID resolution fails with specific error code
342
- */
343
- async fetchPublicKeyFromDID(
344
- did: string,
345
- kid?: string
346
- ): Promise<Ed25519JWK | null> {
347
- try {
348
- const didDoc = await this.fetch.resolveDID(did);
349
-
350
- if (!didDoc) {
351
- throw new ProofVerificationError(
352
- PROOF_VERIFICATION_ERROR_CODES.DID_DOCUMENT_NOT_FOUND,
353
- `DID document not found: ${did}`,
354
- { did }
355
- );
356
- }
357
-
358
- if (
359
- !didDoc.verificationMethod ||
360
- didDoc.verificationMethod.length === 0
361
- ) {
362
- throw new ProofVerificationError(
363
- PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,
364
- `No verification methods found in DID document: ${did}`,
365
- { did }
366
- );
367
- }
368
-
369
- // Find verification method by kid or use first one
370
- let verificationMethod:
371
- | { id: string; publicKeyJwk?: unknown }
372
- | undefined;
373
- if (kid) {
374
- const kidWithHash = kid.startsWith("#") ? kid : `#${kid}`;
375
- verificationMethod = didDoc.verificationMethod.find(
376
- (vm: { id: string }) =>
377
- vm.id === kidWithHash || vm.id === `${did}${kidWithHash}`
378
- );
379
-
380
- if (!verificationMethod) {
381
- throw new ProofVerificationError(
382
- PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,
383
- `Verification method not found for kid: ${kid}`,
384
- {
385
- did,
386
- kid,
387
- availableKids: didDoc.verificationMethod.map(
388
- (vm: { id: string }) => vm.id
389
- ),
390
- }
391
- );
392
- }
393
- } else {
394
- verificationMethod = didDoc.verificationMethod[0];
395
- }
396
-
397
- if (!verificationMethod?.publicKeyJwk) {
398
- throw new ProofVerificationError(
399
- PROOF_VERIFICATION_ERROR_CODES.PUBLIC_KEY_NOT_FOUND,
400
- `Public key JWK not found in verification method`,
401
- { did, kid, verificationMethodId: verificationMethod?.id }
402
- );
403
- }
404
-
405
- const jwk = verificationMethod.publicKeyJwk as {
406
- kty?: string;
407
- crv?: string;
408
- x?: string;
409
- [key: string]: unknown;
410
- };
411
-
412
- // Validate it's an Ed25519 key
413
- if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || !jwk.x) {
414
- throw new ProofVerificationError(
415
- PROOF_VERIFICATION_ERROR_CODES.INVALID_JWK_FORMAT,
416
- `Unsupported key type or curve: kty=${jwk.kty}, crv=${jwk.crv}`,
417
- { did, kid, jwk: { kty: jwk.kty, crv: jwk.crv } }
418
- );
419
- }
420
-
421
- return jwk as Ed25519JWK;
422
- } catch (error) {
423
- if (error instanceof ProofVerificationError) {
424
- throw error;
425
- }
426
- console.error(
427
- "[ProofVerifier] Failed to fetch public key from DID:",
428
- error
429
- );
430
- throw new ProofVerificationError(
431
- PROOF_VERIFICATION_ERROR_CODES.DID_RESOLUTION_FAILED,
432
- `DID resolution failed: ${error instanceof Error ? error.message : String(error)}`,
433
- {
434
- did,
435
- kid,
436
- originalError: error instanceof Error ? error.message : String(error),
437
- }
438
- );
439
- }
440
- }
441
-
442
- /**
443
- * Build canonical payload from proof meta
444
- *
445
- * CRITICAL: This must reconstruct the exact JWS payload structure that was originally signed.
446
- * The original JWS payload uses standard JWT claims (aud, sub, iss) plus custom proof claims,
447
- * NOT the proof.meta structure directly.
448
- *
449
- * @param meta - Proof metadata
450
- * @returns Canonical JSON string matching the original JWS payload structure
451
- */
452
- buildCanonicalPayload(meta: DetachedProof["meta"]): string {
453
- // Reconstruct the original JWS payload structure that was signed
454
- // This matches the structure used in proof generation (proof.ts, proof-generator.ts)
455
- const payload = {
456
- // Standard JWT claims (RFC 7519) - these are what was actually signed
457
- aud: meta.audience, // Audience (who the token is for)
458
- sub: meta.did, // Subject (agent DID)
459
- iss: meta.did, // Issuer (agent DID - self-issued)
460
-
461
- // Custom MCP-I proof claims
462
- requestHash: meta.requestHash,
463
- responseHash: meta.responseHash,
464
- ts: meta.ts,
465
- nonce: meta.nonce,
466
- sessionId: meta.sessionId,
467
-
468
- // Optional claims (only include if present)
469
- ...(meta.scopeId && { scopeId: meta.scopeId }),
470
- ...(meta.delegationRef && { delegationRef: meta.delegationRef }),
471
- ...(meta.clientDid && { clientDid: meta.clientDid }),
472
- };
473
-
474
- // Canonicalize the reconstructed payload using the same function as proof generation
475
- // CRITICAL: Must use json-canonicalize canonicalize() to match proof.ts exactly
476
- return canonicalize(payload);
477
- }
478
- }