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