@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,1048 @@
1
+ /**
2
+ * Access Control API Service
3
+ *
4
+ * Brand-neutral service for interacting with access-control APIs
5
+ * (currently AgentShield/bouncer, but designed to be provider-agnostic).
6
+ *
7
+ * This service provides:
8
+ * - Delegation verification
9
+ * - Configuration fetching
10
+ * - Proof submission
11
+ *
12
+ * @package @kya-os/mcp-i-core
13
+ */
14
+
15
+ import type {
16
+ VerifyDelegationRequest,
17
+ VerifyDelegationAPIResponse,
18
+ ToolProtectionConfigAPIResponse,
19
+ ProofSubmissionRequest,
20
+ ProofSubmissionResponse,
21
+ } from "@kya-os/contracts/agentshield-api";
22
+ import {
23
+ verifyDelegationRequestSchema,
24
+ verifyDelegationAPIResponseSchema,
25
+ toolProtectionConfigAPIResponseSchema,
26
+ proofSubmissionRequestSchema,
27
+ proofSubmissionResponseSchema,
28
+ } from "@kya-os/contracts/agentshield-api";
29
+ import { AgentShieldAPIError } from "@kya-os/contracts/agentshield-api";
30
+ import type { FetchProvider } from "../providers/base";
31
+
32
+ // Type for error response
33
+ type AgentShieldAPIErrorResponse = {
34
+ code: string;
35
+ message: string;
36
+ details?: Record<string, unknown>;
37
+ };
38
+
39
+ export interface AccessControlApiServiceConfig {
40
+ /** Base URL for the access-control API (e.g., "https://kya.vouched.id") */
41
+ baseUrl: string;
42
+
43
+ /** API key for authentication */
44
+ apiKey: string;
45
+
46
+ /** Fetch provider for making HTTP requests */
47
+ fetchProvider: FetchProvider;
48
+
49
+ /** Optional logger callback for diagnostics */
50
+ logger?: (message: string, data?: unknown) => void;
51
+
52
+ /** Optional retry configuration */
53
+ retryConfig?: {
54
+ maxRetries?: number;
55
+ initialDelayMs?: number;
56
+ maxDelayMs?: number;
57
+ };
58
+
59
+ /** Optional sleep function for delays (platform-agnostic) */
60
+ sleepProvider?: (ms: number) => Promise<void>;
61
+ }
62
+
63
+ export interface AccessControlApiServiceMetrics {
64
+ /** Number of successful requests */
65
+ successCount: number;
66
+
67
+ /** Number of failed requests */
68
+ errorCount: number;
69
+
70
+ /** Number of retries performed */
71
+ retryCount: number;
72
+ }
73
+
74
+ /**
75
+ * Internal type with all required properties
76
+ */
77
+ type RequiredAccessControlApiServiceConfig = Required<
78
+ Omit<AccessControlApiServiceConfig, "retryConfig" | "sleepProvider">
79
+ > & {
80
+ retryConfig: Required<
81
+ NonNullable<AccessControlApiServiceConfig["retryConfig"]>
82
+ >;
83
+ sleepProvider: NonNullable<AccessControlApiServiceConfig["sleepProvider"]>;
84
+ };
85
+
86
+ /**
87
+ * Generate correlation ID for request tracking
88
+ */
89
+ function generateCorrelationId(): string {
90
+ // Use crypto.randomUUID() if available (Node.js 14.17+, Cloudflare Workers)
91
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
92
+ return crypto.randomUUID();
93
+ }
94
+ // Fallback for older environments
95
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
96
+ }
97
+
98
+ /**
99
+ * Access Control API Service
100
+ *
101
+ * Handles all interactions with the access-control API (AgentShield/bouncer).
102
+ * Designed to be brand-neutral and work with any access-control provider.
103
+ */
104
+ export class AccessControlApiService {
105
+ private config: RequiredAccessControlApiServiceConfig;
106
+ private metrics: AccessControlApiServiceMetrics;
107
+
108
+ constructor(config: AccessControlApiServiceConfig) {
109
+ const retryConfig = config.retryConfig || {};
110
+ this.config = {
111
+ retryConfig: {
112
+ maxRetries: retryConfig.maxRetries ?? 3,
113
+ initialDelayMs: retryConfig.initialDelayMs ?? 100,
114
+ maxDelayMs: retryConfig.maxDelayMs ?? 5000,
115
+ },
116
+ logger: config.logger || (() => {}),
117
+ baseUrl: config.baseUrl,
118
+ apiKey: config.apiKey,
119
+ fetchProvider: config.fetchProvider,
120
+ sleepProvider:
121
+ config.sleepProvider ||
122
+ ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))),
123
+ };
124
+
125
+ this.metrics = {
126
+ successCount: 0,
127
+ errorCount: 0,
128
+ retryCount: 0,
129
+ };
130
+ }
131
+
132
+ /**
133
+ * Fetch tool protection configuration for an agent
134
+ *
135
+ * GET /api/v1/bouncer/config?agent_did={agentDid}
136
+ */
137
+ async fetchConfig(options: {
138
+ agentDid: string;
139
+ }): Promise<ToolProtectionConfigAPIResponse> {
140
+ return this.retryWithBackoff(async () => {
141
+ const correlationId = generateCorrelationId();
142
+ const url = `${this.config.baseUrl}/api/v1/bouncer/config?agent_did=${encodeURIComponent(options.agentDid)}`;
143
+
144
+ this.config.logger(
145
+ `[AccessControl] Fetching config for agent: ${options.agentDid}`,
146
+ {
147
+ correlationId,
148
+ url,
149
+ }
150
+ );
151
+
152
+ const response = await this.config.fetchProvider.fetch(url, {
153
+ method: "GET",
154
+ headers: {
155
+ Authorization: `Bearer ${this.config.apiKey}`,
156
+ "Content-Type": "application/json",
157
+ "X-Request-ID": correlationId,
158
+ },
159
+ });
160
+
161
+ const responseText = await response.text();
162
+ const responseData = this.parseResponseJSON(response, responseText);
163
+
164
+ // Handle error responses
165
+ if (!response.ok) {
166
+ this.handleErrorResponse(response, responseData);
167
+ }
168
+
169
+ // Validate and parse success response
170
+ const parsed =
171
+ toolProtectionConfigAPIResponseSchema.safeParse(responseData);
172
+ if (!parsed.success) {
173
+ throw new AgentShieldAPIError(
174
+ "invalid_response",
175
+ "Response validation failed",
176
+ { zodErrors: parsed.error.errors }
177
+ );
178
+ }
179
+
180
+ this.config.logger(`[AccessControl] Config fetched successfully`, {
181
+ correlationId,
182
+ agentDid: options.agentDid,
183
+ });
184
+
185
+ return parsed.data;
186
+ });
187
+ }
188
+
189
+ /**
190
+ * Verify a delegation token
191
+ *
192
+ * POST /api/v1/bouncer/delegations/verify
193
+ */
194
+ async verifyDelegation(
195
+ request: VerifyDelegationRequest,
196
+ context?: {
197
+ delegationToken?: string;
198
+ credentialJwt?: string;
199
+ }
200
+ ): Promise<VerifyDelegationAPIResponse> {
201
+ return this.retryWithBackoff(async () => {
202
+ const correlationId = generateCorrelationId();
203
+ const url = `${this.config.baseUrl}/api/v1/bouncer/delegations/verify`;
204
+
205
+ // Build request body dynamically to handle optional fields
206
+ const requestBody: Partial<VerifyDelegationRequest> & {
207
+ agent_did: string;
208
+ } = {
209
+ agent_did: request.agent_did,
210
+ };
211
+
212
+ // Add optional fields only if they exist
213
+ if (request.scopes !== undefined) {
214
+ requestBody.scopes = request.scopes;
215
+ }
216
+
217
+ // ✅ CRITICAL: Include user_did for user-scoped delegation verification
218
+ // This prevents cross-user delegation leakage (Priority 3 fallback issue)
219
+ if (request.user_did !== undefined) {
220
+ requestBody.user_did = request.user_did;
221
+ }
222
+
223
+ // Handle credential_jwt: prefer request, fallback to context
224
+ if (request.credential_jwt !== undefined) {
225
+ requestBody.credential_jwt = request.credential_jwt;
226
+ } else if (context?.credentialJwt) {
227
+ requestBody.credential_jwt = context.credentialJwt;
228
+ }
229
+
230
+ // Handle delegation_token: prefer request, fallback to context
231
+ if (request.delegation_token !== undefined) {
232
+ requestBody.delegation_token = request.delegation_token;
233
+ } else if (context?.delegationToken) {
234
+ requestBody.delegation_token = context.delegationToken;
235
+ }
236
+
237
+ if (request.timestamp !== undefined) {
238
+ requestBody.timestamp = request.timestamp;
239
+ }
240
+
241
+ if (request.client_info) {
242
+ requestBody.client_info = request.client_info;
243
+ }
244
+
245
+ // Remove undefined values to ensure Zod validation passes (optional fields should be omitted, not undefined)
246
+ const cleanedRequestBody = Object.fromEntries(
247
+ Object.entries(requestBody).filter(([_, value]) => value !== undefined)
248
+ );
249
+
250
+ // Validate the cleaned request body
251
+ // Note: Workaround for Zod schema issue where .optional() doesn't properly handle omitted fields
252
+ // See AGENTSHIELD_MCPI_COMPLIANCE_REVIEW.md for details
253
+ const validationResult =
254
+ verifyDelegationRequestSchema.safeParse(cleanedRequestBody);
255
+ if (!validationResult.success) {
256
+ // Check if the error is specifically about scopes being required when it's omitted
257
+ const scopesError = validationResult.error.errors.find(
258
+ (e) => e.path.includes("scopes") && e.message === "Required"
259
+ );
260
+ if (scopesError && !("scopes" in cleanedRequestBody)) {
261
+ // This is a known Zod schema issue in AgentShield - scopes is optional but Zod treats it as required
262
+ // Skip validation for this case since the field is correctly omitted
263
+ // TODO: Remove this workaround once AgentShield fixes their schema
264
+ } else {
265
+ this.config.logger(`[AccessControl] Validation failed:`, {
266
+ errors: validationResult.error.errors,
267
+ requestBody: requestBody,
268
+ });
269
+ throw new AgentShieldAPIError(
270
+ "validation_error",
271
+ "Request validation failed",
272
+ { zodErrors: validationResult.error.errors }
273
+ );
274
+ }
275
+ }
276
+
277
+ this.config.logger(
278
+ `[AccessControl] Verifying delegation for agent: ${request.agent_did}`,
279
+ {
280
+ correlationId,
281
+ url,
282
+ hasScopes: (request.scopes?.length || 0) > 0,
283
+ }
284
+ );
285
+
286
+ const response = await this.config.fetchProvider.fetch(url, {
287
+ method: "POST",
288
+ headers: {
289
+ Authorization: `Bearer ${this.config.apiKey}`,
290
+ "Content-Type": "application/json",
291
+ "X-Request-ID": correlationId,
292
+ },
293
+ // Use cleanedRequestBody directly instead of validated data
294
+ // because Zod seems to strip optional fields in some cases
295
+ body: JSON.stringify(cleanedRequestBody),
296
+ });
297
+
298
+ const responseText = await response.text();
299
+ const responseData = this.parseResponseJSON(response, responseText);
300
+
301
+ // Handle error responses
302
+ if (!response.ok) {
303
+ this.handleErrorResponse(response, responseData);
304
+ }
305
+
306
+ // Validate and parse success response
307
+ const parsed = verifyDelegationAPIResponseSchema.safeParse(responseData);
308
+ if (!parsed.success) {
309
+ throw new AgentShieldAPIError(
310
+ "invalid_response",
311
+ "Response validation failed",
312
+ { zodErrors: parsed.error.errors }
313
+ );
314
+ }
315
+
316
+ this.config.logger(`[AccessControl] Delegation verified`, {
317
+ correlationId,
318
+ agentDid: request.agent_did,
319
+ valid: parsed.data.data.valid,
320
+ });
321
+
322
+ return parsed.data;
323
+ });
324
+ }
325
+
326
+ /**
327
+ * Submit proofs for audit and verification
328
+ *
329
+ * POST /api/v1/bouncer/proofs
330
+ */
331
+ async submitProofs(
332
+ request: ProofSubmissionRequest
333
+ ): Promise<ProofSubmissionResponse> {
334
+ return this.retryWithBackoff(async () => {
335
+ // Validate request directly - Zod's .nullish() should handle null/undefined correctly
336
+ const validationResult = proofSubmissionRequestSchema.safeParse(request);
337
+ if (!validationResult.success) {
338
+ // Log validation errors for debugging
339
+ const errorDetails = JSON.stringify(
340
+ validationResult.error.errors,
341
+ null,
342
+ 2
343
+ );
344
+ this.config.logger(
345
+ `[AccessControl] Proof submission validation failed:`,
346
+ {
347
+ errors: validationResult.error.errors,
348
+ request: JSON.stringify(request, null, 2),
349
+ }
350
+ );
351
+ throw new AgentShieldAPIError(
352
+ "validation_error",
353
+ `Request validation failed: ${errorDetails}`,
354
+ { zodErrors: validationResult.error.errors }
355
+ );
356
+ }
357
+
358
+ // Use validated request for the API call
359
+ const validatedRequest = validationResult.data;
360
+
361
+ const correlationId = generateCorrelationId();
362
+ const url = `${this.config.baseUrl}/api/v1/bouncer/proofs`;
363
+
364
+ this.config.logger(
365
+ `[AccessControl] Submitting ${request.proofs.length} proof(s)`,
366
+ {
367
+ correlationId,
368
+ url,
369
+ sessionId: request.session_id,
370
+ delegationId: request.delegation_id,
371
+ }
372
+ );
373
+
374
+ const httpResponse = await this.config.fetchProvider.fetch(url, {
375
+ method: "POST",
376
+ headers: {
377
+ Authorization: `Bearer ${this.config.apiKey}`,
378
+ "Content-Type": "application/json",
379
+ "X-Request-ID": correlationId,
380
+ },
381
+ body: JSON.stringify(validatedRequest),
382
+ });
383
+
384
+ const responseText = await httpResponse.text();
385
+
386
+ // CRITICAL: Log raw response IMMEDIATELY before parsing/validation
387
+ // This will help us debug validation failures
388
+ console.error(`[AccessControl] 🔍 RAW API RESPONSE (before parsing):`, {
389
+ correlationId,
390
+ status: httpResponse.status,
391
+ statusText: httpResponse.statusText,
392
+ headers: Object.fromEntries(httpResponse.headers.entries()),
393
+ responseTextLength: responseText.length,
394
+ responseTextPreview: responseText.substring(0, 500),
395
+ fullResponseText: responseText, // Full response for debugging
396
+ });
397
+
398
+ const responseData = this.parseResponseJSON(httpResponse, responseText);
399
+
400
+ // Log parsed response immediately after parsing
401
+ console.error(`[AccessControl] 🔍 PARSED RESPONSE DATA:`, {
402
+ correlationId,
403
+ status: httpResponse.status,
404
+ responseDataType: typeof responseData,
405
+ responseDataKeys: Object.keys(
406
+ (responseData as Record<string, unknown>) || {}
407
+ ),
408
+ responseData: JSON.stringify(responseData, null, 2),
409
+ });
410
+
411
+ // Handle error responses
412
+ if (!httpResponse.ok) {
413
+ const errorData = responseData as {
414
+ success?: boolean;
415
+ error?: AgentShieldAPIErrorResponse;
416
+ };
417
+
418
+ if (errorData.error) {
419
+ const errorCode = errorData.error.code || "api_error";
420
+
421
+ // Special handling for all_proofs_rejected - return response instead of throwing
422
+ if (
423
+ errorCode === "all_proofs_rejected" &&
424
+ httpResponse.status === 400
425
+ ) {
426
+ // Parse the error details to extract accepted/rejected counts
427
+ const errorDetails = errorData.error.details as
428
+ | { rejected?: number; errors?: unknown[] }
429
+ | undefined;
430
+ // Create response matching ProofSubmissionResponse interface
431
+ // Validate structure with Zod to ensure type safety
432
+ const errorResponseData = {
433
+ success: false, // ProofSubmissionResponse has a success field
434
+ accepted: 0,
435
+ rejected: errorDetails?.rejected || request.proofs.length,
436
+ outcomes: {
437
+ success: 0,
438
+ failed: 0,
439
+ blocked: 0,
440
+ error: errorDetails?.rejected || request.proofs.length,
441
+ },
442
+ errors: errorDetails?.errors,
443
+ };
444
+
445
+ // Validate with Zod schema to ensure type safety
446
+ const validated =
447
+ proofSubmissionResponseSchema.safeParse(errorResponseData);
448
+ if (validated.success) {
449
+ return validated.data;
450
+ }
451
+
452
+ // If validation fails, log and throw error
453
+ throw new AgentShieldAPIError(
454
+ "invalid_response",
455
+ "Error response validation failed",
456
+ { zodErrors: validated.error.errors }
457
+ );
458
+ }
459
+
460
+ // Ensure error details include status code for retry detection
461
+ const errorDetails = {
462
+ ...(errorData.error.details || {}),
463
+ status: httpResponse.status,
464
+ };
465
+ throw new AgentShieldAPIError(
466
+ errorCode,
467
+ errorData.error.message || `API error: ${httpResponse.status}`,
468
+ errorDetails
469
+ );
470
+ }
471
+
472
+ // Map status codes to error codes
473
+ let errorCode = "api_error";
474
+ if (httpResponse.status === 400) {
475
+ errorCode = "validation_error";
476
+ } else if (httpResponse.status === 404) {
477
+ errorCode = httpResponse.statusText.includes("delegation")
478
+ ? "delegation_not_found"
479
+ : "session_not_found";
480
+ }
481
+
482
+ throw new AgentShieldAPIError(
483
+ errorCode,
484
+ `API request failed: ${httpResponse.status} ${httpResponse.statusText}`,
485
+ { status: httpResponse.status, responseData }
486
+ );
487
+ }
488
+
489
+ // Try to handle wrapped response format first
490
+ const wrappedResponse = responseData as {
491
+ success?: boolean;
492
+ data?: unknown;
493
+ metadata?: unknown;
494
+ };
495
+
496
+ // Log raw response for debugging (always log full response on first submission)
497
+ const rawResponseLog = {
498
+ correlationId,
499
+ hasSuccess: wrappedResponse.success !== undefined,
500
+ hasData: wrappedResponse.data !== undefined,
501
+ responseType: typeof responseData,
502
+ responseKeys: Object.keys(
503
+ (responseData as Record<string, unknown>) || {}
504
+ ),
505
+ responseData: JSON.stringify(responseData, null, 2).substring(0, 2000), // Increased limit for debugging
506
+ };
507
+ this.config.logger(
508
+ `[AccessControl] Raw response received`,
509
+ rawResponseLog
510
+ );
511
+ // Also log to console.error for visibility (especially for first proof submission errors)
512
+ console.error(
513
+ `[AccessControl] Raw response received:`,
514
+ JSON.stringify(responseData, null, 2)
515
+ );
516
+
517
+ if (wrappedResponse.success !== undefined && wrappedResponse.data) {
518
+ // Response is wrapped in { success, data }
519
+ // Extract data and add success field if missing (for schema validation)
520
+ // CRITICAL: Use JSON.parse(JSON.stringify()) to create a clean object
521
+ // This handles edge cases in Cloudflare Workers where response.json()
522
+ // might return objects with proxy/getter issues that prevent property access
523
+ let dataToValidate: Record<string, unknown>;
524
+
525
+ try {
526
+ // Deep clone via JSON to ensure we have a plain JavaScript object
527
+ // This is the most reliable way to handle potential proxy/getter issues
528
+ const rawData = wrappedResponse.data;
529
+ const clonedData = JSON.parse(JSON.stringify(rawData));
530
+
531
+ if (typeof clonedData !== "object" || clonedData === null) {
532
+ throw new AgentShieldAPIError(
533
+ "invalid_response",
534
+ "Response data is not an object after cloning",
535
+ {
536
+ originalType: typeof rawData,
537
+ clonedType: typeof clonedData,
538
+ clonedValue: clonedData,
539
+ }
540
+ );
541
+ }
542
+
543
+ dataToValidate = clonedData as Record<string, unknown>;
544
+ } catch (cloneError) {
545
+ if (cloneError instanceof AgentShieldAPIError) {
546
+ throw cloneError;
547
+ }
548
+ throw new AgentShieldAPIError(
549
+ "invalid_response",
550
+ "Failed to clone response data",
551
+ {
552
+ error:
553
+ cloneError instanceof Error
554
+ ? cloneError.message
555
+ : String(cloneError),
556
+ dataType: typeof wrappedResponse.data,
557
+ }
558
+ );
559
+ }
560
+
561
+ // CRITICAL: Log the actual data structure for debugging
562
+ console.error(`[AccessControl] 🔍 DATA OBJECT STRUCTURE (after deep clone):`, {
563
+ correlationId,
564
+ dataKeys: Object.keys(dataToValidate),
565
+ hasAccepted: "accepted" in dataToValidate,
566
+ hasRejected: "rejected" in dataToValidate,
567
+ hasOutcomes: "outcomes" in dataToValidate,
568
+ hasErrors: "errors" in dataToValidate,
569
+ acceptedType: typeof dataToValidate.accepted,
570
+ acceptedValue: dataToValidate.accepted,
571
+ rejectedType: typeof dataToValidate.rejected,
572
+ rejectedValue: dataToValidate.rejected,
573
+ outcomesType: typeof dataToValidate.outcomes,
574
+ outcomesValue: dataToValidate.outcomes,
575
+ errorsType: typeof dataToValidate.errors,
576
+ errorsIsArray: Array.isArray(dataToValidate.errors),
577
+ fullData: JSON.stringify(dataToValidate, null, 2),
578
+ });
579
+
580
+ // Ensure success field is present (required by schema)
581
+ // wrappedResponse.success should be true since we checked it exists
582
+ // CRITICAL: Construct from the cloned data to ensure all fields are present
583
+ const dataWithSuccess: Record<string, unknown> = {
584
+ success: wrappedResponse.success === true,
585
+ accepted: dataToValidate.accepted,
586
+ rejected: dataToValidate.rejected,
587
+ };
588
+
589
+ // Add optional fields if present
590
+ if (
591
+ "outcomes" in dataToValidate &&
592
+ dataToValidate.outcomes !== undefined
593
+ ) {
594
+ dataWithSuccess.outcomes = dataToValidate.outcomes;
595
+ }
596
+ if ("errors" in dataToValidate && dataToValidate.errors !== undefined) {
597
+ dataWithSuccess.errors = dataToValidate.errors;
598
+ }
599
+
600
+ // CRITICAL: Log what we're validating
601
+ console.error(`[AccessControl] 🔍 VALIDATING DATA WITH SUCCESS:`, {
602
+ correlationId,
603
+ dataWithSuccessKeys: Object.keys(dataWithSuccess),
604
+ hasSuccess: "success" in dataWithSuccess,
605
+ successValue: dataWithSuccess.success,
606
+ hasAccepted: "accepted" in dataWithSuccess,
607
+ acceptedValue: dataWithSuccess.accepted,
608
+ hasRejected: "rejected" in dataWithSuccess,
609
+ rejectedValue: dataWithSuccess.rejected,
610
+ hasOutcomes: "outcomes" in dataWithSuccess,
611
+ outcomesValue: dataWithSuccess.outcomes,
612
+ fullDataWithSuccess: JSON.stringify(dataWithSuccess, null, 2),
613
+ });
614
+
615
+ // CRITICAL: Ensure all required fields are present before validation
616
+ if (
617
+ typeof dataWithSuccess.accepted !== "number" ||
618
+ typeof dataWithSuccess.rejected !== "number"
619
+ ) {
620
+ console.error(
621
+ `[AccessControl] ❌ MISSING REQUIRED FIELDS AFTER CONSTRUCTION:`,
622
+ {
623
+ correlationId,
624
+ hasAccepted: "accepted" in dataWithSuccess,
625
+ acceptedType: typeof dataWithSuccess.accepted,
626
+ acceptedValue: dataWithSuccess.accepted,
627
+ hasRejected: "rejected" in dataWithSuccess,
628
+ rejectedType: typeof dataWithSuccess.rejected,
629
+ rejectedValue: dataWithSuccess.rejected,
630
+ dataWithSuccessKeys: Object.keys(dataWithSuccess),
631
+ fullDataWithSuccess: JSON.stringify(dataWithSuccess, null, 2),
632
+ dataToValidateKeys: Object.keys(dataToValidate),
633
+ fullDataToValidate: JSON.stringify(dataToValidate, null, 2),
634
+ originalResponseData: JSON.stringify(responseData, null, 2),
635
+ }
636
+ );
637
+ throw new AgentShieldAPIError(
638
+ "invalid_response",
639
+ "Response data missing required fields (accepted/rejected)",
640
+ {
641
+ responseData,
642
+ dataToValidate,
643
+ dataWithSuccess,
644
+ }
645
+ );
646
+ }
647
+
648
+ const dataParsed =
649
+ proofSubmissionResponseSchema.safeParse(dataWithSuccess);
650
+ if (dataParsed.success) {
651
+ this.config.logger(
652
+ `[AccessControl] Proofs submitted successfully (wrapped)`,
653
+ {
654
+ correlationId,
655
+ accepted: dataParsed.data.accepted,
656
+ rejected: dataParsed.data.rejected,
657
+ }
658
+ );
659
+ return dataParsed.data;
660
+ } else {
661
+ // Log validation errors for wrapped response (always log errors)
662
+ const validationErrorLog = {
663
+ correlationId,
664
+ zodErrors: dataParsed.error.errors,
665
+ zodErrorDetails: JSON.stringify(dataParsed.error.errors, null, 2),
666
+ dataToValidate: JSON.stringify(dataToValidate, null, 2).substring(
667
+ 0,
668
+ 2000
669
+ ),
670
+ dataWithSuccess: JSON.stringify(dataWithSuccess, null, 2).substring(
671
+ 0,
672
+ 2000
673
+ ),
674
+ dataKeys: Object.keys(dataToValidate),
675
+ dataWithSuccessKeys: Object.keys(dataWithSuccess),
676
+ originalResponse: JSON.stringify(responseData, null, 2).substring(
677
+ 0,
678
+ 2000
679
+ ),
680
+ };
681
+ this.config.logger(
682
+ `[AccessControl] Wrapped response validation failed`,
683
+ validationErrorLog
684
+ );
685
+ // Also log to console.error for visibility in production
686
+ console.error(
687
+ `[AccessControl] Wrapped response validation failed`,
688
+ validationErrorLog
689
+ );
690
+ console.error(
691
+ `[AccessControl] Original wrapped response:`,
692
+ JSON.stringify(responseData, null, 2)
693
+ );
694
+
695
+ // CRITICAL: Log each zod error individually for easier debugging
696
+ console.error(
697
+ `[AccessControl] ❌ ZOD VALIDATION FAILED - ${dataParsed.error.errors.length} error(s):`
698
+ );
699
+ dataParsed.error.errors.forEach((err, idx) => {
700
+ const errorDetails: Record<string, unknown> = {
701
+ path: err.path.join(".") || "(root)",
702
+ message: err.message,
703
+ code: err.code,
704
+ };
705
+ // Only include properties that exist on specific error types
706
+ if ("received" in err) errorDetails.received = err.received;
707
+ if ("expected" in err) errorDetails.expected = err.expected;
708
+ if ("input" in err) errorDetails.input = err.input;
709
+ console.error(
710
+ `[AccessControl] Error ${idx + 1}:`,
711
+ JSON.stringify(errorDetails, null, 2)
712
+ );
713
+ });
714
+ console.error(
715
+ `[AccessControl] ❌ Full ZOD errors JSON:`,
716
+ JSON.stringify(dataParsed.error.errors, null, 2)
717
+ );
718
+ // CRITICAL: Throw error instead of falling through to direct parsing
719
+ // The response is wrapped, so direct parsing will also fail
720
+ throw new AgentShieldAPIError(
721
+ "invalid_response",
722
+ "Response validation failed",
723
+ { zodErrors: dataParsed.error.errors, responseData }
724
+ );
725
+ }
726
+ }
727
+
728
+ // Try parsing as direct ProofSubmissionResponse
729
+ const parsed = proofSubmissionResponseSchema.safeParse(responseData);
730
+ if (!parsed.success) {
731
+ // Log detailed validation errors (always log errors)
732
+ const validationErrorLog = {
733
+ correlationId,
734
+ zodErrors: parsed.error.errors,
735
+ zodErrorDetails: JSON.stringify(parsed.error.errors, null, 2),
736
+ responseData: JSON.stringify(responseData, null, 2),
737
+ responseDataType: typeof responseData,
738
+ responseKeys: Object.keys(
739
+ (responseData as Record<string, unknown>) || {}
740
+ ),
741
+ httpStatus: httpResponse.status,
742
+ httpStatusText: httpResponse.statusText,
743
+ };
744
+ this.config.logger(
745
+ `[AccessControl] Response validation failed`,
746
+ validationErrorLog
747
+ );
748
+ // CRITICAL: Log to console.error with full details for debugging
749
+ // This format matches test expectations: single call with message and error object
750
+ // This log must include 'Response validation failed' in the message for test compatibility
751
+ console.error(`[AccessControl] Response validation failed`, {
752
+ zodErrors: parsed.error.errors,
753
+ responseData: responseData,
754
+ });
755
+ // Additional detailed logging for debugging
756
+ console.error(
757
+ `[AccessControl] Response validation failed`,
758
+ validationErrorLog
759
+ );
760
+
761
+ // CRITICAL: Log each zod error individually for easier debugging
762
+ console.error(
763
+ `[AccessControl] ❌ ZOD VALIDATION FAILED (direct) - ${parsed.error.errors.length} error(s):`
764
+ );
765
+ parsed.error.errors.forEach((err, idx) => {
766
+ const errorDetails: Record<string, unknown> = {
767
+ path: err.path.join(".") || "(root)",
768
+ message: err.message,
769
+ code: err.code,
770
+ };
771
+ // Only include properties that exist on specific error types
772
+ if ("received" in err) errorDetails.received = err.received;
773
+ if ("expected" in err) errorDetails.expected = err.expected;
774
+ if ("input" in err) errorDetails.input = err.input;
775
+ console.error(`[AccessControl] Error ${idx + 1}:`, errorDetails);
776
+ });
777
+ console.error(
778
+ `[AccessControl] ❌ Full ZOD errors JSON:`,
779
+ JSON.stringify(parsed.error.errors, null, 2)
780
+ );
781
+ console.error(
782
+ `[AccessControl] ❌ ACTUAL RESPONSE DATA:`,
783
+ JSON.stringify(responseData, null, 2)
784
+ );
785
+ throw new AgentShieldAPIError(
786
+ "invalid_response",
787
+ "Response validation failed",
788
+ { zodErrors: parsed.error.errors, responseData }
789
+ );
790
+ }
791
+
792
+ this.config.logger(`[AccessControl] Proofs submitted successfully`, {
793
+ correlationId,
794
+ accepted: parsed.data.accepted,
795
+ rejected: parsed.data.rejected,
796
+ });
797
+
798
+ return parsed.data;
799
+ });
800
+ }
801
+
802
+ /**
803
+ * Get current metrics
804
+ */
805
+ getMetrics(): AccessControlApiServiceMetrics {
806
+ return { ...this.metrics };
807
+ }
808
+
809
+ /**
810
+ * Reset metrics
811
+ */
812
+ resetMetrics(): void {
813
+ this.metrics = {
814
+ successCount: 0,
815
+ errorCount: 0,
816
+ retryCount: 0,
817
+ };
818
+ }
819
+
820
+ /**
821
+ * Retry logic with exponential backoff
822
+ *
823
+ * @internal
824
+ */
825
+ private async retryWithBackoff<T>(
826
+ operation: () => Promise<T>,
827
+ retryCount = 0
828
+ ): Promise<T> {
829
+ try {
830
+ const result = await operation();
831
+ this.metrics.successCount++;
832
+ return result;
833
+ } catch (error: unknown) {
834
+ // Check if error is retryable (5xx status codes)
835
+ const isRetryable = this.isRetryableError(error);
836
+ const { maxRetries, initialDelayMs, maxDelayMs } =
837
+ this.config.retryConfig;
838
+
839
+ if (isRetryable && retryCount < maxRetries) {
840
+ const delay = Math.min(
841
+ initialDelayMs * Math.pow(2, retryCount),
842
+ maxDelayMs
843
+ );
844
+
845
+ this.metrics.retryCount++;
846
+ this.config.logger(
847
+ `Retrying after ${delay}ms (attempt ${retryCount + 1}/${maxRetries})`
848
+ );
849
+
850
+ await this.sleep(delay);
851
+ return this.retryWithBackoff(operation, retryCount + 1);
852
+ }
853
+
854
+ this.metrics.errorCount++;
855
+ throw error;
856
+ }
857
+ }
858
+
859
+ /**
860
+ * Check if an error is retryable (5xx status codes)
861
+ *
862
+ * @internal
863
+ */
864
+ private isRetryableError(error: unknown): boolean {
865
+ // Network errors (fetch failures) are retryable
866
+ if (error instanceof TypeError && error.message.includes("fetch")) {
867
+ return true;
868
+ }
869
+
870
+ // AgentShieldAPIError with 5xx status codes are retryable
871
+ if (error instanceof AgentShieldAPIError) {
872
+ // Check error code for server errors
873
+ if (error.code === "server_error") {
874
+ return true;
875
+ }
876
+
877
+ // Check if error details contain status code
878
+ const status = (error.details as { status?: number } | undefined)?.status;
879
+ if (status && status >= 500 && status < 600) {
880
+ return true;
881
+ }
882
+ // Rate limiting (429) is also retryable
883
+ if (status === 429) {
884
+ return true;
885
+ }
886
+ }
887
+
888
+ // Check for timeout errors
889
+ if (error instanceof Error) {
890
+ const message = error.message.toLowerCase();
891
+ if (message.includes("timeout") || message.includes("timed out")) {
892
+ return true;
893
+ }
894
+ }
895
+
896
+ return false;
897
+ }
898
+
899
+ /**
900
+ * Sleep utility for retry delays
901
+ * Uses platform-agnostic sleep provider
902
+ *
903
+ * @internal
904
+ */
905
+ private sleep(ms: number): Promise<void> {
906
+ return this.config.sleepProvider(ms);
907
+ }
908
+
909
+ /**
910
+ * Parse response text to JSON with error handling
911
+ *
912
+ * @internal
913
+ */
914
+ private parseResponseJSON(response: Response, responseText: string): unknown {
915
+ try {
916
+ return JSON.parse(responseText);
917
+ } catch (error) {
918
+ // Handle non-JSON error responses (e.g., plain text "Internal Server Error")
919
+ if (!response.ok) {
920
+ const errorCode = this.mapStatusToErrorCode(response.status);
921
+ throw new AgentShieldAPIError(
922
+ errorCode,
923
+ `API request failed: ${response.status} ${response.statusText}`,
924
+ {
925
+ status: response.status,
926
+ responseText: responseText.substring(0, 500),
927
+ }
928
+ );
929
+ }
930
+ // For success responses that aren't JSON, throw invalid_response error
931
+ throw new AgentShieldAPIError(
932
+ "invalid_response",
933
+ `Failed to parse response: ${error instanceof Error ? error.message : String(error)}`,
934
+ { responseText: responseText.substring(0, 500) }
935
+ );
936
+ }
937
+ }
938
+
939
+ /**
940
+ * Map HTTP status codes to error codes
941
+ *
942
+ * @internal
943
+ */
944
+ private mapStatusToErrorCode(status: number, statusText = ""): string {
945
+ if (status === 400) {
946
+ return "validation_error";
947
+ } else if (status === 401 || status === 403) {
948
+ return "authentication_failed";
949
+ } else if (status === 404) {
950
+ return "config_not_found";
951
+ } else if (status >= 500) {
952
+ return "server_error";
953
+ }
954
+ return "api_error";
955
+ }
956
+
957
+ /**
958
+ * Handle error responses and throw appropriate AgentShieldAPIError
959
+ *
960
+ * @internal
961
+ */
962
+ private handleErrorResponse(
963
+ response: Response,
964
+ responseData: unknown
965
+ ): never {
966
+ const errorData = responseData as {
967
+ success?: boolean;
968
+ error?: AgentShieldAPIErrorResponse;
969
+ };
970
+
971
+ if (errorData.error) {
972
+ const errorCode = errorData.error.code || "api_error";
973
+ // Ensure error details include status code for retry detection
974
+ const errorDetails = {
975
+ ...(errorData.error.details || {}),
976
+ status: response.status,
977
+ };
978
+ throw new AgentShieldAPIError(
979
+ errorCode,
980
+ errorData.error.message || `API error: ${response.status}`,
981
+ errorDetails
982
+ );
983
+ }
984
+
985
+ // Map status codes to error codes
986
+ const errorCode = this.mapStatusToErrorCode(
987
+ response.status,
988
+ response.statusText
989
+ );
990
+ throw new AgentShieldAPIError(
991
+ errorCode,
992
+ `API request failed: ${response.status} ${response.statusText}`,
993
+ { status: response.status, responseData }
994
+ );
995
+ }
996
+ }
997
+
998
+ /**
999
+ * Compare delegation authorization with current tool protection authorization
1000
+ * Returns true if they match, false otherwise
1001
+ *
1002
+ * @param delegationAuth - Authorization from the delegation credential
1003
+ * @param toolAuth - Authorization required by the tool protection config
1004
+ * @returns true if authorization methods match
1005
+ */
1006
+ export function authorizationMatches(
1007
+ delegationAuth: { type: string; provider?: string; credentialType?: string },
1008
+ toolAuth: { type: string; provider?: string; credentialType?: string } | undefined
1009
+ ): boolean {
1010
+ // No tool auth requirement - allow any delegation
1011
+ if (!toolAuth) return true;
1012
+
1013
+ // ✅ CROSS-TYPE COMPATIBILITY: credential providers can satisfy oauth requirements
1014
+ // When a credential provider (like email/password) is used:
1015
+ // - Delegation is created with: { type: 'credential', credentialType: 'credentials' }
1016
+ // - Tool protection may specify: { type: 'oauth', provider: 'credentials' }
1017
+ // These should be considered equivalent since they represent the same auth method.
1018
+ const isCredentialToOAuthCompatible =
1019
+ delegationAuth.type === "credential" &&
1020
+ toolAuth.type === "oauth" &&
1021
+ delegationAuth.credentialType &&
1022
+ toolAuth.provider &&
1023
+ delegationAuth.credentialType === toolAuth.provider;
1024
+
1025
+ if (isCredentialToOAuthCompatible) {
1026
+ return true;
1027
+ }
1028
+
1029
+ // Compare type (strict match for other cases)
1030
+ if (delegationAuth.type !== toolAuth.type) return false;
1031
+
1032
+ // For OAuth, compare provider (undefined in toolAuth means "any provider is acceptable")
1033
+ if (delegationAuth.type === "oauth") {
1034
+ // If tool doesn't specify a provider, any provider is acceptable
1035
+ if (!toolAuth.provider) return true;
1036
+ return delegationAuth.provider === toolAuth.provider;
1037
+ }
1038
+
1039
+ // For verifiable_credential, compare credentialType
1040
+ if (delegationAuth.type === "verifiable_credential") {
1041
+ // If tool doesn't specify a credential type, any type is acceptable
1042
+ if (!toolAuth.credentialType) return true;
1043
+ return delegationAuth.credentialType === toolAuth.credentialType;
1044
+ }
1045
+
1046
+ // For 'none' type, they match if both are 'none'
1047
+ return true;
1048
+ }