@mcp-i/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +390 -0
  3. package/dist/auth/handshake.d.ts +104 -0
  4. package/dist/auth/handshake.d.ts.map +1 -0
  5. package/dist/auth/handshake.js +230 -0
  6. package/dist/auth/handshake.js.map +1 -0
  7. package/dist/auth/index.d.ts +3 -0
  8. package/dist/auth/index.d.ts.map +1 -0
  9. package/dist/auth/index.js +2 -0
  10. package/dist/auth/index.js.map +1 -0
  11. package/dist/auth/types.d.ts +31 -0
  12. package/dist/auth/types.d.ts.map +1 -0
  13. package/dist/auth/types.js +7 -0
  14. package/dist/auth/types.js.map +1 -0
  15. package/dist/delegation/audience-validator.d.ts +9 -0
  16. package/dist/delegation/audience-validator.d.ts.map +1 -0
  17. package/dist/delegation/audience-validator.js +17 -0
  18. package/dist/delegation/audience-validator.js.map +1 -0
  19. package/dist/delegation/bitstring.d.ts +37 -0
  20. package/dist/delegation/bitstring.d.ts.map +1 -0
  21. package/dist/delegation/bitstring.js +117 -0
  22. package/dist/delegation/bitstring.js.map +1 -0
  23. package/dist/delegation/cascading-revocation.d.ts +45 -0
  24. package/dist/delegation/cascading-revocation.d.ts.map +1 -0
  25. package/dist/delegation/cascading-revocation.js +148 -0
  26. package/dist/delegation/cascading-revocation.js.map +1 -0
  27. package/dist/delegation/delegation-graph.d.ts +49 -0
  28. package/dist/delegation/delegation-graph.d.ts.map +1 -0
  29. package/dist/delegation/delegation-graph.js +99 -0
  30. package/dist/delegation/delegation-graph.js.map +1 -0
  31. package/dist/delegation/did-key-resolver.d.ts +64 -0
  32. package/dist/delegation/did-key-resolver.d.ts.map +1 -0
  33. package/dist/delegation/did-key-resolver.js +154 -0
  34. package/dist/delegation/did-key-resolver.js.map +1 -0
  35. package/dist/delegation/did-web-resolver.d.ts +83 -0
  36. package/dist/delegation/did-web-resolver.d.ts.map +1 -0
  37. package/dist/delegation/did-web-resolver.js +218 -0
  38. package/dist/delegation/did-web-resolver.js.map +1 -0
  39. package/dist/delegation/index.d.ts +21 -0
  40. package/dist/delegation/index.d.ts.map +1 -0
  41. package/dist/delegation/index.js +21 -0
  42. package/dist/delegation/index.js.map +1 -0
  43. package/dist/delegation/outbound-headers.d.ts +81 -0
  44. package/dist/delegation/outbound-headers.d.ts.map +1 -0
  45. package/dist/delegation/outbound-headers.js +139 -0
  46. package/dist/delegation/outbound-headers.js.map +1 -0
  47. package/dist/delegation/outbound-proof.d.ts +43 -0
  48. package/dist/delegation/outbound-proof.d.ts.map +1 -0
  49. package/dist/delegation/outbound-proof.js +52 -0
  50. package/dist/delegation/outbound-proof.js.map +1 -0
  51. package/dist/delegation/statuslist-manager.d.ts +44 -0
  52. package/dist/delegation/statuslist-manager.d.ts.map +1 -0
  53. package/dist/delegation/statuslist-manager.js +126 -0
  54. package/dist/delegation/statuslist-manager.js.map +1 -0
  55. package/dist/delegation/storage/memory-graph-storage.d.ts +70 -0
  56. package/dist/delegation/storage/memory-graph-storage.d.ts.map +1 -0
  57. package/dist/delegation/storage/memory-graph-storage.js +145 -0
  58. package/dist/delegation/storage/memory-graph-storage.js.map +1 -0
  59. package/dist/delegation/storage/memory-statuslist-storage.d.ts +19 -0
  60. package/dist/delegation/storage/memory-statuslist-storage.d.ts.map +1 -0
  61. package/dist/delegation/storage/memory-statuslist-storage.js +33 -0
  62. package/dist/delegation/storage/memory-statuslist-storage.js.map +1 -0
  63. package/dist/delegation/utils.d.ts +49 -0
  64. package/dist/delegation/utils.d.ts.map +1 -0
  65. package/dist/delegation/utils.js +131 -0
  66. package/dist/delegation/utils.js.map +1 -0
  67. package/dist/delegation/vc-issuer.d.ts +56 -0
  68. package/dist/delegation/vc-issuer.d.ts.map +1 -0
  69. package/dist/delegation/vc-issuer.js +80 -0
  70. package/dist/delegation/vc-issuer.js.map +1 -0
  71. package/dist/delegation/vc-verifier.d.ts +112 -0
  72. package/dist/delegation/vc-verifier.d.ts.map +1 -0
  73. package/dist/delegation/vc-verifier.js +280 -0
  74. package/dist/delegation/vc-verifier.js.map +1 -0
  75. package/dist/index.d.ts +45 -0
  76. package/dist/index.d.ts.map +1 -0
  77. package/dist/index.js +53 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/logging/index.d.ts +2 -0
  80. package/dist/logging/index.d.ts.map +1 -0
  81. package/dist/logging/index.js +2 -0
  82. package/dist/logging/index.js.map +1 -0
  83. package/dist/logging/logger.d.ts +23 -0
  84. package/dist/logging/logger.d.ts.map +1 -0
  85. package/dist/logging/logger.js +82 -0
  86. package/dist/logging/logger.js.map +1 -0
  87. package/dist/middleware/index.d.ts +7 -0
  88. package/dist/middleware/index.d.ts.map +1 -0
  89. package/dist/middleware/index.js +7 -0
  90. package/dist/middleware/index.js.map +1 -0
  91. package/dist/middleware/with-mcpi.d.ts +152 -0
  92. package/dist/middleware/with-mcpi.d.ts.map +1 -0
  93. package/dist/middleware/with-mcpi.js +472 -0
  94. package/dist/middleware/with-mcpi.js.map +1 -0
  95. package/dist/proof/errors.d.ts +49 -0
  96. package/dist/proof/errors.d.ts.map +1 -0
  97. package/dist/proof/errors.js +61 -0
  98. package/dist/proof/errors.js.map +1 -0
  99. package/dist/proof/generator.d.ts +65 -0
  100. package/dist/proof/generator.d.ts.map +1 -0
  101. package/dist/proof/generator.js +163 -0
  102. package/dist/proof/generator.js.map +1 -0
  103. package/dist/proof/index.d.ts +4 -0
  104. package/dist/proof/index.d.ts.map +1 -0
  105. package/dist/proof/index.js +4 -0
  106. package/dist/proof/index.js.map +1 -0
  107. package/dist/proof/verifier.d.ts +108 -0
  108. package/dist/proof/verifier.d.ts.map +1 -0
  109. package/dist/proof/verifier.js +299 -0
  110. package/dist/proof/verifier.js.map +1 -0
  111. package/dist/providers/base.d.ts +64 -0
  112. package/dist/providers/base.d.ts.map +1 -0
  113. package/dist/providers/base.js +19 -0
  114. package/dist/providers/base.js.map +1 -0
  115. package/dist/providers/index.d.ts +3 -0
  116. package/dist/providers/index.d.ts.map +1 -0
  117. package/dist/providers/index.js +3 -0
  118. package/dist/providers/index.js.map +1 -0
  119. package/dist/providers/memory.d.ts +33 -0
  120. package/dist/providers/memory.d.ts.map +1 -0
  121. package/dist/providers/memory.js +102 -0
  122. package/dist/providers/memory.js.map +1 -0
  123. package/dist/session/index.d.ts +2 -0
  124. package/dist/session/index.d.ts.map +1 -0
  125. package/dist/session/index.js +2 -0
  126. package/dist/session/index.js.map +1 -0
  127. package/dist/session/manager.d.ts +77 -0
  128. package/dist/session/manager.d.ts.map +1 -0
  129. package/dist/session/manager.js +251 -0
  130. package/dist/session/manager.js.map +1 -0
  131. package/dist/types/protocol.d.ts +320 -0
  132. package/dist/types/protocol.d.ts.map +1 -0
  133. package/dist/types/protocol.js +229 -0
  134. package/dist/types/protocol.js.map +1 -0
  135. package/dist/utils/base58.d.ts +31 -0
  136. package/dist/utils/base58.d.ts.map +1 -0
  137. package/dist/utils/base58.js +104 -0
  138. package/dist/utils/base58.js.map +1 -0
  139. package/dist/utils/base64.d.ts +13 -0
  140. package/dist/utils/base64.d.ts.map +1 -0
  141. package/dist/utils/base64.js +99 -0
  142. package/dist/utils/base64.js.map +1 -0
  143. package/dist/utils/crypto-service.d.ts +37 -0
  144. package/dist/utils/crypto-service.d.ts.map +1 -0
  145. package/dist/utils/crypto-service.js +153 -0
  146. package/dist/utils/crypto-service.js.map +1 -0
  147. package/dist/utils/did-helpers.d.ts +156 -0
  148. package/dist/utils/did-helpers.d.ts.map +1 -0
  149. package/dist/utils/did-helpers.js +193 -0
  150. package/dist/utils/did-helpers.js.map +1 -0
  151. package/dist/utils/ed25519-constants.d.ts +18 -0
  152. package/dist/utils/ed25519-constants.d.ts.map +1 -0
  153. package/dist/utils/ed25519-constants.js +21 -0
  154. package/dist/utils/ed25519-constants.js.map +1 -0
  155. package/dist/utils/index.d.ts +5 -0
  156. package/dist/utils/index.d.ts.map +1 -0
  157. package/dist/utils/index.js +5 -0
  158. package/dist/utils/index.js.map +1 -0
  159. package/package.json +105 -0
  160. package/src/__tests__/integration/full-flow.test.ts +362 -0
  161. package/src/__tests__/providers/base.test.ts +173 -0
  162. package/src/__tests__/providers/memory.test.ts +332 -0
  163. package/src/__tests__/utils/mock-providers.ts +319 -0
  164. package/src/__tests__/utils/node-crypto-provider.ts +93 -0
  165. package/src/auth/handshake.ts +411 -0
  166. package/src/auth/index.ts +11 -0
  167. package/src/auth/types.ts +40 -0
  168. package/src/delegation/__tests__/audience-validator.test.ts +110 -0
  169. package/src/delegation/__tests__/bitstring.test.ts +346 -0
  170. package/src/delegation/__tests__/cascading-revocation.test.ts +624 -0
  171. package/src/delegation/__tests__/delegation-graph.test.ts +623 -0
  172. package/src/delegation/__tests__/did-key-resolver.test.ts +265 -0
  173. package/src/delegation/__tests__/did-web-resolver.test.ts +467 -0
  174. package/src/delegation/__tests__/outbound-headers.test.ts +230 -0
  175. package/src/delegation/__tests__/outbound-proof.test.ts +179 -0
  176. package/src/delegation/__tests__/statuslist-manager.test.ts +515 -0
  177. package/src/delegation/__tests__/utils.test.ts +185 -0
  178. package/src/delegation/__tests__/vc-issuer.test.ts +487 -0
  179. package/src/delegation/__tests__/vc-verifier.test.ts +1029 -0
  180. package/src/delegation/audience-validator.ts +24 -0
  181. package/src/delegation/bitstring.ts +160 -0
  182. package/src/delegation/cascading-revocation.ts +224 -0
  183. package/src/delegation/delegation-graph.ts +143 -0
  184. package/src/delegation/did-key-resolver.ts +181 -0
  185. package/src/delegation/did-web-resolver.ts +270 -0
  186. package/src/delegation/index.ts +33 -0
  187. package/src/delegation/outbound-headers.ts +193 -0
  188. package/src/delegation/outbound-proof.ts +90 -0
  189. package/src/delegation/statuslist-manager.ts +219 -0
  190. package/src/delegation/storage/__tests__/memory-graph-storage.test.ts +366 -0
  191. package/src/delegation/storage/__tests__/memory-statuslist-storage.test.ts +228 -0
  192. package/src/delegation/storage/memory-graph-storage.ts +178 -0
  193. package/src/delegation/storage/memory-statuslist-storage.ts +42 -0
  194. package/src/delegation/utils.ts +189 -0
  195. package/src/delegation/vc-issuer.ts +137 -0
  196. package/src/delegation/vc-verifier.ts +440 -0
  197. package/src/index.ts +264 -0
  198. package/src/logging/__tests__/logger.test.ts +366 -0
  199. package/src/logging/index.ts +6 -0
  200. package/src/logging/logger.ts +91 -0
  201. package/src/middleware/__tests__/with-mcpi.test.ts +504 -0
  202. package/src/middleware/index.ts +16 -0
  203. package/src/middleware/with-mcpi.ts +766 -0
  204. package/src/proof/__tests__/proof-generator.test.ts +483 -0
  205. package/src/proof/__tests__/verifier.test.ts +488 -0
  206. package/src/proof/errors.ts +75 -0
  207. package/src/proof/generator.ts +255 -0
  208. package/src/proof/index.ts +22 -0
  209. package/src/proof/verifier.ts +449 -0
  210. package/src/providers/base.ts +68 -0
  211. package/src/providers/index.ts +15 -0
  212. package/src/providers/memory.ts +130 -0
  213. package/src/session/__tests__/session-manager.test.ts +342 -0
  214. package/src/session/index.ts +7 -0
  215. package/src/session/manager.ts +332 -0
  216. package/src/types/protocol.ts +596 -0
  217. package/src/utils/__tests__/base58.test.ts +281 -0
  218. package/src/utils/__tests__/base64.test.ts +239 -0
  219. package/src/utils/__tests__/crypto-service.test.ts +530 -0
  220. package/src/utils/__tests__/did-helpers.test.ts +156 -0
  221. package/src/utils/base58.ts +115 -0
  222. package/src/utils/base64.ts +116 -0
  223. package/src/utils/crypto-service.ts +209 -0
  224. package/src/utils/did-helpers.ts +210 -0
  225. package/src/utils/ed25519-constants.ts +23 -0
  226. package/src/utils/index.ts +9 -0
