@kya-os/mcp-i-runtime 1.0.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 (366) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/dist/auth/handshake.d.ts +136 -0
  3. package/dist/auth/handshake.d.ts.map +1 -0
  4. package/dist/auth/handshake.js +276 -0
  5. package/dist/auth/handshake.js.map +1 -0
  6. package/dist/auth/index.d.ts +6 -0
  7. package/dist/auth/index.d.ts.map +1 -0
  8. package/dist/auth/index.js +12 -0
  9. package/dist/auth/index.js.map +1 -0
  10. package/dist/auth/types.d.ts +52 -0
  11. package/dist/auth/types.d.ts.map +1 -0
  12. package/dist/auth/types.js +10 -0
  13. package/dist/auth/types.js.map +1 -0
  14. package/dist/cache/oauth-config-cache.d.ts +69 -0
  15. package/dist/cache/oauth-config-cache.d.ts.map +1 -0
  16. package/dist/cache/oauth-config-cache.js +76 -0
  17. package/dist/cache/oauth-config-cache.js.map +1 -0
  18. package/dist/cache/tool-protection-cache.d.ts +102 -0
  19. package/dist/cache/tool-protection-cache.d.ts.map +1 -0
  20. package/dist/cache/tool-protection-cache.js +131 -0
  21. package/dist/cache/tool-protection-cache.js.map +1 -0
  22. package/dist/compliance/index.d.ts +8 -0
  23. package/dist/compliance/index.d.ts.map +1 -0
  24. package/dist/compliance/index.js +24 -0
  25. package/dist/compliance/index.js.map +1 -0
  26. package/dist/compliance/schema-registry.d.ts +50 -0
  27. package/dist/compliance/schema-registry.d.ts.map +1 -0
  28. package/dist/compliance/schema-registry.js +438 -0
  29. package/dist/compliance/schema-registry.js.map +1 -0
  30. package/dist/compliance/schema-verifier.d.ts +110 -0
  31. package/dist/compliance/schema-verifier.d.ts.map +1 -0
  32. package/dist/compliance/schema-verifier.js +518 -0
  33. package/dist/compliance/schema-verifier.js.map +1 -0
  34. package/dist/config/remote-config.d.ts +188 -0
  35. package/dist/config/remote-config.d.ts.map +1 -0
  36. package/dist/config/remote-config.js +268 -0
  37. package/dist/config/remote-config.js.map +1 -0
  38. package/dist/config.d.ts +182 -0
  39. package/dist/config.d.ts.map +1 -0
  40. package/dist/config.js +148 -0
  41. package/dist/config.js.map +1 -0
  42. package/dist/identity/idp-token-resolver.d.ts +69 -0
  43. package/dist/identity/idp-token-resolver.d.ts.map +1 -0
  44. package/dist/identity/idp-token-resolver.js +136 -0
  45. package/dist/identity/idp-token-resolver.js.map +1 -0
  46. package/dist/identity/idp-token-storage.interface.d.ts +80 -0
  47. package/dist/identity/idp-token-storage.interface.d.ts.map +1 -0
  48. package/dist/identity/idp-token-storage.interface.js +14 -0
  49. package/dist/identity/idp-token-storage.interface.js.map +1 -0
  50. package/dist/identity/user-did-manager.d.ts +228 -0
  51. package/dist/identity/user-did-manager.d.ts.map +1 -0
  52. package/dist/identity/user-did-manager.js +356 -0
  53. package/dist/identity/user-did-manager.js.map +1 -0
  54. package/dist/index.d.ts +69 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.js +193 -0
  57. package/dist/index.js.map +1 -0
  58. package/dist/logging/index.d.ts +5 -0
  59. package/dist/logging/index.d.ts.map +1 -0
  60. package/dist/logging/index.js +10 -0
  61. package/dist/logging/index.js.map +1 -0
  62. package/dist/logging/logger.d.ts +33 -0
  63. package/dist/logging/logger.d.ts.map +1 -0
  64. package/dist/logging/logger.js +104 -0
  65. package/dist/logging/logger.js.map +1 -0
  66. package/dist/proof/generator.d.ts +109 -0
  67. package/dist/proof/generator.d.ts.map +1 -0
  68. package/dist/proof/generator.js +236 -0
  69. package/dist/proof/generator.js.map +1 -0
  70. package/dist/proof/index.d.ts +5 -0
  71. package/dist/proof/index.d.ts.map +1 -0
  72. package/dist/proof/index.js +11 -0
  73. package/dist/proof/index.js.map +1 -0
  74. package/dist/providers/base.d.ts +95 -0
  75. package/dist/providers/base.d.ts.map +1 -0
  76. package/dist/providers/base.js +47 -0
  77. package/dist/providers/base.js.map +1 -0
  78. package/dist/providers/memory.d.ts +42 -0
  79. package/dist/providers/memory.d.ts.map +1 -0
  80. package/dist/providers/memory.js +121 -0
  81. package/dist/providers/memory.js.map +1 -0
  82. package/dist/runtime/audit-logger.d.ts +37 -0
  83. package/dist/runtime/audit-logger.d.ts.map +1 -0
  84. package/dist/runtime/audit-logger.js +9 -0
  85. package/dist/runtime/audit-logger.js.map +1 -0
  86. package/dist/runtime/base.d.ts +392 -0
  87. package/dist/runtime/base.d.ts.map +1 -0
  88. package/dist/runtime/base.js +1527 -0
  89. package/dist/runtime/base.js.map +1 -0
  90. package/dist/runtime/dif-core.d.ts +33 -0
  91. package/dist/runtime/dif-core.d.ts.map +1 -0
  92. package/dist/runtime/dif-core.js +14 -0
  93. package/dist/runtime/dif-core.js.map +1 -0
  94. package/dist/runtime/ext-apps-constants.d.ts +20 -0
  95. package/dist/runtime/ext-apps-constants.d.ts.map +1 -0
  96. package/dist/runtime/ext-apps-constants.js +23 -0
  97. package/dist/runtime/ext-apps-constants.js.map +1 -0
  98. package/dist/services/access-control.service.d.ts +138 -0
  99. package/dist/services/access-control.service.d.ts.map +1 -0
  100. package/dist/services/access-control.service.js +721 -0
  101. package/dist/services/access-control.service.js.map +1 -0
  102. package/dist/services/authorization/authorization-registry.d.ts +29 -0
  103. package/dist/services/authorization/authorization-registry.d.ts.map +1 -0
  104. package/dist/services/authorization/authorization-registry.js +58 -0
  105. package/dist/services/authorization/authorization-registry.js.map +1 -0
  106. package/dist/services/authorization/types.d.ts +53 -0
  107. package/dist/services/authorization/types.d.ts.map +1 -0
  108. package/dist/services/authorization/types.js +10 -0
  109. package/dist/services/authorization/types.js.map +1 -0
  110. package/dist/services/batch-delegation.service.d.ts +53 -0
  111. package/dist/services/batch-delegation.service.d.ts.map +1 -0
  112. package/dist/services/batch-delegation.service.js +95 -0
  113. package/dist/services/batch-delegation.service.js.map +1 -0
  114. package/dist/services/crypto.service.d.ts +69 -0
  115. package/dist/services/crypto.service.d.ts.map +1 -0
  116. package/dist/services/crypto.service.js +225 -0
  117. package/dist/services/crypto.service.js.map +1 -0
  118. package/dist/services/delegation-error-formatter.d.ts +124 -0
  119. package/dist/services/delegation-error-formatter.d.ts.map +1 -0
  120. package/dist/services/delegation-error-formatter.js +214 -0
  121. package/dist/services/delegation-error-formatter.js.map +1 -0
  122. package/dist/services/errors.d.ts +49 -0
  123. package/dist/services/errors.d.ts.map +1 -0
  124. package/dist/services/errors.js +66 -0
  125. package/dist/services/errors.js.map +1 -0
  126. package/dist/services/index.d.ts +9 -0
  127. package/dist/services/index.d.ts.map +1 -0
  128. package/dist/services/index.js +15 -0
  129. package/dist/services/index.js.map +1 -0
  130. package/dist/services/oauth-config.service.d.ts +53 -0
  131. package/dist/services/oauth-config.service.d.ts.map +1 -0
  132. package/dist/services/oauth-config.service.js +141 -0
  133. package/dist/services/oauth-config.service.js.map +1 -0
  134. package/dist/services/oauth-provider-registry.d.ts +88 -0
  135. package/dist/services/oauth-provider-registry.d.ts.map +1 -0
  136. package/dist/services/oauth-provider-registry.js +128 -0
  137. package/dist/services/oauth-provider-registry.js.map +1 -0
  138. package/dist/services/oauth-service.d.ts +122 -0
  139. package/dist/services/oauth-service.d.ts.map +1 -0
  140. package/dist/services/oauth-service.js +442 -0
  141. package/dist/services/oauth-service.js.map +1 -0
  142. package/dist/services/oauth-token-retrieval.service.d.ts +49 -0
  143. package/dist/services/oauth-token-retrieval.service.d.ts.map +1 -0
  144. package/dist/services/oauth-token-retrieval.service.js +150 -0
  145. package/dist/services/oauth-token-retrieval.service.js.map +1 -0
  146. package/dist/services/policy.service.d.ts +130 -0
  147. package/dist/services/policy.service.d.ts.map +1 -0
  148. package/dist/services/policy.service.js +399 -0
  149. package/dist/services/policy.service.js.map +1 -0
  150. package/dist/services/proof-verifier.d.ts +103 -0
  151. package/dist/services/proof-verifier.d.ts.map +1 -0
  152. package/dist/services/proof-verifier.js +190 -0
  153. package/dist/services/proof-verifier.js.map +1 -0
  154. package/dist/services/provider-resolver.d.ts +89 -0
  155. package/dist/services/provider-resolver.d.ts.map +1 -0
  156. package/dist/services/provider-resolver.js +196 -0
  157. package/dist/services/provider-resolver.js.map +1 -0
  158. package/dist/services/provider-validator.d.ts +55 -0
  159. package/dist/services/provider-validator.d.ts.map +1 -0
  160. package/dist/services/provider-validator.js +135 -0
  161. package/dist/services/provider-validator.js.map +1 -0
  162. package/dist/services/session-registration.service.d.ts +80 -0
  163. package/dist/services/session-registration.service.d.ts.map +1 -0
  164. package/dist/services/session-registration.service.js +174 -0
  165. package/dist/services/session-registration.service.js.map +1 -0
  166. package/dist/services/storage.service.d.ts +116 -0
  167. package/dist/services/storage.service.d.ts.map +1 -0
  168. package/dist/services/storage.service.js +411 -0
  169. package/dist/services/storage.service.js.map +1 -0
  170. package/dist/services/tool-context-builder.d.ts +74 -0
  171. package/dist/services/tool-context-builder.d.ts.map +1 -0
  172. package/dist/services/tool-context-builder.js +215 -0
  173. package/dist/services/tool-context-builder.js.map +1 -0
  174. package/dist/services/tool-protection.service.d.ts +209 -0
  175. package/dist/services/tool-protection.service.d.ts.map +1 -0
  176. package/dist/services/tool-protection.service.js +752 -0
  177. package/dist/services/tool-protection.service.js.map +1 -0
  178. package/dist/session/index.d.ts +5 -0
  179. package/dist/session/index.d.ts.map +1 -0
  180. package/dist/session/index.js +11 -0
  181. package/dist/session/index.js.map +1 -0
  182. package/dist/session/manager.d.ts +118 -0
  183. package/dist/session/manager.d.ts.map +1 -0
  184. package/dist/session/manager.js +285 -0
  185. package/dist/session/manager.js.map +1 -0
  186. package/dist/types/oauth-required-error.d.ts +46 -0
  187. package/dist/types/oauth-required-error.d.ts.map +1 -0
  188. package/dist/types/oauth-required-error.js +42 -0
  189. package/dist/types/oauth-required-error.js.map +1 -0
  190. package/dist/types/tool-protection.d.ts +144 -0
  191. package/dist/types/tool-protection.d.ts.map +1 -0
  192. package/dist/types/tool-protection.js +48 -0
  193. package/dist/types/tool-protection.js.map +1 -0
  194. package/dist/utils/base58.d.ts +31 -0
  195. package/dist/utils/base58.d.ts.map +1 -0
  196. package/dist/utils/base58.js +103 -0
  197. package/dist/utils/base58.js.map +1 -0
  198. package/dist/utils/base64.d.ts +32 -0
  199. package/dist/utils/base64.d.ts.map +1 -0
  200. package/dist/utils/base64.js +172 -0
  201. package/dist/utils/base64.js.map +1 -0
  202. package/dist/utils/cors.d.ts +52 -0
  203. package/dist/utils/cors.d.ts.map +1 -0
  204. package/dist/utils/cors.js +79 -0
  205. package/dist/utils/cors.js.map +1 -0
  206. package/dist/utils/did-helpers.d.ts +168 -0
  207. package/dist/utils/did-helpers.d.ts.map +1 -0
  208. package/dist/utils/did-helpers.js +222 -0
  209. package/dist/utils/did-helpers.js.map +1 -0
  210. package/dist/utils/index.d.ts +8 -0
  211. package/dist/utils/index.d.ts.map +1 -0
  212. package/dist/utils/index.js +24 -0
  213. package/dist/utils/index.js.map +1 -0
  214. package/dist/utils/storage-keys.d.ts +120 -0
  215. package/dist/utils/storage-keys.d.ts.map +1 -0
  216. package/dist/utils/storage-keys.js +217 -0
  217. package/dist/utils/storage-keys.js.map +1 -0
  218. package/dist/wire-format.d.ts +62 -0
  219. package/dist/wire-format.d.ts.map +1 -0
  220. package/dist/wire-format.js +89 -0
  221. package/dist/wire-format.js.map +1 -0
  222. package/package.json +83 -0
  223. package/src/__tests__/cache/tool-protection-cache.test.ts +640 -0
  224. package/src/__tests__/config/provider-runtime-config.test.ts +309 -0
  225. package/src/__tests__/config.test.ts +307 -0
  226. package/src/__tests__/identity/user-did-manager.test.ts +232 -0
  227. package/src/__tests__/index.test.ts +56 -0
  228. package/src/__tests__/integration/full-flow.test.ts +779 -0
  229. package/src/__tests__/integration.test.ts +281 -0
  230. package/src/__tests__/providers/base.test.ts +173 -0
  231. package/src/__tests__/providers/memory.test.ts +319 -0
  232. package/src/__tests__/regression/phase2-regression.test.ts +406 -0
  233. package/src/__tests__/runtime/audit-logger.test.ts +154 -0
  234. package/src/__tests__/runtime/base-extensions.test.ts +595 -0
  235. package/src/__tests__/runtime/base.test.ts +1328 -0
  236. package/src/__tests__/runtime/delegation-flow.test.ts +159 -0
  237. package/src/__tests__/runtime/process-tool-call-security.test.ts +1024 -0
  238. package/src/__tests__/runtime/proof-client-did.test.ts +376 -0
  239. package/src/__tests__/runtime/provider-selection.test.ts +292 -0
  240. package/src/__tests__/runtime/route-interception.test.ts +670 -0
  241. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +989 -0
  242. package/src/__tests__/services/access-control-retry.test.ts +595 -0
  243. package/src/__tests__/services/agentshield-integration.test.ts +709 -0
  244. package/src/__tests__/services/cache-busting.test.ts +125 -0
  245. package/src/__tests__/services/oauth-service-errors.test.ts +704 -0
  246. package/src/__tests__/services/oauth-service-pkce.test.ts +556 -0
  247. package/src/__tests__/services/oauth-service-secret-resolution.test.ts +349 -0
  248. package/src/__tests__/services/provider-resolver-edge-cases.test.ts +591 -0
  249. package/src/__tests__/services/tool-protection-failsafe.test.ts +683 -0
  250. package/src/__tests__/services/tool-protection-merged-config.test.ts +664 -0
  251. package/src/__tests__/services/tool-protection-oauth-provider.test.ts +300 -0
  252. package/src/__tests__/services/tool-protection.service.test.ts +1201 -0
  253. package/src/__tests__/utils/mock-providers.ts +340 -0
  254. package/src/__tests__/wire-format.test.ts +123 -0
  255. package/src/auth/__tests__/resume-token.test.ts +42 -0
  256. package/src/auth/handshake.ts +476 -0
  257. package/src/auth/index.ts +15 -0
  258. package/src/auth/types.ts +68 -0
  259. package/src/cache/__tests__/oauth-config-cache.test.ts +215 -0
  260. package/src/cache/oauth-config-cache.d.ts +69 -0
  261. package/src/cache/oauth-config-cache.d.ts.map +1 -0
  262. package/src/cache/oauth-config-cache.js.map +1 -0
  263. package/src/cache/oauth-config-cache.ts +123 -0
  264. package/src/cache/tool-protection-cache.ts +184 -0
  265. package/src/compliance/EXAMPLE.md +412 -0
  266. package/src/compliance/__tests__/schema-verifier.test.ts +791 -0
  267. package/src/compliance/index.ts +8 -0
  268. package/src/compliance/schema-registry.ts +460 -0
  269. package/src/compliance/schema-verifier.ts +708 -0
  270. package/src/config/__tests__/merged-config.spec.ts +445 -0
  271. package/src/config/__tests__/remote-config-edge-cases.test.ts +424 -0
  272. package/src/config/__tests__/remote-config-helpers.test.ts +280 -0
  273. package/src/config/__tests__/remote-config.spec.ts +265 -0
  274. package/src/config/remote-config.ts +368 -0
  275. package/src/config.ts +312 -0
  276. package/src/identity/__tests__/idp-token-resolver.test.ts +340 -0
  277. package/src/identity/__tests__/user-did-manager.test.ts +487 -0
  278. package/src/identity/idp-token-resolver.ts +181 -0
  279. package/src/identity/idp-token-storage.interface.ts +102 -0
  280. package/src/identity/user-did-manager.ts +592 -0
  281. package/src/index.ts +331 -0
  282. package/src/logging/__tests__/logger.test.ts +366 -0
  283. package/src/logging/index.ts +10 -0
  284. package/src/logging/logger.ts +112 -0
  285. package/src/proof/__tests__/crypto-parity.test.ts +202 -0
  286. package/src/proof/__tests__/proof-generator.test.ts +484 -0
  287. package/src/proof/generator.ts +347 -0
  288. package/src/proof/index.ts +12 -0
  289. package/src/providers/base.d.ts +91 -0
  290. package/src/providers/base.d.ts.map +1 -0
  291. package/src/providers/base.js.map +1 -0
  292. package/src/providers/base.ts +100 -0
  293. package/src/providers/memory.ts +142 -0
  294. package/src/runtime/__tests__/dif-esm-bridge.test.ts +33 -0
  295. package/src/runtime/__tests__/ext-apps-consent.test.ts +334 -0
  296. package/src/runtime/audit-logger.ts +39 -0
  297. package/src/runtime/base.ts +2100 -0
  298. package/src/runtime/dif-core.ts +39 -0
  299. package/src/runtime/ext-apps-constants.ts +20 -0
  300. package/src/services/__tests__/access-control.integration.test.ts +441 -0
  301. package/src/services/__tests__/access-control.proof-response-validation.test.ts +578 -0
  302. package/src/services/__tests__/access-control.service.test.ts +1132 -0
  303. package/src/services/__tests__/batch-delegation.service.test.ts +351 -0
  304. package/src/services/__tests__/crypto.service.test.ts +531 -0
  305. package/src/services/__tests__/delegation-error-formatter.test.ts +643 -0
  306. package/src/services/__tests__/oauth-config.service.test.ts +359 -0
  307. package/src/services/__tests__/oauth-provider-registry.test.ts +142 -0
  308. package/src/services/__tests__/oauth-token-retrieval.service.test.ts +365 -0
  309. package/src/services/__tests__/proof-verifier.integration.test.ts +494 -0
  310. package/src/services/__tests__/proof-verifier.test.ts +489 -0
  311. package/src/services/__tests__/provider-resolution.integration.test.ts +202 -0
  312. package/src/services/__tests__/provider-resolver.test.ts +213 -0
  313. package/src/services/__tests__/provider-validator.test.ts +370 -0
  314. package/src/services/__tests__/session-registration.service.test.ts +312 -0
  315. package/src/services/__tests__/storage.service.test.ts +358 -0
  316. package/src/services/__tests__/tool-context-builder.test.ts +438 -0
  317. package/src/services/access-control.service.ts +1048 -0
  318. package/src/services/authorization/authorization-registry.ts +67 -0
  319. package/src/services/authorization/types.ts +71 -0
  320. package/src/services/batch-delegation.service.ts +136 -0
  321. package/src/services/crypto.service.ts +296 -0
  322. package/src/services/delegation-error-formatter.ts +299 -0
  323. package/src/services/errors.ts +76 -0
  324. package/src/services/index.ts +34 -0
  325. package/src/services/oauth-config.service.d.ts +53 -0
  326. package/src/services/oauth-config.service.d.ts.map +1 -0
  327. package/src/services/oauth-config.service.js.map +1 -0
  328. package/src/services/oauth-config.service.ts +192 -0
  329. package/src/services/oauth-provider-registry.d.ts +57 -0
  330. package/src/services/oauth-provider-registry.d.ts.map +1 -0
  331. package/src/services/oauth-provider-registry.js.map +1 -0
  332. package/src/services/oauth-provider-registry.ts +141 -0
  333. package/src/services/oauth-service.ts +652 -0
  334. package/src/services/oauth-token-retrieval.service.ts +245 -0
  335. package/src/services/policy.service.ts +527 -0
  336. package/src/services/proof-verifier.ts +295 -0
  337. package/src/services/provider-resolver.d.ts +48 -0
  338. package/src/services/provider-resolver.d.ts.map +1 -0
  339. package/src/services/provider-resolver.js.map +1 -0
  340. package/src/services/provider-resolver.ts +236 -0
  341. package/src/services/provider-validator.ts +170 -0
  342. package/src/services/session-registration.service.ts +259 -0
  343. package/src/services/storage.service.ts +566 -0
  344. package/src/services/tool-context-builder.ts +285 -0
  345. package/src/services/tool-protection.service.ts +971 -0
  346. package/src/session/__tests__/session-manager.test.ts +327 -0
  347. package/src/session/index.ts +10 -0
  348. package/src/session/manager.ts +380 -0
  349. package/src/types/__tests__/oauth-required-error.test.ts +79 -0
  350. package/src/types/__tests__/tool-protection.test.ts +121 -0
  351. package/src/types/oauth-required-error.ts +71 -0
  352. package/src/types/tool-protection.ts +179 -0
  353. package/src/utils/__tests__/base58.test.ts +281 -0
  354. package/src/utils/__tests__/base64.test.ts +239 -0
  355. package/src/utils/__tests__/cors.test.ts +184 -0
  356. package/src/utils/__tests__/did-helpers.test.ts +156 -0
  357. package/src/utils/__tests__/storage-keys.test.ts +372 -0
  358. package/src/utils/base58.ts +109 -0
  359. package/src/utils/base64.ts +185 -0
  360. package/src/utils/cors.ts +93 -0
  361. package/src/utils/did-helpers.ts +229 -0
  362. package/src/utils/index.ts +8 -0
  363. package/src/utils/storage-keys.ts +285 -0
  364. package/src/wire-format.ts +114 -0
  365. package/tsconfig.json +21 -0
  366. package/vitest.config.mts +57 -0
