@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,971 @@
1
+ /**
2
+ * ToolProtectionService - Fetches and caches tool protection configurations
3
+ *
4
+ * This service manages tool protection configuration from AgentShield API with
5
+ * efficient caching and automatic synchronization support.
6
+ *
7
+ * C2 (#2916) classification: **product-layer, no DIF equivalent.** This service is
8
+ * config-fetch + precedence-merge + caching + fail-safe plumbing — it resolves
9
+ * *which* ToolProtection config applies to a tool (remote config wins over local,
10
+ * with stale-cache and deny-all fallbacks when the API is unavailable). It does
11
+ * NOT make the allow/deny decision; that lives in the runtime tool-call path
12
+ * (`base.ts`). The DIF `@kya-os/mcp` core owns no remote-config / dashboard-fetch
13
+ * equivalent (its PolicyEngine is an in-memory tool-call decision evaluator — a
14
+ * different layer), so there is nothing to compose from DIF here. Like CORS and
15
+ * the `.well-known` manifests, this module is therefore NOT re-homed onto a DIF
16
+ * primitive; it stays product-side through the decommission. Its precedence,
17
+ * fail-safe (deny-all default), and stale-cache semantics are frozen by
18
+ * `__tests__/services/tool-protection.service.test.ts` and the
19
+ * `tool-protection-{merged-config,oauth-provider,failsafe}.test.ts` suites.
20
+ * Relocating it out of `@kya-os/mcp-i-core` into a surviving package is a C3
21
+ * (#2917, consumer repoint) concern; the breaking wire/DB renames are C4 (#2918).
22
+ *
23
+ * CONFIGURATION PRECEDENCE (highest to lowest):
24
+ * ---------------------------------------------
25
+ * 1. Remote config (AgentShield API) - WINS (source of truth)
26
+ * 2. Local config (localConfig) - Base defaults, overridden by remote
27
+ * 3. Framework defaults
28
+ *
29
+ * OFFLINE FALLBACK (only when API unavailable):
30
+ * ---------------------------------------------
31
+ * 1. Stale cache (if allowStaleCache=true and within maxStaleCacheAge)
32
+ * 2. offlineFallbackConfig (explicit offline-only config)
33
+ * 3. failSafeBehavior (deny-all or allow-all)
34
+ *
35
+ * CORE FUNCTIONALITY:
36
+ * -------------------
37
+ * 1. Fetches tool protection config from AgentShield API (remote wins)
38
+ * 2. Merges with local config (local serves as base defaults)
39
+ * 3. Caches responses with configurable TTL (default 5 minutes)
40
+ * 4. Provides delegation requirement checking before tool execution
41
+ *
42
+ * SYNCHRONIZATION WITH AGENTSHIELD:
43
+ * ----------------------------------
44
+ * When you update tool protection settings in the AgentShield dashboard:
45
+ *
46
+ * 1. Dashboard sends PATCH /api/internal/bouncer/tools/{projectId}/{toolName}
47
+ * 2. AgentShield updates the database immediately (PostgreSQL JSONB column)
48
+ * 3. Dashboard sends POST /admin/clear-cache to this service (automatic)
49
+ * 4. This service clears the cached config from KV storage
50
+ * 5. Next tool call fetches fresh config from AgentShield API
51
+ * 6. New config is cached for the configured TTL period
52
+ *
53
+ * CACHE INVALIDATION:
54
+ * -------------------
55
+ * Cache is invalidated via POST /admin/clear-cache endpoint:
56
+ * - Triggered automatically by AgentShield dashboard when tool protection changes
57
+ * - Can be triggered manually for testing/debugging
58
+ * - Requires API key authentication for security
59
+ *
60
+ * If cache is NOT cleared:
61
+ * - Stale config is served until TTL expires (default 5 minutes)
62
+ * - Configure shorter TTL via TOOL_PROTECTION_CACHE_TTL env var for faster updates
63
+ * - Set to 0 for no cache (not recommended for production)
64
+ *
65
+ * TOOL DISCOVERY PREREQUISITE:
66
+ * ----------------------------
67
+ * IMPORTANT: Tools must be discovered before they can be protected!
68
+ *
69
+ * Discovery happens when:
70
+ * - Agent makes first tool call with proof submission
71
+ * - AgentShield extracts tool info from cryptographic proof
72
+ * - Tool is added to bouncerConfigs.discoveredTools in database
73
+ *
74
+ * If tool not discovered:
75
+ * - Tool won't appear in dashboard
76
+ * - Protection settings can't be configured
77
+ * - GET /config returns empty toolProtection.tools object
78
+ *
79
+ * DEBUGGING:
80
+ * ----------
81
+ * Enable debug logging with:
82
+ * toolProtection: { debug: true }
83
+ *
84
+ * Debug logs show:
85
+ * - Cache hits vs API fetches
86
+ * - Full API responses
87
+ * - Tool protection status for each tool
88
+ * - Cache TTL and expiration times
89
+ * - Source of config data (cache, api, or fallback)
90
+ *
91
+ * TROUBLESHOOTING:
92
+ * ----------------
93
+ * Problem: Dashboard shows protection but tool still executes
94
+ * Cause: Stale cache not invalidated
95
+ * Solution: POST /admin/clear-cache or wait for TTL expiration
96
+ *
97
+ * Problem: Empty toolProtections returned from API
98
+ * Cause: Tool not discovered yet (no proof submissions)
99
+ * Solution: Make at least one tool call to trigger discovery
100
+ *
101
+ * Problem: Updates take 5+ minutes to apply
102
+ * Cause: Long cache TTL and cache clear failed
103
+ * Solution: Configure MCP server URL in AgentShield for auto cache clear
104
+ *
105
+ * @see https://github.com/modelcontextprotocol-identity/agent-shield/docs/bouncer/tool-protection-sync.md
106
+ * @package @kya-os/mcp-i-core
107
+ */
108
+
109
+ import type { ToolProtection, ToolProtectionConfig, ToolProtectionServiceConfig } from "../types/tool-protection.js";
110
+ import type { AuthorizationRequirement } from "@kya-os/contracts/tool-protection";
111
+ import type { ToolProtectionCache } from "../cache/tool-protection-cache.js";
112
+ import { InMemoryToolProtectionCache } from "../cache/tool-protection-cache.js";
113
+
114
+ /**
115
+ * Tool protection data structure in API responses
116
+ */
117
+ interface ToolProtectionData {
118
+ requiresDelegation?: boolean;
119
+ requires_delegation?: boolean;
120
+ requiredScopes?: string[];
121
+ required_scopes?: string[];
122
+ scopes?: string[];
123
+ riskLevel?: string;
124
+ risk_level?: string;
125
+ oauthProvider?: string;
126
+ oauth_provider?: string;
127
+ authorization?: {
128
+ type: string;
129
+ provider?: string;
130
+ issuer?: string;
131
+ credentialType?: string;
132
+ };
133
+ }
134
+
135
+ /**
136
+ * Response from AgentShield API bouncer endpoints
137
+ *
138
+ * Uses the merged config endpoint (/projects/{projectId}/config):
139
+ * { data: { config: { toolProtection: { tools: {...} } } } }
140
+ *
141
+ * Tool protections are embedded at config.toolProtection.tools
142
+ */
143
+ interface BouncerConfigApiResponse {
144
+ success: boolean;
145
+ data: {
146
+ agent_did?: string;
147
+
148
+ // Merged config format - tool protections embedded at config.toolProtection.tools
149
+ config?: {
150
+ toolProtection?: {
151
+ source?: string;
152
+ tools?: Record<string, ToolProtectionData>;
153
+ };
154
+ // Other config fields we don't need to parse
155
+ [key: string]: unknown;
156
+ };
157
+ };
158
+ metadata?: {
159
+ requestId?: string;
160
+ timestamp?: string;
161
+ cachedUntil?: string;
162
+ };
163
+ }
164
+
165
+ /**
166
+ * Service for fetching and checking tool protection configurations
167
+ */
168
+ export class ToolProtectionService {
169
+ private config: ToolProtectionServiceConfig;
170
+ private cache: ToolProtectionCache;
171
+
172
+ constructor(config: ToolProtectionServiceConfig, cache: ToolProtectionCache) {
173
+ this.config = config;
174
+ this.cache = cache;
175
+ }
176
+
177
+ /**
178
+ * Get the project ID from the service configuration
179
+ * @returns Project ID or undefined if not configured
180
+ */
181
+ getProjectId(): string | undefined {
182
+ return this.config.projectId;
183
+ }
184
+
185
+ /**
186
+ * Get stale cache entry if available and within maxStaleCacheAge
187
+ * Only works with InMemoryToolProtectionCache (has internal access to expiresAt)
188
+ *
189
+ * NOTE: This checks stale cache BEFORE calling cache.get() to avoid deletion of expired entries
190
+ *
191
+ * @param cacheKey Cache key to check
192
+ * @returns Stale cache entry or null if not available/too old
193
+ */
194
+ private async getStaleCache(
195
+ cacheKey: string
196
+ ): Promise<ToolProtectionConfig | null> {
197
+ // Only check stale cache if enabled
198
+ if (this.config.allowStaleCache === false) {
199
+ return null;
200
+ }
201
+
202
+ // Only works with InMemoryToolProtectionCache
203
+ if (!(this.cache instanceof InMemoryToolProtectionCache)) {
204
+ return null;
205
+ }
206
+
207
+ // Use public method to get stale cache entry
208
+ const staleConfig = this.cache.getStale(cacheKey);
209
+ if (!staleConfig) {
210
+ return null;
211
+ }
212
+
213
+ // Check if stale cache is within maxStaleCacheAge
214
+ const expiresAt = this.cache.getExpiresAt(cacheKey);
215
+ if (!expiresAt) {
216
+ return null;
217
+ }
218
+
219
+ const now = Date.now();
220
+ const maxStaleAge = this.config.maxStaleCacheAge ?? 86400000; // Default 24 hours
221
+
222
+ // Check if expired but within maxStaleCacheAge
223
+ if (now > expiresAt && now - expiresAt <= maxStaleAge) {
224
+ if (this.config.debug) {
225
+ console.error("[ToolProtectionService] Using stale cache", {
226
+ cacheKey,
227
+ expiredAt: new Date(expiresAt).toISOString(),
228
+ staleAgeMs: now - expiresAt,
229
+ maxStaleAgeMs: maxStaleAge,
230
+ });
231
+ }
232
+ return staleConfig;
233
+ }
234
+
235
+ return null;
236
+ }
237
+
238
+ /**
239
+ * Get tool protection configuration for the agent
240
+ *
241
+ * Flow:
242
+ * 1. Check cache (project-scoped if projectId available)
243
+ * 2. If cache miss, fetch from API
244
+ * 3. If API fails, use fallback config
245
+ * 4. Cache successful API responses
246
+ *
247
+ * @param agentDid DID of the agent to fetch config for
248
+ */
249
+ async getToolProtectionConfig(
250
+ agentDid: string
251
+ ): Promise<ToolProtectionConfig> {
252
+ // Use project-scoped cache key if projectId is available (preferred)
253
+ // Falls back to agent-scoped key for backward compatibility
254
+ // The cache implementation (KVToolProtectionCache) will add any necessary prefix
255
+ const cacheKey = this.config.projectId
256
+ ? `config:tool-protections:${this.config.projectId}`
257
+ : `agent:${agentDid}`;
258
+
259
+ // 1. Check cache
260
+ const cached = await this.cache.get(cacheKey);
261
+ if (cached) {
262
+ const ttl = this.config.cacheTtl ?? 300000;
263
+ const cachedUntil = new Date(Date.now() + ttl).toISOString();
264
+
265
+ if (this.config.debug) {
266
+ console.error("[ToolProtectionService] Cache hit", {
267
+ source: "cache",
268
+ cacheKey,
269
+ agentDid: agentDid.slice(0, 20) + "...",
270
+ projectId: this.config.projectId || "none",
271
+ toolCount: Object.keys(cached.toolProtections).length,
272
+ protectedTools: Object.entries(cached.toolProtections)
273
+ .filter(
274
+ ([_, config]: [string, ToolProtection]) =>
275
+ config.requiresDelegation
276
+ )
277
+ .map(([name]) => name),
278
+ cacheTtlMs: ttl,
279
+ cachedUntil,
280
+ });
281
+ }
282
+ return cached;
283
+ }
284
+
285
+ if (this.config.debug) {
286
+ console.error("[ToolProtectionService] Cache miss, fetching from API", {
287
+ source: "api-fetch-start",
288
+ cacheKey,
289
+ agentDid: agentDid.slice(0, 20) + "...",
290
+ projectId: this.config.projectId || "none",
291
+ apiUrl: this.config.apiUrl,
292
+ endpoint: this.config.projectId
293
+ ? `/api/v1/bouncer/projects/${this.config.projectId}/config`
294
+ : `/api/v1/bouncer/config?agent_did=${agentDid}`,
295
+ });
296
+ }
297
+
298
+ // 3. Fetch from API
299
+ try {
300
+ const response = await this.fetchFromApi(agentDid);
301
+
302
+ if (this.config.debug) {
303
+ console.error("[ToolProtectionService] API response received", {
304
+ source: "api-fetch-complete",
305
+ agentDid: agentDid.slice(0, 20) + "...",
306
+ projectId: this.config.projectId || "none",
307
+ responseKeys: Object.keys(response),
308
+ dataKeys: response.data ? Object.keys(response.data) : [],
309
+ rawConfig: response.data?.config || null,
310
+ rawConfigToolProtection:
311
+ response.data?.config?.toolProtection || null,
312
+ responseMetadata: response.metadata || null,
313
+ });
314
+ }
315
+
316
+ // Transform API response to internal format
317
+ // Uses merged config endpoint: { data: { config: { toolProtection: { tools: {...} } } } }
318
+ const toolProtections: Record<string, ToolProtection> =
319
+ this.parseToolProtectionsFromResponse(response);
320
+
321
+ if (this.config.debug && Object.keys(toolProtections).length > 0) {
322
+ console.error(
323
+ "[ToolProtectionService] Parsed tool protections from merged config",
324
+ {
325
+ toolCount: Object.keys(toolProtections).length,
326
+ tools: Object.keys(toolProtections),
327
+ }
328
+ );
329
+ }
330
+
331
+ // Merge with local config (REMOTE API takes priority over local)
332
+ // Standard precedence: Default < Local < Remote
333
+ // Remote (AgentShield dashboard) is the source of truth and WINS over local config
334
+ const mergedToolProtections: Record<string, ToolProtection> = {};
335
+
336
+ // Step 1: Apply local config as base (if provided)
337
+ if (this.config.localConfig?.toolProtections) {
338
+ for (const [toolName, localConfig] of Object.entries(
339
+ this.config.localConfig.toolProtections
340
+ )) {
341
+ // Skip if localConfig is empty or not a valid ToolProtection object
342
+ // This prevents empty objects from corrupting the merged config
343
+ if (
344
+ !localConfig ||
345
+ typeof localConfig !== "object" ||
346
+ Object.keys(localConfig).length === 0
347
+ ) {
348
+ if (this.config.debug) {
349
+ console.error(
350
+ "[ToolProtectionService] Skipping empty/invalid local config entry",
351
+ { tool: toolName }
352
+ );
353
+ }
354
+ continue;
355
+ }
356
+
357
+ // Ensure requiredScopes exists (default to empty array if missing)
358
+ // Also preserve optional fields like oauthProvider, riskLevel, authorization
359
+ const validConfig: ToolProtection = {
360
+ requiresDelegation:
361
+ (localConfig as ToolProtection).requiresDelegation ?? false,
362
+ requiredScopes:
363
+ (localConfig as ToolProtection).requiredScopes ?? [],
364
+ ...((localConfig as ToolProtection).oauthProvider && {
365
+ oauthProvider: (localConfig as ToolProtection).oauthProvider,
366
+ }),
367
+ ...((localConfig as ToolProtection).riskLevel && {
368
+ riskLevel: (localConfig as ToolProtection).riskLevel,
369
+ }),
370
+ ...((localConfig as ToolProtection).authorization && {
371
+ authorization: (localConfig as ToolProtection).authorization,
372
+ }),
373
+ };
374
+
375
+ mergedToolProtections[toolName] = validConfig;
376
+ if (this.config.debug) {
377
+ console.error(
378
+ "[ToolProtectionService] Applied local config as base",
379
+ {
380
+ tool: toolName,
381
+ localConfig: validConfig,
382
+ }
383
+ );
384
+ }
385
+ }
386
+ }
387
+
388
+ // Step 2: Apply API config (OVERWRITES local config - remote wins)
389
+ for (const [toolName, apiConfig] of Object.entries(toolProtections)) {
390
+ mergedToolProtections[toolName] = apiConfig;
391
+ if (
392
+ this.config.debug &&
393
+ this.config.localConfig?.toolProtections?.[toolName]
394
+ ) {
395
+ console.error(
396
+ "[ToolProtectionService] Remote config overrides local config",
397
+ {
398
+ tool: toolName,
399
+ remoteConfig: apiConfig,
400
+ }
401
+ );
402
+ }
403
+ }
404
+
405
+ const config: ToolProtectionConfig = {
406
+ toolProtections: mergedToolProtections,
407
+ };
408
+
409
+ // 3. Cache the response
410
+ const ttl = this.config.cacheTtl ?? 300000; // Default 5 minutes
411
+ const cacheExpiration = new Date(Date.now() + ttl);
412
+
413
+ await this.cache.set(cacheKey, config, ttl);
414
+
415
+ // Always log tool count and protection status (critical for debugging)
416
+ console.error("[ToolProtectionService] Config loaded from API", {
417
+ source: "api",
418
+ toolCount: Object.keys(mergedToolProtections).length,
419
+ protectedTools: Object.entries(mergedToolProtections)
420
+ .filter(
421
+ ([_, config]: [string, ToolProtection]) => config.requiresDelegation
422
+ )
423
+ .map(([name]) => name),
424
+ agentDid: agentDid.slice(0, 20) + "...",
425
+ projectId: this.config.projectId || "none",
426
+ cacheTtlMs: ttl,
427
+ cacheExpiresAt: cacheExpiration.toISOString(),
428
+ });
429
+
430
+ if (this.config.debug) {
431
+ console.error(
432
+ "[ToolProtectionService] API fetch successful, config cached",
433
+ {
434
+ source: "cache-write",
435
+ agentDid: agentDid.slice(0, 20) + "...",
436
+ cacheKey,
437
+ toolCount: Object.keys(mergedToolProtections).length,
438
+ tools: Object.entries(mergedToolProtections).map(
439
+ ([name, config]) => ({
440
+ name,
441
+ requiresDelegation: config.requiresDelegation,
442
+ scopeCount: (config.requiredScopes || []).length, // Safe access
443
+ })
444
+ ),
445
+ ttlMs: ttl,
446
+ ttlMinutes: Math.round(ttl / 60000),
447
+ expiresAt: cacheExpiration.toISOString(),
448
+ expiresIn: `${Math.round(ttl / 1000)}s`,
449
+ }
450
+ );
451
+ }
452
+
453
+ return config;
454
+ } catch (error) {
455
+ const errorMessage =
456
+ error instanceof Error ? error.message : String(error);
457
+
458
+ // Re-throw API key validation errors (don't fallback)
459
+ if (errorMessage.includes("API key is missing or empty")) {
460
+ throw error;
461
+ }
462
+
463
+ // Re-throw projectId required errors (security fix - don't fallback)
464
+ if (errorMessage.includes("projectId is required")) {
465
+ throw error;
466
+ }
467
+
468
+ // Re-throw HTTP errors (4xx, 5xx) - these indicate API issues, not network failures
469
+ // Exception: 429 (rate limit) should fallback if offline fallback config is available
470
+ if (errorMessage.includes("Failed to fetch bouncer config:")) {
471
+ const status = (error as any).status;
472
+ // Allow 429 to fallback (rate limiting is temporary, fallback is acceptable)
473
+ if (status === 429 && this.config.offlineFallbackConfig) {
474
+ // Will fall through to fallback logic below
475
+ } else {
476
+ throw error;
477
+ }
478
+ }
479
+
480
+ // Re-throw JSON parsing errors
481
+ if (errorMessage.includes("Failed to parse API response:")) {
482
+ throw error;
483
+ }
484
+
485
+ // Re-throw API success: false errors
486
+ if (errorMessage.includes("API returned success: false")) {
487
+ throw error;
488
+ }
489
+
490
+ if (this.config.debug) {
491
+ console.error("[ToolProtectionService] API fetch failed", {
492
+ agentDid: agentDid.slice(0, 20) + "...",
493
+ error: errorMessage,
494
+ });
495
+ }
496
+
497
+ // 4. Fallback to stale cache if available (before fallback config)
498
+ const staleCache = await this.getStaleCache(cacheKey);
499
+ if (staleCache) {
500
+ console.warn(
501
+ "[ToolProtectionService] API fetch failed, using stale cache",
502
+ {
503
+ agentDid: agentDid.slice(0, 20) + "...",
504
+ error: errorMessage,
505
+ cacheKey,
506
+ }
507
+ );
508
+ return staleCache;
509
+ }
510
+
511
+ // 5. Fallback to offline config (only used when API is unavailable)
512
+ // Note: offlineFallbackConfig is separate from localConfig
513
+ // - localConfig: Merged with remote (remote wins), used always
514
+ // - offlineFallbackConfig: Only used when API is completely unavailable
515
+ if (this.config.offlineFallbackConfig) {
516
+ // Always warn when using offline fallback (not just debug mode)
517
+ console.warn(
518
+ "[ToolProtectionService] API fetch failed, using offline fallback config",
519
+ {
520
+ agentDid: agentDid.slice(0, 20) + "...",
521
+ error: errorMessage,
522
+ }
523
+ );
524
+
525
+ // Cache the fallback config to avoid repeated API calls
526
+ const ttl = this.config.cacheTtl ?? 300000; // Default 5 minutes
527
+ await this.cache.set(cacheKey, this.config.offlineFallbackConfig, ttl);
528
+
529
+ return this.config.offlineFallbackConfig;
530
+ }
531
+
532
+ // 6. Fail-safe behavior: deny-all by default (secure)
533
+ // This is the last resort when: API fails AND no stale cache AND no offlineFallbackConfig
534
+ const failSafeBehavior = this.config.failSafeBehavior ?? "deny-all";
535
+
536
+ if (failSafeBehavior === "deny-all") {
537
+ console.error(
538
+ "[ToolProtectionService] API fetch failed, no offline fallback, failing closed (deny-all)",
539
+ {
540
+ agentDid: agentDid.slice(0, 20) + "...",
541
+ error: errorMessage,
542
+ cacheKey,
543
+ }
544
+ );
545
+
546
+ // Create deny-all config (wildcard requires delegation for all tools)
547
+ const denyAllConfig: ToolProtectionConfig = {
548
+ toolProtections: {
549
+ "*": {
550
+ requiresDelegation: true,
551
+ requiredScopes: [],
552
+ },
553
+ },
554
+ };
555
+
556
+ // Cache deny-all config to avoid repeated API calls
557
+ const ttl = this.config.cacheTtl ?? 300000; // Default 5 minutes
558
+ await this.cache.set(cacheKey, denyAllConfig, ttl);
559
+
560
+ return denyAllConfig;
561
+ } else {
562
+ // failSafeBehavior === 'allow-all' (insecure, not recommended)
563
+ console.warn(
564
+ "[ToolProtectionService] API fetch failed, no offline fallback, failing open (allow-all)",
565
+ {
566
+ agentDid: agentDid.slice(0, 20) + "...",
567
+ error: errorMessage,
568
+ cacheKey,
569
+ }
570
+ );
571
+
572
+ // Cache empty config to avoid repeated API calls
573
+ const emptyConfig: ToolProtectionConfig = { toolProtections: {} };
574
+ const ttl = this.config.cacheTtl ?? 300000; // Default 5 minutes
575
+ await this.cache.set(cacheKey, emptyConfig, ttl);
576
+
577
+ return emptyConfig;
578
+ }
579
+ }
580
+ }
581
+
582
+ /**
583
+ * Check if a tool requires delegation
584
+ *
585
+ * @param toolName Name of the tool to check
586
+ * @param agentDid DID of the agent executing the tool
587
+ * @returns Tool protection config or null if no protection required
588
+ */
589
+ async checkToolProtection(
590
+ toolName: string,
591
+ agentDid: string
592
+ ): Promise<ToolProtection | null> {
593
+ const config = await this.getToolProtectionConfig(agentDid);
594
+
595
+ // Check for specific tool protection first
596
+ let protection = config.toolProtections[toolName];
597
+
598
+ // If not found, check for wildcard protection (fail-safe deny-all)
599
+ if (!protection && config.toolProtections["*"]) {
600
+ protection = config.toolProtections["*"];
601
+ }
602
+
603
+ // Always log the check result (critical for debugging)
604
+ if (this.config.debug || !protection || protection.requiresDelegation) {
605
+ console.error("[ToolProtectionService] Protection check", {
606
+ tool: toolName,
607
+ agentDid: agentDid.slice(0, 20) + "...",
608
+ found: !!protection,
609
+ isWildcard: protection === config.toolProtections["*"],
610
+ requiresDelegation: protection?.requiresDelegation ?? false,
611
+ availableTools: Object.keys(config.toolProtections),
612
+ });
613
+ }
614
+
615
+ if (!protection || !protection.requiresDelegation) {
616
+ return null;
617
+ }
618
+
619
+ return protection;
620
+ }
621
+
622
+ /**
623
+ * Fetch tool protection config from AgentShield API
624
+ *
625
+ * Uses the merged /config endpoint which returns tool protections embedded
626
+ * at config.toolProtection.tools. Falls back to legacy formats for backward
627
+ * compatibility.
628
+ *
629
+ * @param agentDid DID of the agent to fetch config for
630
+ * @param options Optional fetch options
631
+ * @param options.bypassCDNCache When true, adds cache-busting to bypass CDN caches (used by clearAndRefresh)
632
+ */
633
+ private async fetchFromApi(
634
+ agentDid: string,
635
+ options?: { bypassCDNCache?: boolean }
636
+ ): Promise<BouncerConfigApiResponse> {
637
+ // Use the merged /config endpoint which includes embedded tool protections
638
+ // This endpoint returns config.toolProtection.tools with all tool rules
639
+ let url: string;
640
+ let useMergedEndpoint = false;
641
+
642
+ // ❌ REMOVED: Legacy agent-scoped endpoint fallback
643
+ // Agent-only scoping causes cross-user delegation leakage (Priority 3 fallback issue)
644
+ // projectId is now REQUIRED for proper user isolation
645
+ if (!this.config.projectId) {
646
+ const error = new Error(
647
+ "[ToolProtectionService] projectId is required for user-scoped delegation. " +
648
+ "Agent-only scoping has been deprecated due to security concerns (cross-user delegation leakage). " +
649
+ "Please configure AGENTSHIELD_PROJECT_ID environment variable."
650
+ );
651
+ console.error("[ToolProtectionService]", error.message);
652
+ throw error;
653
+ }
654
+
655
+ // ✅ PROJECT-SCOPED ENDPOINT: Returns config with embedded toolProtection.tools
656
+ // This endpoint ensures delegations are properly scoped to user+agent
657
+ url = `${this.config.apiUrl}/api/v1/bouncer/projects/${encodeURIComponent(this.config.projectId)}/config`;
658
+ useMergedEndpoint = true;
659
+
660
+ // Add cache-busting query param when bypassing CDN cache
661
+ // This is used during cache invalidation (clearAndRefresh) to ensure we get fresh data
662
+ // from the origin server, not stale CDN-cached data
663
+ if (options?.bypassCDNCache) {
664
+ const separator = url.includes("?") ? "&" : "?";
665
+ url = `${url}${separator}_t=${Date.now()}`;
666
+ }
667
+
668
+ // Debug: Log API key status (masked for security)
669
+ // Format: sk_live... (prefix up to first underscore after type, then ...)
670
+ const apiKeyMasked = this.config.apiKey
671
+ ? (() => {
672
+ const parts = this.config.apiKey.split("_");
673
+ if (parts.length >= 2) {
674
+ return `${parts[0]}_${parts[1]}...`;
675
+ }
676
+ return `${this.config.apiKey.substring(0, 8)}...`;
677
+ })()
678
+ : "(empty)";
679
+ const apiKeyLength = this.config.apiKey?.length || 0;
680
+
681
+ if (this.config.debug) {
682
+ console.error("[ToolProtectionService] Fetching from API:", url, {
683
+ method: useMergedEndpoint
684
+ ? "projects/{projectId}/config (merged)"
685
+ : "config?agent_did (legacy)",
686
+ projectId: this.config.projectId || "none",
687
+ apiKeyPresent: !!this.config.apiKey,
688
+ apiKeyLength,
689
+ apiKeyMasked,
690
+ });
691
+ }
692
+
693
+ // Validate API key is present
694
+ if (!this.config.apiKey || this.config.apiKey.trim() === "") {
695
+ const error = "API key is missing or empty";
696
+ if (this.config.debug) {
697
+ console.error("[ToolProtectionService]", error, {
698
+ apiKeyPresent: !!this.config.apiKey,
699
+ apiKeyLength,
700
+ });
701
+ }
702
+ throw new Error(
703
+ `ToolProtectionService: ${error}. Check AGENTSHIELD_API_KEY in .dev.vars or wrangler.toml [vars]`
704
+ );
705
+ }
706
+
707
+ // Build headers - merged endpoint uses X-API-Key, legacy uses Authorization Bearer
708
+ const headers: Record<string, string> = {
709
+ "Content-Type": "application/json",
710
+ };
711
+
712
+ if (useMergedEndpoint) {
713
+ // ✅ Merged config endpoint headers
714
+ headers["X-API-Key"] = this.config.apiKey;
715
+ if (this.config.projectId) {
716
+ headers["X-Project-Id"] = this.config.projectId;
717
+ }
718
+ } else {
719
+ // ⚠️ Legacy endpoint headers (backward compatibility)
720
+ headers["Authorization"] = `Bearer ${this.config.apiKey}`;
721
+ }
722
+
723
+ // Add cache-control header when bypassing CDN cache
724
+ // This tells any intermediate caches (CDN, proxies) not to serve cached content
725
+ if (options?.bypassCDNCache) {
726
+ headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
727
+ headers["Pragma"] = "no-cache"; // HTTP/1.0 backward compatibility
728
+ }
729
+
730
+ const response = await fetch(url, {
731
+ method: "GET",
732
+ headers,
733
+ });
734
+
735
+ if (!response.ok) {
736
+ const errorText = await response.text().catch(() => "Unknown error");
737
+ const error = new Error(
738
+ `Failed to fetch bouncer config: ${response.status} ${response.statusText} - ${errorText}`
739
+ );
740
+ (error as any).status = response.status;
741
+ throw error;
742
+ }
743
+
744
+ let data: BouncerConfigApiResponse;
745
+ try {
746
+ data = (await response.json()) as BouncerConfigApiResponse;
747
+ } catch (jsonError) {
748
+ throw new Error(
749
+ `Failed to parse API response: ${jsonError instanceof Error ? jsonError.message : String(jsonError)}`
750
+ );
751
+ }
752
+
753
+ if (!data.success) {
754
+ throw new Error("API returned success: false");
755
+ }
756
+
757
+ return data;
758
+ }
759
+
760
+ /**
761
+ * Parse tool protections from API response
762
+ *
763
+ * Extracts tool protection configs from merged config format:
764
+ * { data: { config: { toolProtection: { tools: {...} } } } }
765
+ *
766
+ * @param response API response from AgentShield
767
+ * @returns Record of tool name to ToolProtection
768
+ */
769
+ private parseToolProtectionsFromResponse(
770
+ response: BouncerConfigApiResponse
771
+ ): Record<string, ToolProtection> {
772
+ const toolProtections: Record<string, ToolProtection> = {};
773
+
774
+ // Extract from merged config format: data.config.toolProtection.tools
775
+ const tools = response.data.config?.toolProtection?.tools;
776
+ if (!tools) {
777
+ return toolProtections;
778
+ }
779
+
780
+ for (const [toolName, toolConfig] of Object.entries(tools)) {
781
+ // Support both camelCase and snake_case for backward compatibility with DB data
782
+ const requiresDelegation =
783
+ toolConfig.requiresDelegation ??
784
+ toolConfig.requires_delegation ??
785
+ false;
786
+ const requiredScopes =
787
+ toolConfig.requiredScopes ??
788
+ toolConfig.required_scopes ??
789
+ toolConfig.scopes ??
790
+ [];
791
+ const oauthProvider =
792
+ toolConfig.oauthProvider ?? toolConfig.oauth_provider ?? undefined;
793
+ const rawRiskLevel =
794
+ toolConfig.riskLevel ?? toolConfig.risk_level ?? undefined;
795
+ // Type-safe cast for riskLevel enum
796
+ const riskLevel =
797
+ rawRiskLevel &&
798
+ ["low", "medium", "high", "critical"].includes(rawRiskLevel)
799
+ ? (rawRiskLevel as "low" | "medium" | "high" | "critical")
800
+ : undefined;
801
+ // Cast authorization to proper discriminated union type
802
+ // The API returns the correct shape, we just need to help TypeScript
803
+ const authorization = toolConfig.authorization as
804
+ | AuthorizationRequirement
805
+ | undefined;
806
+
807
+ toolProtections[toolName] = {
808
+ requiresDelegation,
809
+ requiredScopes,
810
+ ...(oauthProvider && { oauthProvider }),
811
+ ...(riskLevel && { riskLevel }),
812
+ ...(authorization && { authorization }),
813
+ };
814
+ }
815
+
816
+ return toolProtections;
817
+ }
818
+
819
+ /**
820
+ * Clear the cache for a project or agent (useful for testing or manual refresh)
821
+ *
822
+ * If projectId is configured, clears project-scoped cache.
823
+ * Otherwise, clears agent-scoped cache.
824
+ *
825
+ * @param agentDid DID of the agent (used for fallback if projectId not available)
826
+ */
827
+ async clearCache(agentDid: string): Promise<void> {
828
+ // Use same cache key strategy as getToolProtectionConfig
829
+ const cacheKey = this.config.projectId
830
+ ? `config:tool-protections:${this.config.projectId}`
831
+ : `agent:${agentDid}`;
832
+
833
+ if (this.config.debug) {
834
+ console.error("[ToolProtectionService] Clearing cache", {
835
+ cacheKey,
836
+ projectId: this.config.projectId || "none",
837
+ agentDid: agentDid.slice(0, 20) + "...",
838
+ });
839
+ }
840
+
841
+ await this.cache.delete(cacheKey);
842
+ }
843
+
844
+ /**
845
+ * Clear cache and immediately fetch fresh config from API
846
+ *
847
+ * This method is designed for Cloudflare Workers where KV has edge caching.
848
+ * After clearing the KV entry, it fetches fresh data from the API and writes
849
+ * it back to KV. This ensures:
850
+ * 1. The global KV entry is deleted
851
+ * 2. Fresh data is fetched from API (with CDN cache bypass!)
852
+ * 3. New data is written to KV (updating edge cache)
853
+ *
854
+ * The next request from the same edge location will get the fresh data.
855
+ *
856
+ * IMPORTANT: This method uses bypassCDNCache to ensure we get fresh data
857
+ * from AgentShield's origin server, not stale CDN-cached data. This is
858
+ * critical for instant cache invalidation when tool protection settings
859
+ * are changed in the AgentShield dashboard.
860
+ *
861
+ * @param agentDid DID of the agent (used for cache key)
862
+ * @returns The fresh tool protection config from API
863
+ */
864
+ async clearAndRefresh(agentDid: string): Promise<{
865
+ config: ToolProtectionConfig;
866
+ cacheKey: string;
867
+ source: "api" | "fallback";
868
+ }> {
869
+ const cacheKey = this.config.projectId
870
+ ? `config:tool-protections:${this.config.projectId}`
871
+ : `agent:${agentDid}`;
872
+
873
+ console.error("[ToolProtectionService] clearAndRefresh starting", {
874
+ cacheKey,
875
+ projectId: this.config.projectId || "none",
876
+ agentDid: agentDid.slice(0, 20) + "...",
877
+ });
878
+
879
+ // 1. Delete the cache entry
880
+ await this.cache.delete(cacheKey);
881
+
882
+ console.error("[ToolProtectionService] Cache entry deleted", { cacheKey });
883
+
884
+ // 2. Fetch fresh config from API with CDN cache bypass
885
+ // This ensures we get fresh data from origin, not stale CDN data
886
+ try {
887
+ const response = await this.fetchFromApi(agentDid, {
888
+ bypassCDNCache: true,
889
+ });
890
+
891
+ // Use shared parsing logic for consistency
892
+ const toolProtections = this.parseToolProtectionsFromResponse(response);
893
+
894
+ // Apply same merge logic as getToolProtectionConfig:
895
+ // Step 1: Apply localConfig as base (if provided)
896
+ // Step 2: Apply API config (OVERWRITES local config - remote wins)
897
+ const mergedToolProtections: Record<string, ToolProtection> = {};
898
+
899
+ // Step 1: Apply local config as base
900
+ if (this.config.localConfig?.toolProtections) {
901
+ for (const [toolName, localConfig] of Object.entries(
902
+ this.config.localConfig.toolProtections
903
+ )) {
904
+ if (
905
+ localConfig &&
906
+ typeof localConfig === "object" &&
907
+ Object.keys(localConfig).length > 0
908
+ ) {
909
+ const validConfig: ToolProtection = {
910
+ requiresDelegation:
911
+ (localConfig as ToolProtection).requiresDelegation ?? false,
912
+ requiredScopes:
913
+ (localConfig as ToolProtection).requiredScopes ?? [],
914
+ ...((localConfig as ToolProtection).oauthProvider && {
915
+ oauthProvider: (localConfig as ToolProtection).oauthProvider,
916
+ }),
917
+ ...((localConfig as ToolProtection).riskLevel && {
918
+ riskLevel: (localConfig as ToolProtection).riskLevel,
919
+ }),
920
+ ...((localConfig as ToolProtection).authorization && {
921
+ authorization: (localConfig as ToolProtection).authorization,
922
+ }),
923
+ };
924
+ mergedToolProtections[toolName] = validConfig;
925
+ }
926
+ }
927
+ }
928
+
929
+ // Step 2: Apply API config (OVERWRITES local config - remote wins)
930
+ for (const [toolName, apiConfig] of Object.entries(toolProtections)) {
931
+ mergedToolProtections[toolName] = apiConfig;
932
+ }
933
+
934
+ // Construct fresh config (ToolProtectionConfig type)
935
+ const freshConfig: ToolProtectionConfig = {
936
+ toolProtections: mergedToolProtections,
937
+ };
938
+
939
+ // 3. Write fresh config to cache
940
+ const ttl = this.config.cacheTtl ?? 300000;
941
+ await this.cache.set(cacheKey, freshConfig, ttl);
942
+
943
+ console.error("[ToolProtectionService] Fresh config fetched and cached", {
944
+ cacheKey,
945
+ toolCount: Object.keys(mergedToolProtections).length,
946
+ protectedTools: Object.entries(mergedToolProtections)
947
+ .filter(([_, cfg]) => cfg.requiresDelegation)
948
+ .map(([name]) => name),
949
+ source: "api",
950
+ });
951
+
952
+ return { config: freshConfig, cacheKey, source: "api" };
953
+ } catch (error) {
954
+ console.warn(
955
+ "[ToolProtectionService] API fetch failed during refresh, using offline fallback",
956
+ {
957
+ error: error instanceof Error ? error.message : String(error),
958
+ cacheKey,
959
+ }
960
+ );
961
+
962
+ // Use offline fallback config if API fails
963
+ const offlineFallback: ToolProtectionConfig = this.config
964
+ .offlineFallbackConfig || {
965
+ toolProtections: {},
966
+ };
967
+
968
+ return { config: offlineFallback, cacheKey, source: "fallback" };
969
+ }
970
+ }
971
+ }