@@ -0,0 +1,449 @@
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 "../utils/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
+ validateDetachedProof,
15
+ type DetachedProof,
16
+ } from "../types/protocol.js";
17
+ import { canonicalize } from "json-canonicalize";
18
+ import {
19
+ ProofVerificationError,
20
+ PROOF_VERIFICATION_ERROR_CODES,
21
+ type ProofVerificationErrorCode,
22
+ } from "./errors.js";
23
+ import { logger } from "../logging/index.js";
24
+
25
+ export interface ProofVerificationResult {
26
+ valid: boolean;
27
+ reason?: string;
28
+ error?: Error;
29
+ errorCode?: ProofVerificationErrorCode;
30
+ details?: Record<string, unknown>;
31
+ }
32
+
33
+ export interface ProofVerifierConfig {
34
+ cryptoProvider: CryptoProvider;
35
+ clockProvider: ClockProvider;
36
+ nonceCacheProvider: NonceCacheProvider;
37
+ fetchProvider: FetchProvider;
38
+ timestampSkewSeconds?: number;
39
+ nonceTtlSeconds?: number;
40
+ }
41
+
42
+ export class ProofVerifier {
43
+ private cryptoService: CryptoService;
44
+ private clock: ClockProvider;
45
+ private nonceCache: NonceCacheProvider;
46
+ private fetch: FetchProvider;
47
+ private timestampSkewSeconds: number;
48
+ private nonceTtlSeconds: number;
49
+
50
+ constructor(config: ProofVerifierConfig) {
51
+ this.cryptoService = new CryptoService(config.cryptoProvider);
52
+ this.clock = config.clockProvider;
53
+ this.nonceCache = config.nonceCacheProvider;
54
+ this.fetch = config.fetchProvider;
55
+ this.timestampSkewSeconds = config.timestampSkewSeconds ?? 300; // Default 5 minutes
56
+ this.nonceTtlSeconds = config.nonceTtlSeconds ?? 300; // Default 5 minutes
57
+ }
58
+
59
+ /**
60
+ * Verify a DetachedProof
61
+ * Automatically reconstructs canonical payload from proof.meta for signature verification
62
+ * @param proof - The proof to verify
63
+ * @param publicKeyJwk - Ed25519 public key in JWK format (from DID document)
64
+ * @returns Verification result
65
+ */
66
+ async verifyProof(
67
+ proof: DetachedProof,
68
+ publicKeyJwk: Ed25519JWK
69
+ ): Promise<ProofVerificationResult> {
70
+ try {
71
+ // Reconstruct canonical payload from proof meta
72
+ const canonicalPayloadString = this.buildCanonicalPayload(proof.meta);
73
+ const canonicalPayloadBytes = new TextEncoder().encode(
74
+ canonicalPayloadString
75
+ );
76
+
77
+ return await this.runVerificationPipeline(proof, publicKeyJwk, canonicalPayloadBytes);
78
+ } catch (error) {
79
+ return this.handleVerificationError(error);
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Verify proof with detached payload (for CLI/verifier compatibility)
85
+ * @param proof - The proof to verify
86
+ * @param canonicalPayload - Canonical JSON payload (for detached JWS) as string or Uint8Array
87
+ * @param publicKeyJwk - Ed25519 public key in JWK format
88
+ * @returns Verification result
89
+ */
90
+ async verifyProofDetached(
91
+ proof: DetachedProof,
92
+ canonicalPayload: string | Uint8Array,
93
+ publicKeyJwk: Ed25519JWK
94
+ ): Promise<ProofVerificationResult> {
95
+ try {
96
+ // Convert canonical payload to Uint8Array if needed
97
+ const canonicalPayloadBytes =
98
+ canonicalPayload instanceof Uint8Array
99
+ ? canonicalPayload
100
+ : new TextEncoder().encode(canonicalPayload);
101
+
102
+ return await this.runVerificationPipeline(proof, publicKeyJwk, canonicalPayloadBytes);
103
+ } catch (error) {
104
+ return this.handleVerificationError(error);
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Shared verification pipeline for proof verification
110
+ * @private
111
+ */
112
+ private async runVerificationPipeline(
113
+ proof: DetachedProof,
114
+ publicKeyJwk: Ed25519JWK,
115
+ canonicalPayloadBytes: Uint8Array
116
+ ): Promise<ProofVerificationResult> {
117
+ // 1. Validate proof structure
118
+ const structureValidation = await this.validateProofStructure(proof);
119
+ if (!structureValidation.valid) {
120
+ return structureValidation;
121
+ }
122
+ const validatedProof = structureValidation.proof!;
123
+
124
+ // 2. Check nonce replay protection (scoped to agent DID to prevent cross-agent replay attacks)
125
+ const nonceValidation = await this.validateNonce(
126
+ validatedProof.meta.nonce,
127
+ validatedProof.meta.did
128
+ );
129
+ if (!nonceValidation.valid) {
130
+ return nonceValidation;
131
+ }
132
+
133
+ // 3. Check timestamp skew
134
+ const timestampValidation = await this.validateTimestamp(
135
+ validatedProof.meta.ts
136
+ );
137
+ if (!timestampValidation.valid) {
138
+ return timestampValidation;
139
+ }
140
+
141
+ // 4. Verify JWS signature with canonical payload
142
+ const signatureValidation = await this.verifySignature(
143
+ validatedProof.jws,
144
+ publicKeyJwk,
145
+ canonicalPayloadBytes,
146
+ validatedProof.meta.kid
147
+ );
148
+ if (!signatureValidation.valid) {
149
+ return signatureValidation;
150
+ }
151
+
152
+ // 5. Add nonce to cache to prevent replay (scoped to agent DID)
153
+ await this.addNonceToCache(
154
+ validatedProof.meta.nonce,
155
+ validatedProof.meta.did
156
+ );
157
+
158
+ return { valid: true };
159
+ }
160
+
161
+ /**
162
+ * Handle verification errors consistently
163
+ * @private
164
+ */
165
+ private handleVerificationError(error: unknown): ProofVerificationResult {
166
+ return {
167
+ valid: false,
168
+ reason: "Proof verification error",
169
+ errorCode: PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_ERROR,
170
+ error: error instanceof Error ? error : new Error(String(error)),
171
+ details: {
172
+ errorMessage: error instanceof Error ? error.message : String(error),
173
+ },
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Validate proof structure
179
+ * @private
180
+ */
181
+ private async validateProofStructure(
182
+ proof: DetachedProof
183
+ ): Promise<ProofVerificationResult & { proof?: DetachedProof }> {
184
+ const validationResult = validateDetachedProof(proof);
185
+ if (!validationResult.success) {
186
+ return {
187
+ valid: false,
188
+ reason: "Invalid proof structure",
189
+ errorCode: PROOF_VERIFICATION_ERROR_CODES.INVALID_PROOF_STRUCTURE,
190
+ error: new Error(
191
+ `Proof validation failed: ${validationResult.error?.message}`
192
+ ),
193
+ details: {
194
+ validationError: validationResult.error?.message,
195
+ },
196
+ };
197
+ }
198
+ return {
199
+ valid: true,
200
+ proof: validationResult.data,
201
+ };
202
+ }
203
+
204
+ /**
205
+ * Validate nonce replay protection
206
+ * @private
207
+ */
208
+ private async validateNonce(
209
+ nonce: string,
210
+ agentDid?: string
211
+ ): Promise<ProofVerificationResult> {
212
+ const nonceUsed = await this.nonceCache.has(nonce, agentDid);
213
+ if (nonceUsed) {
214
+ return {
215
+ valid: false,
216
+ reason: "Nonce already used (replay attack detected)",
217
+ errorCode: PROOF_VERIFICATION_ERROR_CODES.NONCE_REPLAY_DETECTED,
218
+ details: {
219
+ nonce,
220
+ agentDid,
221
+ },
222
+ };
223
+ }
224
+ return { valid: true };
225
+ }
226
+
227
+ /**
228
+ * Validate timestamp skew
229
+ * @private
230
+ */
231
+ private async validateTimestamp(
232
+ timestamp: number
233
+ ): Promise<ProofVerificationResult> {
234
+ // Convert seconds to milliseconds for clock provider (which uses Date.now())
235
+ const timestampMs = timestamp * 1000;
236
+ if (!this.clock.isWithinSkew(timestampMs, this.timestampSkewSeconds)) {
237
+ return {
238
+ valid: false,
239
+ reason: `Timestamp out of skew window (skew: ${this.timestampSkewSeconds}s)`,
240
+ errorCode: PROOF_VERIFICATION_ERROR_CODES.TIMESTAMP_SKEW_EXCEEDED,
241
+ details: {
242
+ timestamp,
243
+ timestampMs,
244
+ skewSeconds: this.timestampSkewSeconds,
245
+ currentTime: this.clock.now(),
246
+ },
247
+ };
248
+ }
249
+ return { valid: true };
250
+ }
251
+
252
+ /**
253
+ * Verify JWS signature
254
+ * @private
255
+ */
256
+ private async verifySignature(
257
+ jws: string,
258
+ publicKeyJwk: Ed25519JWK,
259
+ canonicalPayloadBytes: Uint8Array,
260
+ expectedKid?: string
261
+ ): Promise<ProofVerificationResult> {
262
+ const signatureValid = await this.cryptoService.verifyJWS(
263
+ jws,
264
+ publicKeyJwk,
265
+ {
266
+ detachedPayload: canonicalPayloadBytes,
267
+ expectedKid,
268
+ alg: "EdDSA",
269
+ }
270
+ );
271
+
272
+ if (!signatureValid) {
273
+ return {
274
+ valid: false,
275
+ reason: "Invalid JWS signature",
276
+ errorCode: PROOF_VERIFICATION_ERROR_CODES.INVALID_JWS_SIGNATURE,
277
+ details: {
278
+ jwsLength: jws.length,
279
+ expectedKid,
280
+ actualKid: publicKeyJwk.kid,
281
+ },
282
+ };
283
+ }
284
+
285
+ return { valid: true };
286
+ }
287
+
288
+ /**
289
+ * Add nonce to cache to prevent replay (scoped to agent DID)
290
+ * @private
291
+ */
292
+ private async addNonceToCache(
293
+ nonce: string,
294
+ agentDid: string
295
+ ): Promise<void> {
296
+ // Pass TTL in seconds, not absolute timestamp
297
+ await this.nonceCache.add(nonce, this.nonceTtlSeconds, agentDid);
298
+ }
299
+
300
+ /**
301
+ * Fetch public key from DID document
302
+ * @param did - DID to resolve
303
+ * @param kid - Key ID (optional, defaults to first verification method)
304
+ * @returns Ed25519 JWK or null if not found
305
+ * @throws {ProofVerificationError} If DID resolution fails with specific error code
306
+ */
307
+ async fetchPublicKeyFromDID(
308
+ did: string,
309
+ kid?: string
310
+ ): Promise<Ed25519JWK | null> {
311
+ try {
312
+ const didDoc = await this.fetch.resolveDID(did);
313
+
314
+ if (!didDoc) {
315
+ throw new ProofVerificationError(
316
+ PROOF_VERIFICATION_ERROR_CODES.DID_DOCUMENT_NOT_FOUND,
317
+ `DID document not found: ${did}`,
318
+ { did }
319
+ );
320
+ }
321
+
322
+ const doc = didDoc as {
323
+ verificationMethod?: Array<{ id: string; publicKeyJwk?: unknown }>;
324
+ };
325
+
326
+ if (
327
+ !doc.verificationMethod ||
328
+ doc.verificationMethod.length === 0
329
+ ) {
330
+ throw new ProofVerificationError(
331
+ PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,
332
+ `No verification methods found in DID document: ${did}`,
333
+ { did }
334
+ );
335
+ }
336
+
337
+ // Find verification method by kid or use first one
338
+ let verificationMethod:
339
+ | { id: string; publicKeyJwk?: unknown }
340
+ | undefined;
341
+ if (kid) {
342
+ const kidWithHash = kid.startsWith("#") ? kid : `#${kid}`;
343
+ verificationMethod = doc.verificationMethod.find(
344
+ (vm: { id: string }) =>
345
+ vm.id === kidWithHash || vm.id === `${did}${kidWithHash}`
346
+ );
347
+
348
+ if (!verificationMethod) {
349
+ throw new ProofVerificationError(
350
+ PROOF_VERIFICATION_ERROR_CODES.VERIFICATION_METHOD_NOT_FOUND,
351
+ `Verification method not found for kid: ${kid}`,
352
+ {
353
+ did,
354
+ kid,
355
+ availableKids: doc.verificationMethod.map(
356
+ (vm: { id: string }) => vm.id
357
+ ),
358
+ }
359
+ );
360
+ }
361
+ } else {
362
+ verificationMethod = doc.verificationMethod[0];
363
+ }
364
+
365
+ if (!verificationMethod?.publicKeyJwk) {
366
+ throw new ProofVerificationError(
367
+ PROOF_VERIFICATION_ERROR_CODES.PUBLIC_KEY_NOT_FOUND,
368
+ `Public key JWK not found in verification method`,
369
+ { did, kid, verificationMethodId: verificationMethod?.id }
370
+ );
371
+ }
372
+
373
+ const jwk = verificationMethod.publicKeyJwk as {
374
+ kty?: string;
375
+ crv?: string;
376
+ x?: string;
377
+ [key: string]: unknown;
378
+ };
379
+
380
+ // Validate it's an Ed25519 key
381
+ if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || !jwk.x) {
382
+ throw new ProofVerificationError(
383
+ PROOF_VERIFICATION_ERROR_CODES.INVALID_JWK_FORMAT,
384
+ `Unsupported key type or curve: kty=${jwk.kty}, crv=${jwk.crv}`,
385
+ { did, kid, jwk: { kty: jwk.kty, crv: jwk.crv } }
386
+ );
387
+ }
388
+
389
+ // Set kid from verification method ID so downstream kid-matching works
390
+ const result = jwk as Ed25519JWK;
391
+ if (!result.kid && verificationMethod.id) {
392
+ result.kid = verificationMethod.id;
393
+ }
394
+
395
+ return result;
396
+ } catch (error) {
397
+ if (error instanceof ProofVerificationError) {
398
+ throw error;
399
+ }
400
+ logger.error("[ProofVerifier] Failed to fetch public key from DID", { error });
401
+ throw new ProofVerificationError(
402
+ PROOF_VERIFICATION_ERROR_CODES.DID_RESOLUTION_FAILED,
403
+ `DID resolution failed: ${error instanceof Error ? error.message : String(error)}`,
404
+ {
405
+ did,
406
+ kid,
407
+ originalError: error instanceof Error ? error.message : String(error),
408
+ }
409
+ );
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Build canonical payload from proof meta
415
+ *
416
+ * CRITICAL: This must reconstruct the exact JWS payload structure that was originally signed.
417
+ * The original JWS payload uses standard JWT claims (aud, sub, iss) plus custom proof claims,
418
+ * NOT the proof.meta structure directly.
419
+ *
420
+ * @param meta - Proof metadata
421
+ * @returns Canonical JSON string matching the original JWS payload structure
422
+ */
423
+ buildCanonicalPayload(meta: DetachedProof["meta"]): string {
424
+ // Reconstruct the original JWS payload structure that was signed
425
+ // This matches the structure used in proof generation (proof.ts, proof-generator.ts)
426
+ const payload = {
427
+ // Standard JWT claims (RFC 7519) - these are what was actually signed
428
+ aud: meta.audience, // Audience (who the token is for)
429
+ sub: meta.did, // Subject (agent DID)
430
+ iss: meta.did, // Issuer (agent DID - self-issued)
431
+
432
+ // Custom MCP-I proof claims
433
+ requestHash: meta.requestHash,
434
+ responseHash: meta.responseHash,
435
+ ts: meta.ts,
436
+ nonce: meta.nonce,
437
+ sessionId: meta.sessionId,
438
+
439
+ // Optional claims (only include if present)
440
+ ...(meta.scopeId && { scopeId: meta.scopeId }),
441
+ ...(meta.delegationRef && { delegationRef: meta.delegationRef }),
442
+ ...(meta.clientDid && { clientDid: meta.clientDid }),
443
+ };
444
+
445
+ // Canonicalize the reconstructed payload using the same function as proof generation
446
+ // CRITICAL: Must use json-canonicalize canonicalize() to match proof.ts exactly
447
+ return canonicalize(payload);
448
+ }
449
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Base Provider Classes
3
+ *
4
+ * Abstract classes that define the provider interfaces for
5
+ * platform-specific implementations.
6
+ */
7
+
8
+ import type { DIDDocument } from '../delegation/vc-verifier.js';
9
+ import type { StatusList2021Credential, DelegationRecord } from '../types/protocol.js';
10
+
11
+ export abstract class CryptoProvider {
12
+ abstract sign(data: Uint8Array, privateKey: string): Promise<Uint8Array>;
13
+ abstract verify(data: Uint8Array, signature: Uint8Array, publicKey: string): Promise<boolean>;
14
+ abstract generateKeyPair(): Promise<{ privateKey: string; publicKey: string }>;
15
+ /**
16
+ * Compute SHA-256 hash of data.
17
+ * Returns "sha256:<hex>" format for cross-platform parity.
18
+ */
19
+ abstract hash(data: Uint8Array): Promise<string>;
20
+ abstract randomBytes(length: number): Promise<Uint8Array>;
21
+ }
22
+
23
+ export abstract class ClockProvider {
24
+ abstract now(): number;
25
+ abstract isWithinSkew(timestamp: number, skewSeconds: number): boolean;
26
+ abstract hasExpired(expiresAt: number): boolean;
27
+ abstract calculateExpiry(ttlSeconds: number): number;
28
+ abstract format(timestamp: number): string;
29
+ }
30
+
31
+ export abstract class FetchProvider {
32
+ abstract resolveDID(did: string): Promise<DIDDocument | null>;
33
+ abstract fetchStatusList(url: string): Promise<StatusList2021Credential | null>;
34
+ abstract fetchDelegationChain(id: string): Promise<DelegationRecord[]>;
35
+ abstract fetch(url: string, options?: unknown): Promise<Response>;
36
+ }
37
+
38
+ export abstract class StorageProvider {
39
+ abstract get(key: string): Promise<string | null>;
40
+ abstract set(key: string, value: string): Promise<void>;
41
+ abstract delete(key: string): Promise<void>;
42
+ abstract exists(key: string): Promise<boolean>;
43
+ abstract list(prefix?: string): Promise<string[]>;
44
+ }
45
+
46
+ export abstract class NonceCacheProvider {
47
+ abstract has(nonce: string, agentDid?: string): Promise<boolean>;
48
+ abstract add(nonce: string, ttlSeconds: number, agentDid?: string): Promise<void>;
49
+ abstract cleanup(): Promise<void>;
50
+ abstract destroy(): Promise<void>;
51
+ }
52
+
53
+ export interface AgentIdentity {
54
+ did: string;
55
+ kid: string;
56
+ privateKey: string;
57
+ publicKey: string;
58
+ createdAt: string;
59
+ type: 'development' | 'production';
60
+ metadata?: Record<string, unknown>;
61
+ }
62
+
63
+ export abstract class IdentityProvider {
64
+ abstract getIdentity(): Promise<AgentIdentity>;
65
+ abstract saveIdentity(identity: AgentIdentity): Promise<void>;
66
+ abstract rotateKeys(): Promise<AgentIdentity>;
67
+ abstract deleteIdentity(): Promise<void>;
68
+ }
@@ -0,0 +1,15 @@
1
+ export {
2
+ CryptoProvider,
3
+ ClockProvider,
4
+ FetchProvider,
5
+ StorageProvider,
6
+ NonceCacheProvider,
7
+ IdentityProvider,
8
+ type AgentIdentity,
9
+ } from './base.js';
10
+
11
+ export {
12
+ MemoryStorageProvider,
13
+ MemoryNonceCacheProvider,
14
+ MemoryIdentityProvider,
15
+ } from './memory.js';
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Memory-based provider implementations
3
+ *
4
+ * Simple in-memory implementations for development and testing.
5
+ */
6
+
7
+ import {
8
+ CryptoProvider,
9
+ StorageProvider,
10
+ NonceCacheProvider,
11
+ IdentityProvider,
12
+ type AgentIdentity,
13
+ } from './base.js';
14
+ import { generateDidKeyFromBase64 } from '../utils/did-helpers.js';
15
+
16
+ export class MemoryStorageProvider extends StorageProvider {
17
+ private store: Map<string, string> = new Map();
18
+
19
+ async get(key: string): Promise<string | null> {
20
+ return this.store.get(key) ?? null;
21
+ }
22
+
23
+ async set(key: string, value: string): Promise<void> {
24
+ this.store.set(key, value);
25
+ }
26
+
27
+ async delete(key: string): Promise<void> {
28
+ this.store.delete(key);
29
+ }
30
+
31
+ async exists(key: string): Promise<boolean> {
32
+ return this.store.has(key);
33
+ }
34
+
35
+ async list(prefix?: string): Promise<string[]> {
36
+ const keys = Array.from(this.store.keys());
37
+ if (prefix) {
38
+ return keys.filter((k) => k.startsWith(prefix));
39
+ }
40
+ return keys;
41
+ }
42
+ }
43
+
44
+ export class MemoryNonceCacheProvider extends NonceCacheProvider {
45
+ private nonces: Map<string, number> = new Map();
46
+
47
+ async has(nonce: string, agentDid?: string): Promise<boolean> {
48
+ const key = agentDid ? `nonce:${agentDid}:${nonce}` : `nonce:${nonce}`;
49
+ const expiry = this.nonces.get(key);
50
+ if (!expiry) return false;
51
+
52
+ if (Date.now() > expiry) {
53
+ this.nonces.delete(key);
54
+ return false;
55
+ }
56
+
57
+ return true;
58
+ }
59
+
60
+ async add(nonce: string, ttlSeconds: number, agentDid?: string): Promise<void> {
61
+ const key = agentDid ? `nonce:${agentDid}:${nonce}` : `nonce:${nonce}`;
62
+ const expiresAt = Date.now() + ttlSeconds * 1000;
63
+ this.nonces.set(key, expiresAt);
64
+ }
65
+
66
+ async cleanup(): Promise<void> {
67
+ const now = Date.now();
68
+ for (const [nonce, expiry] of this.nonces) {
69
+ if (now > expiry) {
70
+ this.nonces.delete(nonce);
71
+ }
72
+ }
73
+ }
74
+
75
+ async destroy(): Promise<void> {
76
+ this.nonces.clear();
77
+ }
78
+ }
79
+
80
+ export class MemoryIdentityProvider extends IdentityProvider {
81
+ private identity?: AgentIdentity;
82
+ private cryptoProvider: CryptoProvider | undefined;
83
+
84
+ constructor(cryptoProvider?: CryptoProvider) {
85
+ super();
86
+ this.cryptoProvider = cryptoProvider;
87
+ }
88
+
89
+ async getIdentity(): Promise<AgentIdentity> {
90
+ if (!this.identity) {
91
+ this.identity = await this.generateIdentity();
92
+ }
93
+ return this.identity;
94
+ }
95
+
96
+ async saveIdentity(identity: AgentIdentity): Promise<void> {
97
+ this.identity = identity;
98
+ }
99
+
100
+ async rotateKeys(): Promise<AgentIdentity> {
101
+ this.identity = await this.generateIdentity();
102
+ return this.identity;
103
+ }
104
+
105
+ async deleteIdentity(): Promise<void> {
106
+ this.identity = undefined;
107
+ }
108
+
109
+ private async generateIdentity(): Promise<AgentIdentity> {
110
+ if (!this.cryptoProvider) {
111
+ throw new Error('Crypto provider required for identity generation');
112
+ }
113
+
114
+ const keyPair = await this.cryptoProvider.generateKeyPair();
115
+ const did = this.generateDIDFromPublicKey(keyPair.publicKey);
116
+
117
+ return {
118
+ did,
119
+ kid: `${did}#keys-1`,
120
+ privateKey: keyPair.privateKey,
121
+ publicKey: keyPair.publicKey,
122
+ createdAt: new Date().toISOString(),
123
+ type: 'development',
124
+ };
125
+ }
126
+
127
+ private generateDIDFromPublicKey(publicKey: string): string {
128
+ return generateDidKeyFromBase64(publicKey);
129
+ }
130
+ }