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