@@ -0,0 +1,2100 @@
1
+ /**
2
+ * MCPIRuntimeBase - Provider-based runtime
3
+ *
4
+ * Core runtime that accepts providers for all platform-specific operations.
5
+ * This enables the same runtime logic to work across Node.js, Cloudflare Workers,
6
+ * and other platforms.
7
+ */
8
+
9
+ import {
10
+ CryptoProvider,
11
+ ClockProvider,
12
+ FetchProvider,
13
+ StorageProvider,
14
+ NonceCacheProvider,
15
+ IdentityProvider,
16
+ AgentIdentity,
17
+ } from "../providers/base";
18
+ import { DelegationRequiredError } from "../types/tool-protection.js";
19
+ import { CryptoService, type Ed25519JWK } from "../services/crypto.service.js";
20
+ import { ProofVerifier } from "../services/proof-verifier.js";
21
+ import type { DetachedProof } from "@kya-os/contracts/proof";
22
+ import type { HandshakeRequest } from "@kya-os/contracts/handshake";
23
+ import type {
24
+ DIDDocument,
25
+ AgentDocument,
26
+ MCPIdentity,
27
+ WellKnownConfig,
28
+ WellKnownResponse,
29
+ } from "@kya-os/contracts/well-known";
30
+ import type { AccessControlApiService } from "../services/access-control.service.js";
31
+ import { authorizationMatches } from "../services/access-control.service.js";
32
+ import type { VerifyDelegationRequest } from "@kya-os/contracts/agentshield-api";
33
+ import { AgentShieldAPIError } from "@kya-os/contracts/agentshield-api";
34
+
35
+ // Import the new provider runtime config
36
+ import type { ProviderRuntimeConfig } from "../config";
37
+ import {
38
+ UserDidManager,
39
+ type OAuthIdentity,
40
+ } from "../identity/user-did-manager";
41
+ import type { InterceptedToolCall } from "../types/tool-protection.js";
42
+ import type { IAuditLogger } from "./audit-logger.js";
43
+ import {
44
+ SESSION_ID_PREFIX,
45
+ WELL_KNOWN_IDENTITY_PATH,
46
+ LEGACY_WELL_KNOWN_IDENTITY_PATH,
47
+ recordWireForm,
48
+ } from "../wire-format";
49
+
50
+ /**
51
+ * Interface for runtime instances that have AccessControlApiService available
52
+ * This allows type-safe access to the access control service without using `as any`
53
+ *
54
+ * @deprecated AccessControlApiService is now directly available as protected property on MCPIRuntimeBase
55
+ */
56
+ export interface RuntimeWithAccessControl {
57
+ accessControlService?: AccessControlApiService;
58
+ }
59
+
60
+ type RuntimeRecord = Record<string, unknown>;
61
+
62
+ type RuntimeHandshakeRequest = Partial<HandshakeRequest> &
63
+ RuntimeRecord & {
64
+ audience?: string;
65
+ agentDid?: string;
66
+ clientInfo?: RuntimeRecord;
67
+ clientProtocolVersion?: unknown;
68
+ clientCapabilities?: unknown;
69
+ clientDid?: string;
70
+ oauthIdentity?: OAuthIdentity | null;
71
+ };
72
+
73
+ interface RuntimeHandshakeResponse {
74
+ sessionId: string;
75
+ agentDid: string;
76
+ timestamp: number;
77
+ capabilities: string[];
78
+ userDid?: string;
79
+ signature: string;
80
+ }
81
+
82
+ interface RuntimeSessionContext {
83
+ id?: string;
84
+ audience?: string;
85
+ createdAt?: number;
86
+ expiresAt?: number;
87
+ clientDid?: string;
88
+ userDid?: string;
89
+ agentDid?: string;
90
+ serverDid?: string;
91
+ nonce?: string;
92
+ delegationToken?: string;
93
+ consentProof?: string;
94
+ projectId?: string;
95
+ serverOrigin?: string;
96
+ userAgent?: string;
97
+ clientId?: string;
98
+ agentName?: string;
99
+ clientInfo?: Record<string, unknown>;
100
+ identityState?: "anonymous" | "authenticated";
101
+ oauthIdentity?: OAuthIdentity;
102
+ canonicalPayload?: string;
103
+ [key: string]: unknown;
104
+ }
105
+
106
+ interface StoredRuntimeSession extends RuntimeSessionContext {
107
+ id: string;
108
+ createdAt: number;
109
+ expiresAt: number;
110
+ }
111
+
112
+ interface LegacyProof {
113
+ timestamp: number;
114
+ nonce: string;
115
+ did: string;
116
+ signature: string;
117
+ algorithm: "Ed25519";
118
+ sessionId?: string;
119
+ audience?: string;
120
+ }
121
+
122
+ type RuntimeProof = LegacyProof | DetachedProof;
123
+
124
+ type RuntimeAuditLogger =
125
+ | IAuditLogger
126
+ | {
127
+ log: (event: string, data: unknown) => void;
128
+ };
129
+
130
+ interface NonceCacheWithInitialize extends NonceCacheProvider {
131
+ initialize?: () => Promise<void> | void;
132
+ }
133
+
134
+ const isRecord = (value: unknown): value is RuntimeRecord =>
135
+ typeof value === "object" && value !== null;
136
+
137
+ export class MCPIRuntimeBase {
138
+ protected crypto: CryptoProvider;
139
+ protected clock: ClockProvider;
140
+ protected fetch: FetchProvider;
141
+ protected storage: StorageProvider;
142
+ protected nonceCache: NonceCacheProvider;
143
+ protected identity: IdentityProvider;
144
+ protected config: ProviderRuntimeConfig;
145
+ private cachedIdentity?: AgentIdentity;
146
+ private sessions: Map<string, StoredRuntimeSession> = new Map();
147
+ private lastProof?: RuntimeProof;
148
+ private userDidManager?: UserDidManager;
149
+ private interceptedCalls: Map<string, InterceptedToolCall> = new Map(); // Store intercepted tool calls by resume token
150
+ private cryptoService?: CryptoService;
151
+ protected proofVerifier?: ProofVerifier; // Optional ProofVerifier (injected by subclasses)
152
+ protected accessControlService?: AccessControlApiService; // Optional AccessControlApiService (injected by subclasses)
153
+ /**
154
+ * Cached flag indicating whether @modelcontextprotocol/ext-apps is available.
155
+ * Set by subclasses after a successful dynamic import (avoids require() vs ESM issues).
156
+ * When undefined, falls back to synchronous require() probe.
157
+ */
158
+ private _extAppsAvailable?: boolean;
159
+
160
+ constructor(config: ProviderRuntimeConfig) {
161
+ this.config = config;
162
+ this.crypto = config.cryptoProvider;
163
+ this.clock = config.clockProvider;
164
+ this.fetch = config.fetchProvider;
165
+ this.storage = config.storageProvider;
166
+ this.nonceCache = config.nonceCacheProvider;
167
+ this.identity = config.identityProvider;
168
+ // Initialize CryptoService for JWS verification
169
+ this.cryptoService = new CryptoService(this.crypto);
170
+ }
171
+
172
+ /**
173
+ * Initialize the runtime
174
+ */
175
+ async initialize(): Promise<void> {
176
+ // Load or generate identity
177
+ this.cachedIdentity = await this.identity.getIdentity();
178
+
179
+ // Initialize user DID manager if identity config enables it
180
+ if (this.config.identity?.generateUserDids) {
181
+ this.userDidManager = new UserDidManager({
182
+ crypto: this.crypto,
183
+ storage: this.config.identity?.userDidStorage
184
+ ? {
185
+ get: async (key: string) =>
186
+ await this.storage.get(`userDid:${key}`),
187
+ set: async (key: string, value: string, ttl?: number) => {
188
+ await this.storage.set(`userDid:${key}`, value);
189
+ },
190
+ delete: async (key: string) =>
191
+ await this.storage.delete(`userDid:${key}`),
192
+ }
193
+ : undefined,
194
+ useDidWeb: this.config.identity?.userDidStorage === "persistent",
195
+ });
196
+ }
197
+
198
+ // Initialize nonce cache if it has an initialize method
199
+ const nonceCacheWithInitialize = this
200
+ .nonceCache as NonceCacheWithInitialize;
201
+ if (typeof nonceCacheWithInitialize.initialize === "function") {
202
+ await nonceCacheWithInitialize.initialize();
203
+ }
204
+
205
+ // Log initialization if audit is enabled
206
+ if (this.config.audit?.enabled) {
207
+ this.logAudit("runtime_initialized", {
208
+ did: this.cachedIdentity.did,
209
+ environment: this.config.environment || "development",
210
+ userDidGeneration: this.config.identity?.generateUserDids
211
+ ? "enabled"
212
+ : "disabled",
213
+ });
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Get the current agent identity
219
+ */
220
+ async getIdentity(): Promise<AgentIdentity> {
221
+ if (!this.cachedIdentity) {
222
+ this.cachedIdentity = await this.identity.getIdentity();
223
+ }
224
+ return this.cachedIdentity;
225
+ }
226
+
227
+ /**
228
+ * Handle MCP handshake request
229
+ *
230
+ * Phase 5: Anonymous Sessions Until OAuth
231
+ * - Sessions start anonymous (no userDid) unless OAuth identity provided
232
+ * - User DID is resolved via AgentShield after OAuth completes
233
+ * - Eliminates DID fragmentation (same user = same DID across sessions)
234
+ *
235
+ * @param request - Handshake request object (may include oauthIdentity for persistent user DID lookup)
236
+ * @returns Handshake response with session ID and agent DID
237
+ *
238
+ * C2 (#2916) classification: product-side handshake orchestration (Phase-5
239
+ * userDid resolution, clientInfo, identity-state, signed session in the
240
+ * in-process session store). NOT re-homed onto the DIF `@kya-os/mcp`
241
+ * `SessionManager` (a nonce/timestamp/audience challenge-validator — a
242
+ * different operation). The session-id wire-format blocker is now cleared:
243
+ * the C4 (#2918) dual-accept window has flipped emission to `kyaos_`
244
+ * ({@link SESSION_ID_PREFIX}) while pre-flip `mcpi_` ids still parse, so the
245
+ * DIF `SessionManager` re-home (3b, also `kyaos_`) becomes a drop-in
246
+ * follow-up. PR-0's `loadDifCore()` seam already cleared the CJS/ESM (TS1479)
247
+ * blocker. Behavior is frozen by the base.ts handshake suites. See
248
+ * packages/mcp-i/src/runtime/session.ts.
249
+ */
250
+ async handleHandshake(
251
+ request: RuntimeHandshakeRequest
252
+ ): Promise<RuntimeHandshakeResponse> {
253
+ const identity = await this.getIdentity();
254
+ const timestamp = this.clock.now();
255
+ const sessionId = await this.generateSessionId();
256
+
257
+ // Phase 5: Try to resolve user DID from existing OAuth mapping
258
+ // Sessions start anonymous - no ephemeral generation
259
+ let userDid: string | undefined;
260
+ if (this.userDidManager) {
261
+ try {
262
+ const oauthIdentity = request.oauthIdentity;
263
+ const resolvedDid = await this.userDidManager.getOrCreateUserDid(
264
+ sessionId,
265
+ oauthIdentity
266
+ );
267
+ // Convert null to undefined for session storage
268
+ userDid = resolvedDid ?? undefined;
269
+
270
+ if (this.config.audit?.enabled) {
271
+ if (userDid) {
272
+ console.error("[MCP-I] Resolved existing user DID for session:", {
273
+ userDid: userDid.substring(0, 20) + "...",
274
+ hasOAuth: !!oauthIdentity,
275
+ provider: oauthIdentity?.provider,
276
+ });
277
+ } else {
278
+ console.error("[MCP-I] Session started anonymous (no userDid):", {
279
+ sessionId: sessionId.substring(0, 8) + "...",
280
+ hasOAuth: !!oauthIdentity,
281
+ });
282
+ }
283
+ }
284
+ } catch (error) {
285
+ console.warn("[MCP-I] Failed to resolve user DID:", error);
286
+ // Continue without user DID - session is anonymous
287
+ }
288
+ }
289
+
290
+ // Extract client info if available
291
+ const normalizeString = (value: unknown): string | undefined => {
292
+ if (typeof value !== "string") {
293
+ return undefined;
294
+ }
295
+ const trimmed = value.trim();
296
+ return trimmed.length > 0 ? trimmed : undefined;
297
+ };
298
+
299
+ const protocolVersion = normalizeString(request.clientProtocolVersion);
300
+ const clientCapabilities = request.clientCapabilities;
301
+
302
+ const requestClientInfo = request.clientInfo;
303
+ const shouldPersistClientInfo =
304
+ requestClientInfo ||
305
+ typeof protocolVersion === "string" ||
306
+ typeof clientCapabilities !== "undefined";
307
+
308
+ const clientInfo = shouldPersistClientInfo
309
+ ? {
310
+ name: normalizeString(requestClientInfo?.name) ?? "unknown",
311
+ title: normalizeString(requestClientInfo?.title),
312
+ version: normalizeString(requestClientInfo?.version),
313
+ platform: normalizeString(requestClientInfo?.platform),
314
+ vendor: normalizeString(requestClientInfo?.vendor),
315
+ persistentId: normalizeString(requestClientInfo?.persistentId),
316
+ clientId:
317
+ normalizeString(requestClientInfo?.clientId) ?? crypto.randomUUID(),
318
+ protocolVersion,
319
+ capabilities: clientCapabilities,
320
+ }
321
+ : undefined;
322
+
323
+ // Create session with Phase 5 identity state
324
+ const session: StoredRuntimeSession = {
325
+ id: sessionId,
326
+ clientDid: request.clientDid || userDid, // Use provided clientDid or generated userDid
327
+ userDid: userDid, // Store user DID (may be undefined for anonymous sessions)
328
+ agentDid: request.agentDid, // ✅ FIXED: Only agent DID, no fallback
329
+ serverDid: identity.did, // ✅ NEW: Server's DID (for clarity)
330
+ audience: request.audience,
331
+ createdAt: timestamp,
332
+ expiresAt: this.clock.calculateExpiry(
333
+ (this.config.session?.ttlMinutes || 30) * 60
334
+ ),
335
+ clientInfo, // Store client information
336
+ // Phase 5: Identity state tracking
337
+ identityState: userDid ? "authenticated" : "anonymous",
338
+ oauthIdentity: request.oauthIdentity ?? undefined,
339
+ };
340
+
341
+ this.sessions.set(sessionId, session);
342
+
343
+ // Create handshake response
344
+ const response = {
345
+ sessionId,
346
+ agentDid: identity.did,
347
+ timestamp,
348
+ capabilities: ["identity", "proof", "audit"],
349
+ ...(userDid && { userDid }), // Include user DID in response if generated
350
+ };
351
+
352
+ // Sign the response
353
+ const signature = await this.signData(response);
354
+
355
+ return {
356
+ ...response,
357
+ signature,
358
+ };
359
+ }
360
+
361
+ /**
362
+ * Update session identity after OAuth resolution (Phase 5)
363
+ *
364
+ * Called after AgentShield identity/resolve returns a persistent user DID.
365
+ * Updates the session to authenticated state with the resolved DID.
366
+ *
367
+ * @param sessionId - MCP session ID
368
+ * @param userDid - Persistent user DID from AgentShield
369
+ * @param oauthIdentity - OAuth identity information
370
+ * @throws Error if session not found
371
+ */
372
+ async updateSessionIdentity(
373
+ sessionId: string,
374
+ userDid: string,
375
+ oauthIdentity?: { provider: string; subject: string; email?: string }
376
+ ): Promise<void> {
377
+ const session = this.sessions.get(sessionId);
378
+ if (!session) {
379
+ throw new Error(`Session not found: ${sessionId}`);
380
+ }
381
+
382
+ // Update session with resolved identity
383
+ session.userDid = userDid;
384
+ session.identityState = "authenticated";
385
+ if (oauthIdentity) {
386
+ session.oauthIdentity = oauthIdentity;
387
+ }
388
+
389
+ // Update the sessions map
390
+ this.sessions.set(sessionId, session);
391
+
392
+ // Also update UserDidManager cache if available
393
+ if (this.userDidManager) {
394
+ await this.userDidManager.setUserDidForSession(
395
+ sessionId,
396
+ userDid,
397
+ oauthIdentity
398
+ );
399
+ }
400
+
401
+ if (this.config.audit?.enabled) {
402
+ console.error("[MCP-I] Session identity updated (Phase 5):", {
403
+ sessionId: sessionId.substring(0, 8) + "...",
404
+ userDid: userDid.substring(0, 20) + "...",
405
+ provider: oauthIdentity?.provider,
406
+ identityState: "authenticated",
407
+ });
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Get session by ID
413
+ */
414
+ getSession(sessionId: string): StoredRuntimeSession | undefined {
415
+ return this.sessions.get(sessionId);
416
+ }
417
+
418
+ /**
419
+ * Extract the correct provider for consent URL from tool protection config
420
+ *
421
+ * For password auth tools, the provider is in authorization.provider.
422
+ * For OAuth auth tools, the provider is in oauthProvider (legacy) or authorization.provider.
423
+ *
424
+ * Note: Not all authorization types have a provider field (e.g., 'none', 'mdl', 'webauthn').
425
+ * Only 'oauth', 'oauth2', 'password', and 'idv' types have provider.
426
+ *
427
+ * @param protection - Tool protection configuration
428
+ * @returns Provider name to use in consent URL, or undefined
429
+ */
430
+ private getConsentProvider(
431
+ protection: import("../types/tool-protection.js").ToolProtection
432
+ ): string | undefined {
433
+ // Check authorization field - only some types have provider
434
+ if (protection.authorization) {
435
+ const auth = protection.authorization;
436
+ // Types with provider: oauth, oauth2, password, idv
437
+ if (
438
+ auth.type === "oauth" ||
439
+ auth.type === "oauth2" ||
440
+ auth.type === "password" ||
441
+ auth.type === "idv"
442
+ ) {
443
+ // Return auth.provider if set, otherwise fall through to legacy oauthProvider
444
+ if (auth.provider) {
445
+ return auth.provider;
446
+ }
447
+ }
448
+ // Other types don't have provider (none, mdl, verifiable_credential, webauthn, siwe)
449
+ // Fall through to legacy oauthProvider
450
+ }
451
+
452
+ // Fall back to legacy oauthProvider (deprecated)
453
+ return protection.oauthProvider;
454
+ }
455
+
456
+ /**
457
+ * Process tool call with automatic proof generation
458
+ * Returns clean result only - proof is stored for out-of-band retrieval
459
+ *
460
+ * @param toolName - Name of the tool being called
461
+ * @param args - Tool arguments
462
+ * @param handler - Tool execution handler
463
+ * @param session - Session context (expected fields: id, audience, nonce?, delegationToken?, consentProof?)
464
+ */
465
+ async processToolCall<TArgs = unknown, TResult = unknown>(
466
+ toolName: string,
467
+ args: TArgs,
468
+ handler: (args: TArgs) => Promise<TResult>,
469
+ session?: RuntimeSessionContext
470
+ ): Promise<TResult | RuntimeRecord> {
471
+ // Check tool protection (delegation requirement)
472
+ if (this.config.toolProtectionService) {
473
+ // Get agent identity to check protection
474
+ const identity = await this.getIdentity();
475
+
476
+ if (this.config.audit?.enabled) {
477
+ console.error("[MCP-I] Checking tool protection:", {
478
+ tool: toolName,
479
+ agentDid: identity.did.slice(0, 20) + "...",
480
+ hasDelegation: !!(session?.delegationToken || session?.consentProof),
481
+ });
482
+ }
483
+
484
+ const protection =
485
+ await this.config.toolProtectionService.checkToolProtection(
486
+ toolName,
487
+ identity.did
488
+ );
489
+
490
+ if (protection) {
491
+ // Tool requires delegation
492
+ const hasDelegation = session?.delegationToken || session?.consentProof;
493
+
494
+ if (!hasDelegation) {
495
+ // No delegation provided - intercept the tool call and store context
496
+ // Store intercepted tool call context for resumption
497
+ const interceptedCall: InterceptedToolCall = {
498
+ toolName,
499
+ args,
500
+ sessionId: session?.id || "unknown",
501
+ timestamp: this.clock.now(),
502
+ expiresAt: this.clock.calculateExpiry(1800), // 30 minutes
503
+ };
504
+
505
+ // Generate resume token
506
+ const resumeToken = await this.generateResumeToken(interceptedCall);
507
+
508
+ // Build consent URL with resume token
509
+ // Note: projectId is not available in base class - subclasses should override buildConsentUrl
510
+ // Pass oauthProvider to ensure correct auth method is selected (e.g., "credentials" vs "github")
511
+ const consentUrl = this.buildConsentUrl(
512
+ toolName,
513
+ protection.requiredScopes,
514
+ session,
515
+ resumeToken,
516
+ undefined, // projectId - handled by subclass override
517
+ this.getConsentProvider(protection) // Provider from tool config (supports both password and oauth auth)
518
+ );
519
+
520
+ // Create error with intercepted call context and pre-generated resume token
521
+ const error = new DelegationRequiredError(
522
+ toolName,
523
+ protection.requiredScopes,
524
+ consentUrl,
525
+ interceptedCall,
526
+ resumeToken
527
+ );
528
+
529
+ // Store intercepted call for resumption
530
+ this.interceptedCalls.set(resumeToken, interceptedCall);
531
+
532
+ // Clean up expired intercepted calls periodically
533
+ this.cleanupExpiredInterceptedCalls();
534
+
535
+ if (this.config.audit?.enabled) {
536
+ console.warn(
537
+ "[MCP-I] BLOCKED: Tool requires delegation but none provided",
538
+ {
539
+ tool: toolName,
540
+ requiredScopes: protection.requiredScopes,
541
+ agentDid: identity.did.slice(0, 20) + "...",
542
+ resumeToken: error.resumeToken,
543
+ consentUrl,
544
+ }
545
+ );
546
+ }
547
+
548
+ // Try MCP Apps inline consent UI before falling back to error
549
+ // Client capabilities are stored under session.clientInfo.capabilities (set during handleHandshake)
550
+ const clientInfo = session?.clientInfo;
551
+ const clientCaps = isRecord(clientInfo?.capabilities)
552
+ ? clientInfo.capabilities
553
+ : undefined;
554
+ const uiResult = this.buildConsentUIResult(
555
+ toolName,
556
+ protection.requiredScopes,
557
+ session,
558
+ resumeToken,
559
+ (session?.projectId as string) || undefined,
560
+ (session?.serverOrigin as string) || undefined,
561
+ clientCaps
562
+ );
563
+ if (uiResult) {
564
+ return uiResult;
565
+ }
566
+
567
+ throw error;
568
+ }
569
+
570
+ // Delegation provided - verify it with AccessControlApiService
571
+ const delegationToken = session?.delegationToken;
572
+ const consentProof = session?.consentProof;
573
+
574
+ if (!this.accessControlService) {
575
+ // Access control service not available - log warning but allow execution
576
+ // This enables graceful degradation when service is not configured
577
+ if (this.config.audit?.enabled) {
578
+ console.warn(
579
+ "[MCP-I] ⚠️ Delegation token provided but AccessControlApiService not configured - skipping verification",
580
+ {
581
+ tool: toolName,
582
+ agentDid: identity.did.slice(0, 20) + "...",
583
+ hasDelegationToken: !!delegationToken,
584
+ hasConsentProof: !!consentProof,
585
+ }
586
+ );
587
+ }
588
+ } else {
589
+ // Verify delegation token with AccessControlApiService
590
+ try {
591
+ if (this.config.audit?.enabled) {
592
+ console.error(
593
+ "[MCP-I] 🔐 Verifying delegation token with AccessControlApiService",
594
+ {
595
+ tool: toolName,
596
+ agentDid: identity.did.slice(0, 20) + "...",
597
+ hasDelegationToken: !!delegationToken,
598
+ hasConsentProof: !!consentProof,
599
+ requiredScopes: protection.requiredScopes,
600
+ }
601
+ );
602
+ }
603
+
604
+ // Build verification request
605
+ const verifyRequest: VerifyDelegationRequest = {
606
+ agent_did: identity.did,
607
+ scopes: protection.requiredScopes,
608
+ };
609
+
610
+ // ✅ CRITICAL: Include user_did for user-scoped delegation verification
611
+ // This prevents cross-user delegation leakage (Priority 3 fallback issue)
612
+ // Without user_did, AgentShield cannot validate user isolation
613
+ if (session?.userDid) {
614
+ verifyRequest.user_did = session.userDid;
615
+ if (this.config.audit?.enabled) {
616
+ console.error(
617
+ "[MCP-I] 🔐 Including user_did in verification request",
618
+ {
619
+ userDid: session.userDid.slice(0, 20) + "...",
620
+ }
621
+ );
622
+ }
623
+ }
624
+
625
+ // Add delegation token if available (preferred over consent proof)
626
+ if (delegationToken) {
627
+ verifyRequest.delegation_token = delegationToken;
628
+ } else if (consentProof) {
629
+ // Consent proof is a JWT credential - use as credential_jwt
630
+ verifyRequest.credential_jwt = consentProof;
631
+ }
632
+
633
+ // Add optional timestamp for verification
634
+ verifyRequest.timestamp = this.clock.now();
635
+
636
+ // Add client info from session if available
637
+ if (session?.clientDid || session?.clientId) {
638
+ verifyRequest.client_info = {
639
+ origin: session?.serverOrigin,
640
+ user_agent: session?.userAgent,
641
+ };
642
+ }
643
+
644
+ // Perform verification
645
+ const verificationResult =
646
+ await this.accessControlService.verifyDelegation(verifyRequest, {
647
+ delegationToken: delegationToken || undefined,
648
+ credentialJwt: consentProof || undefined,
649
+ });
650
+
651
+ // Check verification result
652
+ if (!verificationResult.data.valid) {
653
+ // Delegation verification failed
654
+ const reason =
655
+ verificationResult.data.reason ||
656
+ "Delegation token invalid or expired";
657
+ const errorDetails = verificationResult.data.error;
658
+
659
+ if (this.config.audit?.enabled) {
660
+ console.error("[MCP-I] ❌ Delegation verification FAILED", {
661
+ tool: toolName,
662
+ agentDid: identity.did.slice(0, 20) + "...",
663
+ reason,
664
+ errorCode: errorDetails?.code,
665
+ errorMessage: errorDetails?.message,
666
+ requiredScopes: protection.requiredScopes,
667
+ });
668
+ }
669
+
670
+ // Throw DelegationRequiredError to trigger consent flow
671
+ const interceptedCall: InterceptedToolCall = {
672
+ toolName,
673
+ args,
674
+ sessionId: session?.id || "unknown",
675
+ timestamp: this.clock.now(),
676
+ expiresAt: this.clock.calculateExpiry(1800), // 30 minutes
677
+ };
678
+
679
+ const resumeToken =
680
+ await this.generateResumeToken(interceptedCall);
681
+ const consentUrl = this.buildConsentUrl(
682
+ toolName,
683
+ protection.requiredScopes,
684
+ session,
685
+ resumeToken,
686
+ undefined, // projectId - handled by subclass override
687
+ this.getConsentProvider(protection) // Provider from tool config (supports both password and oauth auth)
688
+ );
689
+
690
+ this.interceptedCalls.set(resumeToken, interceptedCall);
691
+ this.cleanupExpiredInterceptedCalls();
692
+
693
+ throw new DelegationRequiredError(
694
+ toolName,
695
+ protection.requiredScopes,
696
+ consentUrl,
697
+ interceptedCall,
698
+ resumeToken
699
+ );
700
+ }
701
+
702
+ // ✅ SECURITY: Validate user_identifier matches session userDid
703
+ // This ensures delegations are user-specific and prevents user isolation bypass
704
+ const credential = verificationResult.data.credential;
705
+ const delegationUserIdentifier = credential?.user_identifier;
706
+ // Also check for user_id field (AgentShield may return DID or ID directly)
707
+ const delegationUserId = credential?.user_id;
708
+ const sessionUserDid = session?.userDid;
709
+
710
+ if (delegationUserIdentifier && sessionUserDid) {
711
+ // Check if identifiers match (direct match or via user_id field)
712
+ const identifiersMatch =
713
+ delegationUserIdentifier === sessionUserDid ||
714
+ delegationUserId === sessionUserDid;
715
+
716
+ // Special case: If delegationUserIdentifier is NOT a DID (e.g., email),
717
+ // but AgentShield verified the delegation, trust it.
718
+ // AgentShield internally links email → DID, so the verification is valid.
719
+ // Only fail if BOTH are DIDs and they don't match.
720
+ const isDelegationIdentifierDid =
721
+ delegationUserIdentifier.startsWith("did:");
722
+ const shouldEnforceMatch =
723
+ isDelegationIdentifierDid || delegationUserId;
724
+
725
+ if (shouldEnforceMatch && !identifiersMatch) {
726
+ // User identifier mismatch - potential security issue
727
+ const securityError = `Delegation user_identifier mismatch: delegation has "${delegationUserIdentifier.substring(0, 20)}..." but session has "${sessionUserDid.substring(0, 20)}..."`;
728
+
729
+ if (this.config.audit?.enabled) {
730
+ console.error(
731
+ "[MCP-I] 🔒 SECURITY: User identifier validation FAILED",
732
+ {
733
+ tool: toolName,
734
+ agentDid: identity.did.slice(0, 20) + "...",
735
+ delegationUserIdentifier:
736
+ delegationUserIdentifier.substring(0, 20) + "...",
737
+ delegationUserId: delegationUserId
738
+ ? delegationUserId.substring(0, 20) + "..."
739
+ : "N/A",
740
+ sessionUserDid: sessionUserDid.substring(0, 20) + "...",
741
+ sessionId: session?.id?.substring(0, 20) + "...",
742
+ reason: "user_identifier_mismatch",
743
+ severity: "high",
744
+ }
745
+ );
746
+ }
747
+
748
+ // Throw DelegationRequiredError to force re-authentication
749
+ const interceptedCall: InterceptedToolCall = {
750
+ toolName,
751
+ args,
752
+ sessionId: session?.id || "unknown",
753
+ timestamp: this.clock.now(),
754
+ expiresAt: this.clock.calculateExpiry(1800), // 30 minutes
755
+ };
756
+
757
+ const resumeToken =
758
+ await this.generateResumeToken(interceptedCall);
759
+ const consentUrl = this.buildConsentUrl(
760
+ toolName,
761
+ protection.requiredScopes,
762
+ session,
763
+ resumeToken,
764
+ undefined, // projectId - handled by subclass override
765
+ this.getConsentProvider(protection) // Provider from tool config (supports both password and oauth auth)
766
+ );
767
+
768
+ this.interceptedCalls.set(resumeToken, interceptedCall);
769
+ this.cleanupExpiredInterceptedCalls();
770
+
771
+ throw new DelegationRequiredError(
772
+ toolName,
773
+ protection.requiredScopes,
774
+ consentUrl,
775
+ interceptedCall,
776
+ resumeToken
777
+ );
778
+ }
779
+
780
+ // User identifier validation passed (direct match or trusted AgentShield verification)
781
+ if (this.config.audit?.enabled) {
782
+ console.error("[MCP-I] ✅ User identifier validation PASSED", {
783
+ tool: toolName,
784
+ agentDid: identity.did.slice(0, 20) + "...",
785
+ userDid: sessionUserDid.substring(0, 20) + "...",
786
+ sessionId: session?.id?.substring(0, 20) + "...",
787
+ matchType: identifiersMatch
788
+ ? "direct"
789
+ : "trusted_agentshield_verification",
790
+ delegationIdentifierFormat: isDelegationIdentifierDid
791
+ ? "did"
792
+ : "email_or_other",
793
+ });
794
+ }
795
+ } else if (delegationUserIdentifier && !sessionUserDid) {
796
+ // Delegation has user_identifier but session doesn't - log warning
797
+ if (this.config.audit?.enabled) {
798
+ console.warn(
799
+ "[MCP-I] ⚠️ Delegation has user_identifier but session missing userDid",
800
+ {
801
+ tool: toolName,
802
+ agentDid: identity.did.slice(0, 20) + "...",
803
+ delegationUserIdentifier:
804
+ delegationUserIdentifier.substring(0, 20) + "...",
805
+ sessionId: session?.id?.substring(0, 20) + "...",
806
+ }
807
+ );
808
+ }
809
+ }
810
+
811
+ // ✅ SECURITY: Validate authorization method matches tool requirements
812
+ // This prevents stale delegations from working after tool auth method changes
813
+ // NOTE: Authorization validation only applies when credential is present (AgentShield API verifier).
814
+ // KV/Memory verifiers don't return credential data, so we skip auth method validation for them.
815
+ const toolAuth = protection.authorization;
816
+ const delegationAuth = credential?.authorization as
817
+ | { type: string; provider?: string; credentialType?: string }
818
+ | undefined;
819
+
820
+ // Only validate when:
821
+ // 1. Tool has authorization requirement defined
822
+ // 2. Credential is present (AgentShield API verifier)
823
+ if (toolAuth && credential) {
824
+ // If tool requires authorization but credential doesn't have auth data, reject
825
+ // This prevents bypassing auth checks with incomplete credential data
826
+ if (!delegationAuth) {
827
+ if (this.config.audit?.enabled) {
828
+ console.error(
829
+ "[MCP-I] ❌ Tool requires authorization but credential missing auth data",
830
+ {
831
+ tool: toolName,
832
+ agentDid: identity.did.slice(0, 20) + "...",
833
+ toolAuth,
834
+ note: "Credential exists but missing authorization metadata - rejecting for security",
835
+ }
836
+ );
837
+ }
838
+
839
+ // Throw DelegationRequiredError to force re-authorization
840
+ const interceptedCall: InterceptedToolCall = {
841
+ toolName,
842
+ args,
843
+ sessionId: session?.id || "unknown",
844
+ timestamp: this.clock.now(),
845
+ expiresAt: this.clock.calculateExpiry(1800),
846
+ };
847
+
848
+ const resumeToken =
849
+ await this.generateResumeToken(interceptedCall);
850
+ const consentUrl = this.buildConsentUrl(
851
+ toolName,
852
+ protection.requiredScopes,
853
+ session,
854
+ resumeToken,
855
+ undefined,
856
+ this.getConsentProvider(protection)
857
+ );
858
+
859
+ this.interceptedCalls.set(resumeToken, interceptedCall);
860
+ this.cleanupExpiredInterceptedCalls();
861
+
862
+ throw new DelegationRequiredError(
863
+ toolName,
864
+ protection.requiredScopes,
865
+ consentUrl,
866
+ interceptedCall,
867
+ resumeToken
868
+ );
869
+ }
870
+
871
+ // Both tool and delegation have authorization - compare them
872
+ if (!authorizationMatches(delegationAuth, toolAuth)) {
873
+ const toolAuthRecord = toolAuth as RuntimeRecord;
874
+ const toolAuthProvider =
875
+ typeof toolAuthRecord.provider === "string"
876
+ ? `:${toolAuthRecord.provider}`
877
+ : "";
878
+ const toolAuthCredentialType =
879
+ typeof toolAuthRecord.credentialType === "string"
880
+ ? `:${toolAuthRecord.credentialType}`
881
+ : "";
882
+ const authMismatchReason = `Authorization method mismatch: delegation has ${delegationAuth.type}${delegationAuth.provider ? `:${delegationAuth.provider}` : ""}${delegationAuth.credentialType ? `:${delegationAuth.credentialType}` : ""} but tool requires ${toolAuth.type}${toolAuthProvider}${toolAuthCredentialType}`;
883
+
884
+ if (this.config.audit?.enabled) {
885
+ console.error(
886
+ "[MCP-I] ❌ Authorization method validation FAILED",
887
+ {
888
+ tool: toolName,
889
+ agentDid: identity.did.slice(0, 20) + "...",
890
+ reason: authMismatchReason,
891
+ delegationAuth,
892
+ toolAuth,
893
+ }
894
+ );
895
+ }
896
+
897
+ // Throw DelegationRequiredError to force re-authorization with correct method
898
+ const interceptedCall: InterceptedToolCall = {
899
+ toolName,
900
+ args,
901
+ sessionId: session?.id || "unknown",
902
+ timestamp: this.clock.now(),
903
+ expiresAt: this.clock.calculateExpiry(1800),
904
+ };
905
+
906
+ const resumeToken =
907
+ await this.generateResumeToken(interceptedCall);
908
+ const consentUrl = this.buildConsentUrl(
909
+ toolName,
910
+ protection.requiredScopes,
911
+ session,
912
+ resumeToken,
913
+ undefined,
914
+ this.getConsentProvider(protection)
915
+ );
916
+
917
+ this.interceptedCalls.set(resumeToken, interceptedCall);
918
+ this.cleanupExpiredInterceptedCalls();
919
+
920
+ throw new DelegationRequiredError(
921
+ toolName,
922
+ protection.requiredScopes,
923
+ consentUrl,
924
+ interceptedCall,
925
+ resumeToken
926
+ );
927
+ }
928
+
929
+ // Authorization method validation passed
930
+ if (this.config.audit?.enabled) {
931
+ console.error(
932
+ "[MCP-I] ✅ Authorization method validation PASSED",
933
+ {
934
+ tool: toolName,
935
+ agentDid: identity.did.slice(0, 20) + "...",
936
+ authType: delegationAuth.type,
937
+ provider: delegationAuth.provider || "N/A",
938
+ }
939
+ );
940
+ }
941
+ }
942
+ // If credential is missing entirely (KV/Memory verifiers), skip validation for backward compatibility
943
+
944
+ // Verification succeeded
945
+ if (this.config.audit?.enabled) {
946
+ console.error("[MCP-I] ✅ Delegation verification SUCCEEDED", {
947
+ tool: toolName,
948
+ agentDid: identity.did.slice(0, 20) + "...",
949
+ delegationId: verificationResult.data.delegation_id,
950
+ credentialScopes: verificationResult.data.credential?.scopes,
951
+ requiredScopes: protection.requiredScopes,
952
+ });
953
+ }
954
+ } catch (error: unknown) {
955
+ // Handle verification errors
956
+ if (error instanceof DelegationRequiredError) {
957
+ // Re-throw DelegationRequiredError as-is (already handled above)
958
+ throw error;
959
+ }
960
+
961
+ // Handle AgentShieldAPIError (network errors, API errors, etc.)
962
+ if (error instanceof AgentShieldAPIError) {
963
+ if (this.config.audit?.enabled) {
964
+ console.error(
965
+ "[MCP-I] ❌ Delegation verification error (API failure)",
966
+ {
967
+ tool: toolName,
968
+ agentDid: identity.did.slice(0, 20) + "...",
969
+ errorCode: error.code,
970
+ errorMessage: error.message,
971
+ errorDetails: error.details,
972
+ }
973
+ );
974
+ }
975
+
976
+ // On API errors, fail securely by requiring delegation
977
+ // This prevents unauthorized access when verification service is unavailable
978
+ const interceptedCall: InterceptedToolCall = {
979
+ toolName,
980
+ args,
981
+ sessionId: session?.id || "unknown",
982
+ timestamp: this.clock.now(),
983
+ expiresAt: this.clock.calculateExpiry(1800),
984
+ };
985
+
986
+ const resumeToken =
987
+ await this.generateResumeToken(interceptedCall);
988
+ const consentUrl = this.buildConsentUrl(
989
+ toolName,
990
+ protection.requiredScopes,
991
+ session,
992
+ resumeToken,
993
+ undefined, // projectId - handled by subclass override
994
+ this.getConsentProvider(protection) // Provider from tool config (supports both password and oauth auth)
995
+ );
996
+
997
+ this.interceptedCalls.set(resumeToken, interceptedCall);
998
+ this.cleanupExpiredInterceptedCalls();
999
+
1000
+ throw new DelegationRequiredError(
1001
+ toolName,
1002
+ protection.requiredScopes,
1003
+ consentUrl,
1004
+ interceptedCall,
1005
+ resumeToken
1006
+ );
1007
+ }
1008
+
1009
+ // Unexpected error - log and fail securely
1010
+ if (this.config.audit?.enabled) {
1011
+ console.error(
1012
+ "[MCP-I] ❌ Unexpected error during delegation verification",
1013
+ {
1014
+ tool: toolName,
1015
+ agentDid: identity.did.slice(0, 20) + "...",
1016
+ error: error instanceof Error ? error.message : String(error),
1017
+ errorStack: error instanceof Error ? error.stack : undefined,
1018
+ }
1019
+ );
1020
+ }
1021
+
1022
+ // Fail securely - require delegation on unexpected errors
1023
+ const interceptedCall: InterceptedToolCall = {
1024
+ toolName,
1025
+ args,
1026
+ sessionId: session?.id || "unknown",
1027
+ timestamp: this.clock.now(),
1028
+ expiresAt: this.clock.calculateExpiry(1800),
1029
+ };
1030
+
1031
+ const resumeToken = await this.generateResumeToken(interceptedCall);
1032
+ const consentUrl = this.buildConsentUrl(
1033
+ toolName,
1034
+ protection.requiredScopes,
1035
+ session,
1036
+ resumeToken,
1037
+ undefined, // projectId - handled by subclass override
1038
+ this.getConsentProvider(protection) // Provider from tool config (supports both password and oauth auth)
1039
+ );
1040
+
1041
+ this.interceptedCalls.set(resumeToken, interceptedCall);
1042
+ this.cleanupExpiredInterceptedCalls();
1043
+
1044
+ throw new DelegationRequiredError(
1045
+ toolName,
1046
+ protection.requiredScopes,
1047
+ consentUrl,
1048
+ interceptedCall,
1049
+ resumeToken
1050
+ );
1051
+ }
1052
+ }
1053
+ } else {
1054
+ // No protection required - tool can be executed freely
1055
+ if (this.config.audit?.enabled) {
1056
+ console.error(
1057
+ "[MCP-I] Tool protection check passed (no delegation required)",
1058
+ {
1059
+ tool: toolName,
1060
+ agentDid: identity.did.slice(0, 20) + "...",
1061
+ reason: "Tool not configured to require delegation",
1062
+ }
1063
+ );
1064
+ }
1065
+ }
1066
+ }
1067
+
1068
+ // Execute the tool
1069
+ const result = await handler(args);
1070
+
1071
+ // Create proof
1072
+ const proof = await this.createProof(result, session);
1073
+
1074
+ // Store proof for out-of-band retrieval
1075
+ this.lastProof = proof;
1076
+
1077
+ // Log if audit is enabled
1078
+ if (this.config.audit?.enabled) {
1079
+ this.logAudit("tool_executed", {
1080
+ tool: toolName,
1081
+ sessionId: session?.id,
1082
+ timestamp: this.clock.now(),
1083
+ });
1084
+ }
1085
+
1086
+ // Return clean result only (no proof in LLM context)
1087
+ return result;
1088
+ }
1089
+
1090
+ /**
1091
+ * Resume a tool call after authorization
1092
+ *
1093
+ * @param resumeToken - Token from DelegationRequiredError
1094
+ * @param handler - Tool execution handler
1095
+ * @param delegationToken - Delegation token from authorization
1096
+ * @returns Tool execution result
1097
+ */
1098
+ async resumeToolCall(
1099
+ resumeToken: string,
1100
+ handler: (args: unknown) => Promise<unknown>,
1101
+ delegationToken?: string
1102
+ ): Promise<unknown> {
1103
+ const interceptedCall = this.interceptedCalls.get(resumeToken);
1104
+
1105
+ if (!interceptedCall) {
1106
+ throw new Error(`Invalid or expired resume token: ${resumeToken}`);
1107
+ }
1108
+
1109
+ // Check if call has expired
1110
+ if (this.clock.hasExpired(interceptedCall.expiresAt)) {
1111
+ this.interceptedCalls.delete(resumeToken);
1112
+ throw new Error(`Resume token expired: ${resumeToken}`);
1113
+ }
1114
+
1115
+ // Get session for the intercepted call
1116
+ const session = this.sessions.get(interceptedCall.sessionId);
1117
+ if (!session) {
1118
+ throw new Error(
1119
+ `Session not found for intercepted call: ${interceptedCall.sessionId}`
1120
+ );
1121
+ }
1122
+
1123
+ // Add delegation token to session
1124
+ const enhancedSession: RuntimeSessionContext = {
1125
+ ...session,
1126
+ delegationToken,
1127
+ };
1128
+
1129
+ // Resume the tool call with delegation
1130
+ const result = await this.processToolCall(
1131
+ interceptedCall.toolName,
1132
+ interceptedCall.args,
1133
+ handler,
1134
+ enhancedSession
1135
+ );
1136
+
1137
+ // Clean up intercepted call after successful resumption to prevent memory leak
1138
+ this.interceptedCalls.delete(resumeToken);
1139
+
1140
+ return result;
1141
+ }
1142
+
1143
+ /**
1144
+ * Generate a resume token for intercepted tool call
1145
+ *
1146
+ * Uses cryptographically secure random bytes for token generation.
1147
+ * The token is used as an opaque lookup key in the interceptedCalls Map.
1148
+ */
1149
+ private async generateResumeToken(
1150
+ _call: InterceptedToolCall
1151
+ ): Promise<string> {
1152
+ const bytes = await this.crypto.randomBytes(16);
1153
+ return `resume_${this.bytesToHex(bytes)}`;
1154
+ }
1155
+
1156
+ /**
1157
+ * Clean up expired intercepted calls
1158
+ */
1159
+ private cleanupExpiredInterceptedCalls(): void {
1160
+ const now = this.clock.now();
1161
+ for (const [token, call] of this.interceptedCalls.entries()) {
1162
+ if (this.clock.hasExpired(call.expiresAt)) {
1163
+ this.interceptedCalls.delete(token);
1164
+ }
1165
+ }
1166
+ }
1167
+
1168
+ /**
1169
+ * Build consent URL for AgentShield delegation flow
1170
+ *
1171
+ * Note: Parameter names use snake_case for AgentShield API compatibility.
1172
+ * This is documented in docs/API_PARITY_GUIDE.md under "Field Naming Conventions".
1173
+ *
1174
+ * AgentShield API requires snake_case in URL parameters:
1175
+ * - session_id (not sessionId)
1176
+ * - agent_did (not agentDid)
1177
+ * - resume_token (not resumeToken)
1178
+ * - agent_name (human-readable agent name for dashboard display)
1179
+ *
1180
+ * @param toolName - Tool that requires delegation
1181
+ * @param scopes - Required scopes for the tool
1182
+ * @param session - Current session context
1183
+ * @param resumeToken - Token to resume after delegation
1184
+ * @param projectId - Project ID for AgentShield API
1185
+ * @param provider - Provider name (e.g., "github", "credentials") to select specific auth method
1186
+ * @returns Full consent URL with snake_case parameters
1187
+ */
1188
+ /**
1189
+ * MCP Apps UI consent resource URI.
1190
+ * Single shared resource for all consent flows - tool-specific data
1191
+ * is passed via structuredContent in the tool result.
1192
+ */
1193
+ // C4 (#2918): de-branded from `ui://mcpi-consent/authorize`. Must stay
1194
+ // identical to ext-apps-constants.ts CONSENT_UI_RESOURCE_URI — base emits this
1195
+ // in the tool result's `_meta.ui` and the runtime serves the resource at the
1196
+ // same URI, so a mismatch would break consent rendering. Same-exchange read =
1197
+ // no dual-accept window needed.
1198
+ protected static readonly CONSENT_UI_RESOURCE_URI =
1199
+ "ui://kya-os-consent/authorize";
1200
+
1201
+ /**
1202
+ * Check if the connected MCP client supports MCP Apps UI rendering.
1203
+ * Returns false if @modelcontextprotocol/ext-apps is not installed
1204
+ * or the client didn't advertise the io.modelcontextprotocol/ui capability.
1205
+ *
1206
+ * Override in subclasses to provide client capabilities from the MCP session.
1207
+ */
1208
+ protected hasUICapability(
1209
+ clientCapabilities?: Record<string, unknown>
1210
+ ): boolean {
1211
+ if (!clientCapabilities) {
1212
+ console.error("[MCP-I] hasUICapability: no clientCapabilities provided");
1213
+ return false;
1214
+ }
1215
+ try {
1216
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1217
+ const {
1218
+ getUiCapability,
1219
+ RESOURCE_MIME_TYPE,
1220
+ } = require("@modelcontextprotocol/ext-apps/server");
1221
+ const uiCap = getUiCapability(clientCapabilities);
1222
+ const hasUI = uiCap?.mimeTypes?.includes(RESOURCE_MIME_TYPE) ?? false;
1223
+ console.error("[MCP-I] hasUICapability check:", {
1224
+ hasUI,
1225
+ uiCap: uiCap ? JSON.stringify(uiCap) : "null",
1226
+ capabilityKeys: Object.keys(clientCapabilities),
1227
+ });
1228
+ return hasUI;
1229
+ } catch {
1230
+ // ext-apps not installed - graceful degradation
1231
+ console.error("[MCP-I] hasUICapability: ext-apps not available");
1232
+ return false;
1233
+ }
1234
+ }
1235
+
1236
+ /**
1237
+ * Mark the ext-apps SDK as available.
1238
+ * Called by subclasses after a successful dynamic import() of the SDK,
1239
+ * which avoids the CJS require() vs ESM incompatibility that causes
1240
+ * the synchronous probe to fail in Cloudflare Workers.
1241
+ */
1242
+ public setExtAppsAvailable(available: boolean): void {
1243
+ this._extAppsAvailable = available;
1244
+ }
1245
+
1246
+ /**
1247
+ * Check if the MCP Apps inline consent UI is enabled.
1248
+ * Requires BOTH conditions:
1249
+ * 1. The SDK is available (set via setExtAppsAvailable(true) after dynamic import)
1250
+ * 2. The config flag is enabled (config.inlineConsent === true OR MCPI_INLINE_CONSENT env var)
1251
+ * This allows merging the feature while keeping it off by default.
1252
+ */
1253
+ protected isExtAppsAvailable(): boolean {
1254
+ return (
1255
+ this._extAppsAvailable === true && this.config.inlineConsent === true
1256
+ );
1257
+ }
1258
+
1259
+ /**
1260
+ * Build an MCP Apps-compatible tool result that renders an inline consent UI.
1261
+ * Returns null when the host doesn't support MCP Apps or the SDK is unavailable,
1262
+ * allowing callers to fall back to DelegationRequiredError.
1263
+ *
1264
+ * @param toolName - Tool requiring delegation
1265
+ * @param scopes - Required scopes
1266
+ * @param session - Current session context
1267
+ * @param resumeToken - Token to resume after delegation
1268
+ * @param projectId - AgentShield project ID
1269
+ * @param serverUrl - Server URL for consent approval POST
1270
+ * @param clientCapabilities - MCP client capabilities from the session
1271
+ */
1272
+ public buildConsentUIResult(
1273
+ toolName: string,
1274
+ scopes: string[],
1275
+ session?: Record<string, unknown>,
1276
+ resumeToken?: string,
1277
+ projectId?: string,
1278
+ serverUrl?: string,
1279
+ clientCapabilities?: Record<string, unknown>,
1280
+ authMode: "consent-only" | "credentials" = "consent-only",
1281
+ provider?: string
1282
+ ): Record<string, unknown> | null {
1283
+ // Per the MCP Apps spec, always return UI metadata when the SDK is available.
1284
+ // Clients that support MCP Apps will render the inline iframe;
1285
+ // clients that don't will use the text content as fallback.
1286
+ // The capability check is logged but not gating.
1287
+ this.hasUICapability(clientCapabilities);
1288
+ if (!this.isExtAppsAvailable()) return null;
1289
+
1290
+ // Build fallback URL for graceful degradation within the UI itself
1291
+ const consentUrl = this.buildConsentUrl(
1292
+ toolName,
1293
+ scopes,
1294
+ session,
1295
+ resumeToken,
1296
+ projectId
1297
+ );
1298
+
1299
+ return {
1300
+ content: [
1301
+ {
1302
+ type: "text",
1303
+ text: `Authorization required for tool "${toolName}". Please approve in the consent form below, or open this link to authorize in your browser: ${consentUrl}`,
1304
+ },
1305
+ ],
1306
+ structuredContent: {
1307
+ type: "consent_required",
1308
+ authMode,
1309
+ tool: toolName,
1310
+ scopes,
1311
+ agentDid: (session?.agentDid as string) || "",
1312
+ agentName: (session?.agentName as string) || "",
1313
+ sessionId: (session?.id as string) || "",
1314
+ projectId: projectId || "",
1315
+ resumeToken: resumeToken || "",
1316
+ serverUrl: serverUrl || "",
1317
+ consentUrl,
1318
+ ...(provider ? { provider } : {}),
1319
+ },
1320
+ _meta: {
1321
+ ui: {
1322
+ resourceUri: MCPIRuntimeBase.CONSENT_UI_RESOURCE_URI,
1323
+ },
1324
+ // Legacy flat format for backward compatibility with older clients
1325
+ "ui/resourceUri": MCPIRuntimeBase.CONSENT_UI_RESOURCE_URI,
1326
+ },
1327
+ };
1328
+ }
1329
+
1330
+ protected buildConsentUrl(
1331
+ toolName: string,
1332
+ scopes: string[],
1333
+ session?: RuntimeSessionContext,
1334
+ resumeToken?: string,
1335
+ projectId?: string,
1336
+ provider?: string
1337
+ ): string {
1338
+ // Default implementation - override in subclasses
1339
+ // This URL should point to AgentShield's consent page
1340
+ // Parameter names use snake_case for AgentShield API compatibility
1341
+ const params = new URLSearchParams({
1342
+ tool: toolName,
1343
+ scopes: scopes.join(","),
1344
+ session_id: session?.id || "",
1345
+ agent_did: session?.agentDid || "",
1346
+ });
1347
+
1348
+ // Add agent_name for AgentShield dashboard display
1349
+ // Priority: session.agentName > "Unknown Agent"
1350
+ const agentName = session?.agentName;
1351
+ if (agentName) {
1352
+ params.set("agent_name", agentName);
1353
+ }
1354
+
1355
+ // Add project_id if provided (required for AgentShield consent endpoint)
1356
+ if (projectId) {
1357
+ params.set("project_id", projectId);
1358
+ }
1359
+
1360
+ // Add resume token if provided
1361
+ if (resumeToken) {
1362
+ params.set("resume_token", resumeToken);
1363
+ }
1364
+
1365
+ // Add provider if specified (allows selecting specific auth method like "credentials" or "github")
1366
+ // This is critical when multiple providers are configured for a project
1367
+ if (provider) {
1368
+ params.set("provider", provider);
1369
+ }
1370
+
1371
+ // Use AgentShield consent endpoint
1372
+ return `https://kya.vouched.id/bouncer/consent?${params.toString()}`;
1373
+ }
1374
+
1375
+ /**
1376
+ * Issue a new nonce and register it in the cache
1377
+ * Use this to get a nonce for the session context before calling processToolCall
1378
+ */
1379
+ async issueNonce(sessionId: string): Promise<string> {
1380
+ const nonce = await this.generateNonce();
1381
+ // Get session to extract agentDid for agent-scoped nonce caching
1382
+ const session = this.sessions.get(sessionId);
1383
+ const agentDid = session?.agentDid || (await this.getIdentity()).did;
1384
+ await this.nonceCache.add(
1385
+ nonce,
1386
+ 300, // 5 minute expiry in seconds
1387
+ agentDid // Agent-scoped nonce to prevent cross-agent replay attacks
1388
+ );
1389
+ return nonce;
1390
+ }
1391
+
1392
+ /**
1393
+ * Create cryptographic proof for data
1394
+ */
1395
+ async createProof(
1396
+ data: unknown,
1397
+ session?: RuntimeSessionContext
1398
+ ): Promise<RuntimeProof> {
1399
+ const identity = await this.getIdentity();
1400
+ const timestamp = this.clock.now();
1401
+
1402
+ // Use nonce from session if provided, otherwise generate new one
1403
+ let nonce: string;
1404
+ if (session?.nonce) {
1405
+ nonce = session.nonce;
1406
+ } else {
1407
+ nonce = await this.generateNonce();
1408
+ // Add nonce to cache to prevent replay (agent-scoped to prevent cross-agent replay attacks)
1409
+ const agentDid = session?.agentDid || identity.did;
1410
+ await this.nonceCache.add(
1411
+ nonce,
1412
+ 300, // 5 minute expiry in seconds
1413
+ agentDid // Agent-scoped nonce to prevent cross-agent replay attacks
1414
+ );
1415
+ }
1416
+
1417
+ const proofData = {
1418
+ data,
1419
+ timestamp,
1420
+ nonce,
1421
+ did: identity.did,
1422
+ sessionId: session?.id,
1423
+ audience: session?.audience,
1424
+ };
1425
+
1426
+ const signature = await this.signData(proofData);
1427
+
1428
+ return {
1429
+ timestamp,
1430
+ nonce,
1431
+ did: identity.did,
1432
+ signature,
1433
+ algorithm: "Ed25519",
1434
+ sessionId: session?.id,
1435
+ audience: session?.audience,
1436
+ };
1437
+ }
1438
+
1439
+ /**
1440
+ * Verify a proof
1441
+ *
1442
+ * Supports both old format (data, proof) and new DetachedProof format.
1443
+ * When DetachedProof format is used, ProofVerifier is used if available.
1444
+ *
1445
+ * @param dataOrProof - Either raw data (old format) or DetachedProof (new format)
1446
+ * @param proofOrSession - Either proof object (old format) or session context (new format)
1447
+ * @returns true if proof is valid, false otherwise
1448
+ */
1449
+ async verifyProof(
1450
+ dataOrProof: unknown,
1451
+ proofOrSession?: unknown
1452
+ ): Promise<boolean> {
1453
+ // Check if first argument is DetachedProof format
1454
+ if (
1455
+ dataOrProof &&
1456
+ typeof dataOrProof === "object" &&
1457
+ "jws" in dataOrProof &&
1458
+ "meta" in dataOrProof
1459
+ ) {
1460
+ // New DetachedProof format
1461
+ const detachedProof = dataOrProof as DetachedProof;
1462
+ const session = isRecord(proofOrSession)
1463
+ ? (proofOrSession as RuntimeSessionContext)
1464
+ : undefined;
1465
+
1466
+ // Use ProofVerifier if available
1467
+ if (this.proofVerifier) {
1468
+ try {
1469
+ // Resolve DID to get public key
1470
+ const didDoc = await this.fetch.resolveDID(detachedProof.meta.did);
1471
+ const publicKeyJwk = this.extractPublicKeyJwk(
1472
+ didDoc,
1473
+ detachedProof.meta.kid
1474
+ );
1475
+
1476
+ if (!publicKeyJwk) {
1477
+ console.error("[MCPIRuntimeBase] Failed to extract public key JWK");
1478
+ return false;
1479
+ }
1480
+
1481
+ // Verify proof using ProofVerifier
1482
+ const result = await this.proofVerifier.verifyProof(
1483
+ detachedProof,
1484
+ publicKeyJwk
1485
+ );
1486
+
1487
+ if (result.valid && session) {
1488
+ // Store canonical payload in session for detached JWS consumers
1489
+ const canonicalPayload = this.proofVerifier.buildCanonicalPayload(
1490
+ detachedProof.meta
1491
+ );
1492
+ session.canonicalPayload = canonicalPayload;
1493
+ }
1494
+
1495
+ return result.valid;
1496
+ } catch (error) {
1497
+ console.error("[MCPIRuntimeBase] Proof verification failed:", error);
1498
+ return false;
1499
+ }
1500
+ } else {
1501
+ // Fallback to old verification if ProofVerifier not available
1502
+ console.warn(
1503
+ "[MCPIRuntimeBase] ProofVerifier not available, using fallback verification"
1504
+ );
1505
+ return this.verifyProofLegacy(
1506
+ dataOrProof,
1507
+ isRecord(proofOrSession) ? proofOrSession : {}
1508
+ );
1509
+ }
1510
+ } else {
1511
+ // Old format (data, proof)
1512
+ return this.verifyProofLegacy(
1513
+ dataOrProof,
1514
+ isRecord(proofOrSession) ? proofOrSession : {}
1515
+ );
1516
+ }
1517
+ }
1518
+
1519
+ /**
1520
+ * Legacy proof verification (backward compatibility)
1521
+ * @internal
1522
+ */
1523
+ private async verifyProofLegacy(
1524
+ data: unknown,
1525
+ proof: RuntimeRecord
1526
+ ): Promise<boolean> {
1527
+ try {
1528
+ const nonce = typeof proof.nonce === "string" ? proof.nonce : undefined;
1529
+ const did = typeof proof.did === "string" ? proof.did : undefined;
1530
+ const timestamp =
1531
+ typeof proof.timestamp === "number" ? proof.timestamp : undefined;
1532
+ const signature =
1533
+ typeof proof.signature === "string" ? proof.signature : undefined;
1534
+ const sessionId =
1535
+ typeof proof.sessionId === "string" ? proof.sessionId : undefined;
1536
+
1537
+ if (!nonce || !did || !timestamp || !signature) {
1538
+ return false;
1539
+ }
1540
+
1541
+ // Check nonce hasn't been used (scoped to agent DID to prevent cross-agent replay attacks)
1542
+ if (await this.nonceCache.has(nonce, did)) {
1543
+ return false;
1544
+ }
1545
+
1546
+ // Check timestamp is within skew
1547
+ if (
1548
+ !this.clock.isWithinSkew(
1549
+ timestamp,
1550
+ this.config.session?.timestampSkewSeconds || 300
1551
+ )
1552
+ ) {
1553
+ return false;
1554
+ }
1555
+
1556
+ // Resolve DID to get public key
1557
+ const didDoc = await this.fetch.resolveDID(did);
1558
+ const publicKey = this.extractPublicKey(didDoc);
1559
+
1560
+ // Verify signature
1561
+ const proofData = {
1562
+ data,
1563
+ timestamp,
1564
+ nonce,
1565
+ did,
1566
+ sessionId,
1567
+ };
1568
+
1569
+ const dataBytes = new TextEncoder().encode(JSON.stringify(proofData));
1570
+ const signatureBytes = this.base64ToBytes(signature);
1571
+
1572
+ const isValid = await this.crypto.verify(
1573
+ dataBytes,
1574
+ signatureBytes,
1575
+ publicKey
1576
+ );
1577
+
1578
+ // If signature is valid, add nonce to cache to prevent replay (scoped to agent DID)
1579
+ if (isValid) {
1580
+ // Pass TTL in seconds, not absolute timestamp
1581
+ const ttlSeconds = (this.config.session?.ttlMinutes || 30) * 60; // Convert minutes to seconds
1582
+ await this.nonceCache.add(nonce, ttlSeconds, did);
1583
+ }
1584
+
1585
+ return isValid;
1586
+ } catch (error) {
1587
+ console.error("Proof verification failed:", error);
1588
+ return false;
1589
+ }
1590
+ }
1591
+
1592
+ /**
1593
+ * Verify a JWS proof (full compact JWS format: header.payload.signature)
1594
+ *
1595
+ * This method provides full cryptographic signature verification using CryptoService.
1596
+ * Use this when you have a DetachedProof with JWS instead of raw signature.
1597
+ *
1598
+ * @param jws - Full compact JWS string (header.payload.signature)
1599
+ * @param publicKeyJwk - Ed25519 public key in JWK format
1600
+ * @param detachedPayload - Optional detached payload for detached JWS format
1601
+ * @returns true if signature is valid, false otherwise
1602
+ */
1603
+ async verifyProofJWS(
1604
+ jws: string,
1605
+ publicKeyJwk: Ed25519JWK,
1606
+ detachedPayload?: string | Uint8Array
1607
+ ): Promise<boolean> {
1608
+ if (!this.cryptoService) {
1609
+ console.error("[MCPIRuntimeBase] CryptoService not initialized");
1610
+ return false;
1611
+ }
1612
+
1613
+ try {
1614
+ const options =
1615
+ detachedPayload !== undefined ? { detachedPayload } : undefined;
1616
+ return await this.cryptoService.verifyJWS(jws, publicKeyJwk, options);
1617
+ } catch (error) {
1618
+ console.error("[MCPIRuntimeBase] JWS verification failed:", error);
1619
+ return false;
1620
+ }
1621
+ }
1622
+
1623
+ /**
1624
+ * Get current session
1625
+ */
1626
+ async getCurrentSession(): Promise<StoredRuntimeSession | null> {
1627
+ // Find non-expired session
1628
+ for (const [id, session] of this.sessions) {
1629
+ if (!this.clock.hasExpired(session.expiresAt)) {
1630
+ return session;
1631
+ }
1632
+ }
1633
+ return null;
1634
+ }
1635
+
1636
+ /**
1637
+ * Get the last generated proof for out-of-band transport
1638
+ */
1639
+ getLastProof(): RuntimeProof | undefined {
1640
+ return this.lastProof;
1641
+ }
1642
+
1643
+ /**
1644
+ * Create well-known handler for identity verification
1645
+ */
1646
+ createWellKnownHandler(
1647
+ config?: WellKnownConfig
1648
+ ): (path: string) => Promise<WellKnownResponse | MCPIdentity | null> {
1649
+ return async (path: string) => {
1650
+ const identity = await this.getIdentity();
1651
+
1652
+ if (path === "/.well-known/did.json") {
1653
+ const didDocument = this.createDIDDocument(identity);
1654
+ return {
1655
+ status: 200,
1656
+ headers: {
1657
+ "Content-Type": "application/did+json",
1658
+ "Cache-Control":
1659
+ this.config.environment === "production"
1660
+ ? "public, max-age=300"
1661
+ : "no-store",
1662
+ },
1663
+ body: JSON.stringify(didDocument, null, 2),
1664
+ };
1665
+ }
1666
+
1667
+ if (path === "/.well-known/agent.json") {
1668
+ const agentDocument: AgentDocument = {
1669
+ id: identity.did,
1670
+ capabilities: {
1671
+ "mcp-i": ["handshake", "signing", "verification"],
1672
+ },
1673
+ };
1674
+
1675
+ if (config?.serviceName || config?.serviceEndpoint) {
1676
+ agentDocument.metadata = {
1677
+ ...(config?.serviceName && { name: config.serviceName }),
1678
+ ...(config?.serviceEndpoint && {
1679
+ serviceEndpoint: config.serviceEndpoint,
1680
+ }),
1681
+ };
1682
+ }
1683
+
1684
+ return {
1685
+ status: 200,
1686
+ headers: {
1687
+ "Content-Type": "application/json",
1688
+ "Cache-Control":
1689
+ this.config.environment === "production"
1690
+ ? "public, max-age=300"
1691
+ : "no-store",
1692
+ },
1693
+ body: JSON.stringify(agentDocument, null, 2),
1694
+ };
1695
+ }
1696
+
1697
+ if (
1698
+ path === LEGACY_WELL_KNOWN_IDENTITY_PATH ||
1699
+ path === WELL_KNOWN_IDENTITY_PATH
1700
+ ) {
1701
+ // C4 (#2918) dual-accept: `kya-os-identity` is the canonical discovery
1702
+ // path; the legacy `mcp-identity` path stays served with an identical
1703
+ // body during the window. The W3C-frozen did.json / agent.json paths
1704
+ // are untouched. Count the wire form for the sunset gate.
1705
+ recordWireForm(
1706
+ "well_known",
1707
+ path === WELL_KNOWN_IDENTITY_PATH ? "new" : "old"
1708
+ );
1709
+ return {
1710
+ did: identity.did,
1711
+ publicKey: identity.publicKey,
1712
+ serviceName: config?.serviceName || "MCP-I Service",
1713
+ serviceEndpoint: config?.serviceEndpoint || "https://example.com",
1714
+ timestamp: this.clock.now(),
1715
+ };
1716
+ }
1717
+
1718
+ // SEP-1649 MCP Server Card for client discovery
1719
+ // Support both paths during spec transition:
1720
+ // - /.well-known/mcp.json (current Cursor/Claude Desktop usage)
1721
+ // - /.well-known/mcp/server-card.json (SEP-1649 proposed spec)
1722
+ if (
1723
+ path === "/.well-known/mcp.json" ||
1724
+ path === "/.well-known/mcp/server-card.json"
1725
+ ) {
1726
+ const serverName = config?.serviceName || "mcp-i-server";
1727
+
1728
+ // SEP-1649 compliant MCP Server Card
1729
+ const mcpServerCard = {
1730
+ $schema:
1731
+ "https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json",
1732
+ version: "1.0",
1733
+ protocolVersion: config?.protocolVersion || "2025-06-18",
1734
+ serverInfo: {
1735
+ name: serverName,
1736
+ title:
1737
+ config?.serviceTitle || config?.serviceName || "MCP-I Server",
1738
+ version: config?.serverVersion || "1.0.0",
1739
+ },
1740
+ description:
1741
+ config?.description ||
1742
+ "MCP-I enabled server with cryptographic identity",
1743
+ ...(config?.iconUrl && { iconUrl: config.iconUrl }),
1744
+ ...(config?.documentationUrl && {
1745
+ documentationUrl: config.documentationUrl,
1746
+ }),
1747
+ transport: {
1748
+ type: "streamable-http" as const,
1749
+ endpoint: "/mcp",
1750
+ },
1751
+ capabilities: {
1752
+ tools: { listChanged: true },
1753
+ },
1754
+ ...(config?.requiresAuth && {
1755
+ authentication: {
1756
+ required: true,
1757
+ schemes: config.authSchemes || ["oauth2"],
1758
+ },
1759
+ }),
1760
+ ...(config?.instructions && { instructions: config.instructions }),
1761
+ // Tools are dynamic - discovered via protocol
1762
+ tools: "dynamic" as const,
1763
+ _meta: {
1764
+ ...config?.metadata,
1765
+ "mcp-i": {
1766
+ agentDid: identity.did,
1767
+ publicKey: identity.publicKey,
1768
+ generatedAt: this.clock.now(),
1769
+ },
1770
+ },
1771
+ };
1772
+
1773
+ const headers: Record<string, string> = {
1774
+ "Content-Type": "application/json",
1775
+ "Cache-Control":
1776
+ this.config.environment === "production"
1777
+ ? "public, max-age=3600" // SEP-1649 recommends 1 hour
1778
+ : "no-store",
1779
+ // SEP-1649 CORS requirements for browser-based client discovery
1780
+ "Access-Control-Allow-Origin": "*",
1781
+ "Access-Control-Allow-Methods": "GET",
1782
+ "Access-Control-Allow-Headers": "Content-Type",
1783
+ };
1784
+
1785
+ return {
1786
+ status: 200,
1787
+ headers,
1788
+ body: JSON.stringify(mcpServerCard, null, 2),
1789
+ };
1790
+ }
1791
+
1792
+ // Client configuration helper - ready-to-use config for Cursor/Claude Desktop
1793
+ if (path === "/.well-known/mcp-client-config.json") {
1794
+ const serviceEndpoint =
1795
+ config?.serviceEndpoint || "https://example.com";
1796
+ const serverName = config?.serviceName || "mcp-i-server";
1797
+ const mcpUrl = `${serviceEndpoint}/mcp`;
1798
+
1799
+ // Generate Cursor deep link
1800
+ // Note: Base64 can contain +, /, = which have special meaning in URLs
1801
+ // Must URL-encode the base64 string for safe transmission
1802
+ const cursorConfig = {
1803
+ [serverName]: { url: mcpUrl, transport: "sse" },
1804
+ };
1805
+ const encodedConfig = Buffer.from(
1806
+ JSON.stringify(cursorConfig)
1807
+ ).toString("base64");
1808
+ const cursorDeepLink = `cursor://anysphere.cursor-deeplink/mcp/install?name=${encodeURIComponent(serverName)}&config=${encodeURIComponent(encodedConfig)}`;
1809
+
1810
+ const clientConfig = {
1811
+ // For claude_desktop_config.json
1812
+ claudeDesktop: {
1813
+ mcpServers: {
1814
+ [serverName]: {
1815
+ url: mcpUrl,
1816
+ transport: "sse",
1817
+ },
1818
+ },
1819
+ },
1820
+ // For .cursor/mcp.json
1821
+ cursor: {
1822
+ mcpServers: {
1823
+ [serverName]: {
1824
+ url: mcpUrl,
1825
+ transport: "sse",
1826
+ },
1827
+ },
1828
+ },
1829
+ // One-click install for Cursor
1830
+ cursorDeepLink,
1831
+ // Additional info
1832
+ _meta: {
1833
+ serverName,
1834
+ serverUrl: serviceEndpoint,
1835
+ mcpEndpoint: mcpUrl,
1836
+ agentDid: identity.did,
1837
+ generatedAt: this.clock.now(),
1838
+ instructions:
1839
+ "Copy the appropriate config section to your client configuration file.",
1840
+ },
1841
+ };
1842
+
1843
+ return {
1844
+ status: 200,
1845
+ headers: {
1846
+ "Content-Type": "application/json",
1847
+ "Cache-Control":
1848
+ this.config.environment === "production"
1849
+ ? "public, max-age=300"
1850
+ : "no-store",
1851
+ },
1852
+ body: JSON.stringify(clientConfig, null, 2),
1853
+ };
1854
+ }
1855
+
1856
+ return null;
1857
+ };
1858
+ }
1859
+
1860
+ /**
1861
+ * Create debug endpoint (development only)
1862
+ */
1863
+ createDebugEndpoint(): (() => Promise<RuntimeRecord>) | null {
1864
+ if (this.config.environment === "production") {
1865
+ return null;
1866
+ }
1867
+
1868
+ return async () => {
1869
+ const identity = await this.getIdentity();
1870
+ const session = await this.getCurrentSession();
1871
+
1872
+ return {
1873
+ identity: {
1874
+ did: identity.did,
1875
+ publicKey: identity.publicKey,
1876
+ },
1877
+ session,
1878
+ config: {
1879
+ environment: this.config.environment,
1880
+ timestampSkewSeconds: this.config.session?.timestampSkewSeconds,
1881
+ sessionTtlMinutes: this.config.session?.ttlMinutes,
1882
+ },
1883
+ timestamp: this.clock.now(),
1884
+ };
1885
+ };
1886
+ }
1887
+
1888
+ /**
1889
+ * Get audit logger
1890
+ */
1891
+ getAuditLogger(): RuntimeAuditLogger | undefined {
1892
+ return {
1893
+ log: (event: string, data: unknown) => this.logAudit(event, data),
1894
+ };
1895
+ }
1896
+
1897
+ /**
1898
+ * Rotate keys
1899
+ */
1900
+ async rotateKeys(): Promise<AgentIdentity> {
1901
+ const oldDid = this.cachedIdentity?.did;
1902
+ const newIdentity = await this.identity.rotateKeys();
1903
+ this.cachedIdentity = newIdentity;
1904
+
1905
+ if (this.config.audit?.enabled) {
1906
+ this.logAudit("keys_rotated", {
1907
+ oldDid: oldDid,
1908
+ newDid: newIdentity.did,
1909
+ timestamp: this.clock.now(),
1910
+ });
1911
+ }
1912
+
1913
+ return newIdentity;
1914
+ }
1915
+
1916
+ // Helper methods
1917
+
1918
+ private async signData(data: unknown): Promise<string> {
1919
+ const identity = await this.getIdentity();
1920
+ const dataBytes = new TextEncoder().encode(JSON.stringify(data));
1921
+ const signature = await this.crypto.sign(dataBytes, identity.privateKey);
1922
+ return this.bytesToBase64(signature);
1923
+ }
1924
+
1925
+ private async generateNonce(): Promise<string> {
1926
+ const bytes = await this.crypto.randomBytes(32);
1927
+ return this.bytesToBase64(bytes);
1928
+ }
1929
+
1930
+ /**
1931
+ * Generate a unique session ID.
1932
+ *
1933
+ * C4 (#2918) dual-accept window: emits the canonical `kyaos_` prefix
1934
+ * ({@link SESSION_ID_PREFIX}). The earlier C2 (#2916) note that the `mcpi_`
1935
+ * prefix was "frozen until C4" no longer applies — this is that flip. Reads
1936
+ * stay lenient (the store keys on the full opaque id), so a client still
1937
+ * presenting a pre-flip `mcpi_…` id resolves; old ids drain within a TTL.
1938
+ */
1939
+ private async generateSessionId(): Promise<string> {
1940
+ const bytes = await this.crypto.randomBytes(16);
1941
+ // Set version (4) and variant (RFC4122)
1942
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
1943
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
1944
+ const hex = this.bytesToHex(bytes);
1945
+ const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
1946
+ return `${SESSION_ID_PREFIX}${uuid}`;
1947
+ }
1948
+
1949
+ /**
1950
+ * Log structured events in JSON format (NOT frozen audit format).
1951
+ *
1952
+ * **Important:** This method logs events in JSON format for general runtime events
1953
+ * (e.g., "runtime_initialized", "tool_executed", "keys_rotated").
1954
+ *
1955
+ * **For frozen format audit logs** (MCP-I spec compliance), use `AuditLogger.logAuditRecord()`
1956
+ * from `@kya-os/mcp-i/runtime` instead. The frozen format is:
1957
+ * ```
1958
+ * audit.v1 ts=<unix> session=<id> audience=<host> did=<did> kid=<kid> reqHash=<sha256:..> resHash=<sha256:..> verified=yes|no scope=<scopeId|->
1959
+ * ```
1960
+ *
1961
+ * **Format:** JSON object with `event`, `data`, `timestamp`, and `timestampFormatted` fields.
1962
+ *
1963
+ * **Privacy:** If `includePayloads` is false (default), the `data` field is omitted.
1964
+ *
1965
+ * **Use Cases:**
1966
+ * - Developer debugging and local logging
1967
+ * - Runtime initialization events
1968
+ * - Tool execution tracking (non-spec-compliant)
1969
+ * - Key rotation events
1970
+ *
1971
+ * **NOT for:**
1972
+ * - MCP-I spec-compliant audit logs (use `AuditLogger`)
1973
+ * - Production audit trails (use `AuditLogger`)
1974
+ * - Compliance requirements (use `AuditLogger`)
1975
+ *
1976
+ * @param event - Event name (e.g., "runtime_initialized", "tool_executed")
1977
+ * @param data - Event data (only included if `includePayloads` is true)
1978
+ *
1979
+ * @example
1980
+ * ```typescript
1981
+ * // Logs: {"event":"runtime_initialized","timestamp":1234567890,"timestampFormatted":"2024-01-01T00:00:00Z"}
1982
+ * this.logAudit("runtime_initialized", { did: "did:key:..." });
1983
+ * ```
1984
+ *
1985
+ * @internal This is a private method for internal runtime events.
1986
+ * Use AuditLogger for spec-compliant frozen format audit logs.
1987
+ */
1988
+ private logAudit(event: string, data: unknown): void {
1989
+ if (!this.config.audit?.enabled) return;
1990
+
1991
+ const record = {
1992
+ event,
1993
+ data: this.config.audit.includePayloads ? data : undefined,
1994
+ timestamp: this.clock.now(),
1995
+ timestampFormatted: this.clock.format(this.clock.now()),
1996
+ };
1997
+
1998
+ const logLine = JSON.stringify(record);
1999
+
2000
+ if (this.config.audit.logFunction) {
2001
+ this.config.audit.logFunction(logLine);
2002
+ } else {
2003
+ console.error("[AUDIT]", logLine);
2004
+ }
2005
+ }
2006
+
2007
+ private createDIDDocument(identity: AgentIdentity): DIDDocument {
2008
+ return {
2009
+ "@context": ["https://www.w3.org/ns/did/v1"],
2010
+ id: identity.did,
2011
+ verificationMethod: [
2012
+ {
2013
+ id: `${identity.did}#key-1`,
2014
+ type: "Ed25519VerificationKey2020",
2015
+ controller: identity.did,
2016
+ // Using base64 for cross-platform compatibility (Cloudflare Workers)
2017
+ // W3C DID spec supports both base64 and multibase formats
2018
+ publicKeyBase64: identity.publicKey,
2019
+ },
2020
+ ],
2021
+ authentication: [`${identity.did}#key-1`],
2022
+ assertionMethod: [`${identity.did}#key-1`],
2023
+ };
2024
+ }
2025
+
2026
+ private extractPublicKey(didDoc: DIDDocument | RuntimeRecord): string {
2027
+ const verificationMethods = isRecord(didDoc)
2028
+ ? didDoc.verificationMethod
2029
+ : undefined;
2030
+ const method = Array.isArray(verificationMethods)
2031
+ ? (verificationMethods[0] as RuntimeRecord | undefined)
2032
+ : undefined;
2033
+ if (method?.publicKeyBase64) {
2034
+ return String(method.publicKeyBase64);
2035
+ }
2036
+ if (method?.publicKeyMultibase) {
2037
+ // Convert multibase to base64
2038
+ return String(method.publicKeyMultibase); // Simplified
2039
+ }
2040
+ throw new Error("Public key not found in DID document");
2041
+ }
2042
+
2043
+ /**
2044
+ * Extract public key JWK from DID document
2045
+ */
2046
+ private extractPublicKeyJwk(
2047
+ didDoc: DIDDocument | RuntimeRecord,
2048
+ kid?: string
2049
+ ): Ed25519JWK | null {
2050
+ const verificationMethods = isRecord(didDoc)
2051
+ ? didDoc.verificationMethod
2052
+ : undefined;
2053
+ const verificationMethodList = Array.isArray(verificationMethods)
2054
+ ? (verificationMethods as RuntimeRecord[])
2055
+ : [];
2056
+
2057
+ // Try to find Ed25519 public key matching kid if provided
2058
+ const verificationMethod =
2059
+ verificationMethodList.find((vm) => {
2060
+ const vmType = typeof vm.type === "string" ? vm.type : undefined;
2061
+ const vmId = typeof vm.id === "string" ? vm.id : undefined;
2062
+ const matchesType =
2063
+ vmType === "Ed25519VerificationKey2020" ||
2064
+ vmType === "JsonWebKey2020";
2065
+ const matchesKid = !kid || vmId === kid || vmId?.endsWith(`#${kid}`);
2066
+ return matchesType && matchesKid;
2067
+ }) || verificationMethodList[0]; // Fallback to first method
2068
+
2069
+ if (verificationMethod && isRecord(verificationMethod.publicKeyJwk)) {
2070
+ const jwk = verificationMethod.publicKeyJwk;
2071
+ // Ensure it's Ed25519 format
2072
+ if (jwk.kty === "OKP" && jwk.crv === "Ed25519") {
2073
+ return jwk as unknown as Ed25519JWK;
2074
+ }
2075
+ }
2076
+
2077
+ // Fallback: try to convert multibase to JWK (simplified)
2078
+ if (verificationMethod?.publicKeyMultibase) {
2079
+ // This is a simplified conversion - in production, use proper multibase decoding
2080
+ console.warn(
2081
+ "[MCPIRuntimeBase] Multibase to JWK conversion not fully implemented"
2082
+ );
2083
+ return null;
2084
+ }
2085
+
2086
+ return null;
2087
+ }
2088
+
2089
+ private bytesToBase64(bytes: Uint8Array): string {
2090
+ return Buffer.from(bytes).toString("base64");
2091
+ }
2092
+
2093
+ private base64ToBytes(base64: string): Uint8Array {
2094
+ return new Uint8Array(Buffer.from(base64, "base64"));
2095
+ }
2096
+
2097
+ private bytesToHex(bytes: Uint8Array): string {
2098
+ return Buffer.from(bytes).toString("hex");
2099
+ }
2100
+ }