@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,1201 @@
1
+ /**
2
+ * Tool Protection Service Tests
3
+ *
4
+ * Tests for fetching and caching tool protection configurations from AgentShield API
5
+ */
6
+
7
+ import { describe, test, expect, beforeEach, vi, afterEach } from "vitest";
8
+ import { ToolProtectionService } from "../../services/tool-protection.service";
9
+ import {
10
+ InMemoryToolProtectionCache,
11
+ NoOpToolProtectionCache,
12
+ type ToolProtectionCache,
13
+ } from "../../cache/tool-protection-cache";
14
+ import type { ToolProtectionServiceConfig, ToolProtectionConfig } from "../../types/tool-protection";
15
+ import type { ToolProtection } from "@kya-os/contracts/tool-protection";
16
+
17
+ // Mock global fetch
18
+ global.fetch = vi.fn();
19
+
20
+ /**
21
+ * Helper to create mock API response in merged config format
22
+ * The API returns: { data: { config: { toolProtection: { tools: {...} } } } }
23
+ */
24
+ function createMockApiResponse(tools: Record<string, Partial<ToolProtection>>) {
25
+ return {
26
+ success: true,
27
+ data: {
28
+ config: {
29
+ toolProtection: {
30
+ source: "agentshield",
31
+ tools,
32
+ },
33
+ },
34
+ },
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Helper to create mock fetch that returns tools in merged config format
40
+ */
41
+ function mockFetchWithTools(tools: Record<string, Partial<ToolProtection>>) {
42
+ const response = createMockApiResponse(tools);
43
+ (global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
44
+ ok: true,
45
+ json: async () => response,
46
+ text: async () => JSON.stringify(response),
47
+ });
48
+ }
49
+
50
+ describe("ToolProtectionService", () => {
51
+ let service: ToolProtectionService;
52
+ let cache: ToolProtectionCache;
53
+ let config: ToolProtectionServiceConfig;
54
+ const mockAgentDid =
55
+ "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK";
56
+
57
+ beforeEach(() => {
58
+ vi.clearAllMocks();
59
+ cache = new InMemoryToolProtectionCache();
60
+ config = {
61
+ apiUrl: "https://kya.vouched.id",
62
+ apiKey: "test-api-key-12345",
63
+ projectId: "test-project-uuid-12345", // ✅ REQUIRED: projectId is now mandatory for user-scoped delegation
64
+ cacheTtl: 300000, // 5 minutes
65
+ debug: false,
66
+ };
67
+ service = new ToolProtectionService(config, cache);
68
+ });
69
+
70
+ afterEach(() => {
71
+ vi.restoreAllMocks();
72
+ });
73
+
74
+ describe("constructor", () => {
75
+ test("should initialize with config and cache", () => {
76
+ expect(service).toBeDefined();
77
+ expect((service as any).config).toEqual(config);
78
+ expect((service as any).cache).toBe(cache);
79
+ });
80
+ });
81
+
82
+ describe("getToolProtectionConfig", () => {
83
+ describe("cache hit", () => {
84
+ test("should return cached config if available", async () => {
85
+ // projectId is required (set in beforeEach), use project-scoped cache key
86
+ const cachedConfig: ToolProtectionConfig = {
87
+ toolProtections: {
88
+ greet: {
89
+ requiresDelegation: false,
90
+ requiredScopes: [],
91
+ },
92
+ },
93
+ };
94
+
95
+ // Use project-scoped cache key
96
+ const cacheKey = `config:tool-protections:${config.projectId}`;
97
+ await cache.set(cacheKey, cachedConfig, 300000);
98
+
99
+ const result = await service.getToolProtectionConfig(mockAgentDid);
100
+
101
+ expect(result).toEqual(cachedConfig);
102
+ expect(global.fetch).not.toHaveBeenCalled();
103
+ });
104
+
105
+ test("should use project-scoped cache key (projectId is always required)", async () => {
106
+ // projectId is required for all operations
107
+ const cachedConfig: ToolProtectionConfig = {
108
+ toolProtections: {
109
+ greet: {
110
+ requiresDelegation: false,
111
+ requiredScopes: [],
112
+ },
113
+ },
114
+ };
115
+
116
+ const cacheKey = `config:tool-protections:${config.projectId}`;
117
+ await cache.set(cacheKey, cachedConfig, 300000);
118
+
119
+ const result = await service.getToolProtectionConfig(mockAgentDid);
120
+
121
+ expect(result).toEqual(cachedConfig);
122
+ expect(global.fetch).not.toHaveBeenCalled();
123
+ });
124
+
125
+ test("should throw error when projectId is not set (agent-only fallback deprecated)", async () => {
126
+ // ❌ SECURITY FIX: Legacy agent-only fallback has been removed
127
+ // Agent-only scoping causes cross-user delegation leakage (Priority 3 fallback issue)
128
+ // projectId is now REQUIRED for proper user isolation
129
+ const configWithoutProjectId = {
130
+ apiUrl: "https://kya.vouched.id",
131
+ apiKey: "test-api-key-12345",
132
+ cacheTtl: 300000,
133
+ debug: false,
134
+ // Note: projectId is intentionally omitted
135
+ };
136
+ const serviceWithoutProjectId = new ToolProtectionService(
137
+ configWithoutProjectId,
138
+ cache
139
+ );
140
+
141
+ await expect(
142
+ serviceWithoutProjectId.getToolProtectionConfig(mockAgentDid)
143
+ ).rejects.toThrow("projectId is required");
144
+ expect(global.fetch).not.toHaveBeenCalled();
145
+ });
146
+ });
147
+
148
+ describe("API fetch - merged config format", () => {
149
+ test("should fetch from project-scoped /config endpoint when projectId is available", async () => {
150
+ const projectId = "test-project-123";
151
+ config.projectId = projectId;
152
+ service = new ToolProtectionService(config, cache);
153
+
154
+ // Merged config format - tools embedded at config.toolProtection.tools
155
+ const apiResponse = {
156
+ success: true,
157
+ data: {
158
+ config: {
159
+ toolProtection: {
160
+ source: "agentshield",
161
+ tools: {
162
+ checkout: {
163
+ requiresDelegation: true,
164
+ requiredScopes: ["cart:write"],
165
+ },
166
+ search: {
167
+ requiresDelegation: false,
168
+ requiredScopes: [],
169
+ },
170
+ },
171
+ },
172
+ },
173
+ },
174
+ metadata: {
175
+ timestamp: new Date().toISOString(),
176
+ cachedUntil: new Date(Date.now() + 300000).toISOString(),
177
+ },
178
+ };
179
+
180
+ (global.fetch as any).mockResolvedValueOnce({
181
+ ok: true,
182
+ json: async () => apiResponse,
183
+ });
184
+
185
+ const result = await service.getToolProtectionConfig(mockAgentDid);
186
+
187
+ // Now calls /config endpoint (not /tool-protections)
188
+ expect(global.fetch).toHaveBeenCalledWith(
189
+ `https://kya.vouched.id/api/v1/bouncer/projects/${encodeURIComponent(projectId)}/config`,
190
+ expect.objectContaining({
191
+ method: "GET",
192
+ headers: expect.objectContaining({
193
+ "Content-Type": "application/json",
194
+ "X-API-Key": "test-api-key-12345",
195
+ "X-Project-Id": projectId,
196
+ }),
197
+ })
198
+ );
199
+
200
+ expect(result.toolProtections.checkout).toBeDefined();
201
+ expect(result.toolProtections.checkout.requiresDelegation).toBe(true);
202
+ expect(result.toolProtections.checkout.requiredScopes).toEqual([
203
+ "cart:write",
204
+ ]);
205
+ });
206
+
207
+ test("should handle merged config format with snake_case fields", async () => {
208
+ const projectId = "test-project-123";
209
+ config.projectId = projectId;
210
+ service = new ToolProtectionService(config, cache);
211
+
212
+ // Merged config format with snake_case fields (backward compat with DB data)
213
+ const apiResponse = createMockApiResponse({
214
+ protected_tool: {
215
+ requiresDelegation: true,
216
+ requiredScopes: ["scope1", "scope2"],
217
+ },
218
+ unprotected_tool: {
219
+ requiresDelegation: false,
220
+ requiredScopes: [],
221
+ },
222
+ });
223
+
224
+ (global.fetch as any).mockResolvedValueOnce({
225
+ ok: true,
226
+ json: async () => apiResponse,
227
+ });
228
+
229
+ const result = await service.getToolProtectionConfig(mockAgentDid);
230
+
231
+ expect(result.toolProtections.protected_tool.requiresDelegation).toBe(
232
+ true
233
+ );
234
+ expect(result.toolProtections.protected_tool.requiredScopes).toEqual([
235
+ "scope1",
236
+ "scope2",
237
+ ]);
238
+ expect(result.toolProtections.unprotected_tool.requiresDelegation).toBe(
239
+ false
240
+ );
241
+ });
242
+
243
+ test("should parse oauthProvider from merged config format (Phase 2)", async () => {
244
+ const projectId = "test-project-123";
245
+ config.projectId = projectId;
246
+ service = new ToolProtectionService(config, cache);
247
+
248
+ mockFetchWithTools({
249
+ read_repos: {
250
+ requiresDelegation: true,
251
+ requiredScopes: ["repo:read"],
252
+ oauthProvider: "github",
253
+ },
254
+ send_email: {
255
+ requiresDelegation: true,
256
+ requiredScopes: ["gmail:send"],
257
+ oauthProvider: "google",
258
+ },
259
+ });
260
+
261
+ const result = await service.getToolProtectionConfig(mockAgentDid);
262
+
263
+ expect(result.toolProtections.read_repos.oauthProvider).toBe("github");
264
+ expect(result.toolProtections.send_email.oauthProvider).toBe("google");
265
+ });
266
+
267
+ test("should preserve oauthProvider through cache operations", async () => {
268
+ const projectId = "test-project-123";
269
+ config.projectId = projectId;
270
+ service = new ToolProtectionService(config, cache);
271
+
272
+ mockFetchWithTools({
273
+ read_repos: {
274
+ requiresDelegation: true,
275
+ requiredScopes: ["repo:read"],
276
+ oauthProvider: "github",
277
+ },
278
+ });
279
+
280
+ // First call - should fetch and cache
281
+ const result1 = await service.getToolProtectionConfig(mockAgentDid);
282
+ expect(result1.toolProtections.read_repos.oauthProvider).toBe("github");
283
+
284
+ // Second call - should use cache
285
+ const result2 = await service.getToolProtectionConfig(mockAgentDid);
286
+ expect(result2.toolProtections.read_repos.oauthProvider).toBe("github");
287
+ expect(global.fetch).toHaveBeenCalledTimes(1); // Still 1, not 2
288
+ });
289
+ });
290
+
291
+ describe("API fetch - projectId required (legacy agent-scoped deprecated)", () => {
292
+ test("should throw error when projectId is not available (agent-scoped deprecated)", async () => {
293
+ // ❌ SECURITY FIX: Legacy agent-only fallback has been removed
294
+ // Agent-only scoping causes cross-user delegation leakage (Priority 3 fallback issue)
295
+ // projectId is now REQUIRED for proper user isolation
296
+ const configWithoutProjectId = {
297
+ apiUrl: "https://kya.vouched.id",
298
+ apiKey: "test-api-key-12345",
299
+ cacheTtl: 300000,
300
+ debug: false,
301
+ };
302
+ const serviceWithoutProjectId = new ToolProtectionService(
303
+ configWithoutProjectId,
304
+ cache
305
+ );
306
+
307
+ await expect(
308
+ serviceWithoutProjectId.getToolProtectionConfig(mockAgentDid)
309
+ ).rejects.toThrow("projectId is required");
310
+ });
311
+
312
+ test("should use project-scoped endpoint when projectId is set", async () => {
313
+ mockFetchWithTools({
314
+ checkout: {
315
+ requiresDelegation: true,
316
+ requiredScopes: ["cart:write"],
317
+ },
318
+ search: {
319
+ requiresDelegation: false,
320
+ requiredScopes: [],
321
+ },
322
+ });
323
+
324
+ const result = await service.getToolProtectionConfig(mockAgentDid);
325
+
326
+ // Project-scoped endpoint uses X-API-Key and X-Project-Id headers
327
+ expect(global.fetch).toHaveBeenCalledWith(
328
+ `https://kya.vouched.id/api/v1/bouncer/projects/${encodeURIComponent(config.projectId!)}/config`,
329
+ expect.objectContaining({
330
+ method: "GET",
331
+ headers: expect.objectContaining({
332
+ "Content-Type": "application/json",
333
+ "X-API-Key": "test-api-key-12345",
334
+ "X-Project-Id": config.projectId,
335
+ }),
336
+ })
337
+ );
338
+
339
+ expect(result.toolProtections.checkout).toBeDefined();
340
+ expect(result.toolProtections.checkout.requiresDelegation).toBe(true);
341
+ expect(result.toolProtections.checkout.requiredScopes).toEqual([
342
+ "cart:write",
343
+ ]);
344
+ });
345
+
346
+ // NOTE: Legacy format tests (tools array) have been removed.
347
+ // The API only returns merged config format (config.toolProtection.tools).
348
+ // Business logic (snake_case parsing, oauthProvider extraction) is tested
349
+ // in the merged config format tests in tool-protection-oauth-provider.test.ts
350
+
351
+ test("should parse multiple tools from merged config format", async () => {
352
+ // Tests parsing multiple tools from the current API format
353
+ mockFetchWithTools({
354
+ tool1: {
355
+ requiresDelegation: true,
356
+ requiredScopes: ["scope1"],
357
+ },
358
+ tool2: {
359
+ requiresDelegation: false,
360
+ requiredScopes: [],
361
+ },
362
+ });
363
+
364
+ const result = await service.getToolProtectionConfig(mockAgentDid);
365
+
366
+ expect(result.toolProtections.tool1.requiresDelegation).toBe(true);
367
+ expect(result.toolProtections.tool1.requiredScopes).toEqual(["scope1"]);
368
+ expect(result.toolProtections.tool2.requiresDelegation).toBe(false);
369
+ });
370
+
371
+ test("should parse oauthProvider from merged config format", async () => {
372
+ mockFetchWithTools({
373
+ read_repos: {
374
+ requiresDelegation: true,
375
+ requiredScopes: ["repo:read"],
376
+ oauthProvider: "github",
377
+ },
378
+ send_email: {
379
+ requiresDelegation: true,
380
+ requiredScopes: ["gmail:send"],
381
+ oauthProvider: "google",
382
+ },
383
+ });
384
+
385
+ const result = await service.getToolProtectionConfig(mockAgentDid);
386
+
387
+ expect(result.toolProtections.read_repos.oauthProvider).toBe("github");
388
+ expect(result.toolProtections.send_email.oauthProvider).toBe("google");
389
+ });
390
+
391
+ // NOTE: Legacy format tests (tools object, tools array) have been removed.
392
+ // The API only returns merged config format (config.toolProtection.tools).
393
+ // The oauthProvider parsing and snake_case handling is tested in
394
+ // tool-protection-oauth-provider.test.ts using the merged config format.
395
+ });
396
+
397
+ describe("API fetch error handling", () => {
398
+ test("should throw error when API key is missing", async () => {
399
+ config.apiKey = "";
400
+ service = new ToolProtectionService(config, cache);
401
+
402
+ await expect(
403
+ service.getToolProtectionConfig(mockAgentDid)
404
+ ).rejects.toThrow("ToolProtectionService: API key is missing or empty");
405
+ });
406
+
407
+ test("should throw error when API key is whitespace only", async () => {
408
+ config.apiKey = " ";
409
+ service = new ToolProtectionService(config, cache);
410
+
411
+ await expect(
412
+ service.getToolProtectionConfig(mockAgentDid)
413
+ ).rejects.toThrow("ToolProtectionService: API key is missing or empty");
414
+ });
415
+
416
+ test("should throw error when API returns non-OK status", async () => {
417
+ (global.fetch as any).mockResolvedValueOnce({
418
+ ok: false,
419
+ status: 401,
420
+ statusText: "Unauthorized",
421
+ text: async () => "Invalid API key",
422
+ });
423
+
424
+ await expect(
425
+ service.getToolProtectionConfig(mockAgentDid)
426
+ ).rejects.toThrow(
427
+ "Failed to fetch bouncer config: 401 Unauthorized - Invalid API key"
428
+ );
429
+ });
430
+
431
+ test("should throw error when API returns success: false", async () => {
432
+ (global.fetch as any).mockResolvedValueOnce({
433
+ ok: true,
434
+ json: async () => ({
435
+ success: false,
436
+ error: "Invalid request",
437
+ }),
438
+ });
439
+
440
+ await expect(
441
+ service.getToolProtectionConfig(mockAgentDid)
442
+ ).rejects.toThrow("API returned success: false");
443
+ });
444
+
445
+ test("should use offline fallback config when API fails", async () => {
446
+ const offlineFallbackConfig: ToolProtectionConfig = {
447
+ toolProtections: {
448
+ fallback_tool: {
449
+ requiresDelegation: true,
450
+ requiredScopes: ["fallback"],
451
+ },
452
+ },
453
+ };
454
+
455
+ config.offlineFallbackConfig = offlineFallbackConfig;
456
+
457
+ (global.fetch as any).mockRejectedValueOnce(new Error("Network error"));
458
+
459
+ const consoleSpy = vi
460
+ .spyOn(console, "warn")
461
+ .mockImplementation(() => {});
462
+
463
+ const result = await service.getToolProtectionConfig(mockAgentDid);
464
+
465
+ expect(result).toEqual(offlineFallbackConfig);
466
+ expect(consoleSpy).toHaveBeenCalledWith(
467
+ expect.stringContaining(
468
+ "API fetch failed, using offline fallback config"
469
+ ),
470
+ expect.any(Object)
471
+ );
472
+
473
+ consoleSpy.mockRestore();
474
+ });
475
+
476
+ test("should return deny-all config when API fails and no offline fallback (fail-safe)", async () => {
477
+ (global.fetch as any).mockRejectedValueOnce(new Error("Network error"));
478
+
479
+ const consoleSpy = vi
480
+ .spyOn(console, "error")
481
+ .mockImplementation(() => {});
482
+
483
+ const result = await service.getToolProtectionConfig(mockAgentDid);
484
+
485
+ expect(result.toolProtections["*"]).toBeDefined();
486
+ expect(result.toolProtections["*"]?.requiresDelegation).toBe(true);
487
+ expect(consoleSpy).toHaveBeenCalledWith(
488
+ expect.stringContaining(
489
+ "API fetch failed, no offline fallback, failing closed (deny-all)"
490
+ ),
491
+ expect.any(Object)
492
+ );
493
+
494
+ consoleSpy.mockRestore();
495
+ });
496
+
497
+ test("should return allow-all config when failSafeBehavior is allow-all", async () => {
498
+ config.failSafeBehavior = "allow-all";
499
+ service = new ToolProtectionService(config, cache);
500
+
501
+ (global.fetch as any).mockRejectedValueOnce(new Error("Network error"));
502
+
503
+ const consoleSpy = vi
504
+ .spyOn(console, "warn")
505
+ .mockImplementation(() => {});
506
+
507
+ const result = await service.getToolProtectionConfig(mockAgentDid);
508
+
509
+ expect(result).toEqual({ toolProtections: {} });
510
+ expect(consoleSpy).toHaveBeenCalledWith(
511
+ expect.stringContaining(
512
+ "API fetch failed, no offline fallback, failing open (allow-all)"
513
+ ),
514
+ expect.any(Object)
515
+ );
516
+
517
+ consoleSpy.mockRestore();
518
+ });
519
+
520
+ test("should use stale cache when API fails and stale cache is available", async () => {
521
+ config.allowStaleCache = true;
522
+ config.maxStaleCacheAge = 86400000; // 24 hours
523
+ service = new ToolProtectionService(config, cache);
524
+
525
+ // Create a stale cache entry (expired but within maxStaleCacheAge)
526
+ const staleConfig: ToolProtectionConfig = {
527
+ toolProtections: {
528
+ stale_tool: {
529
+ requiresDelegation: true,
530
+ requiredScopes: ["stale"],
531
+ },
532
+ },
533
+ };
534
+
535
+ // Use project-scoped cache key (agent-scoped is deprecated)
536
+ const cacheKey = `config:tool-protections:${config.projectId}`;
537
+ const expiresAt = Date.now() - 10000; // Expired 10 seconds ago
538
+
539
+ // Mock cache.get() to NOT delete expired entries, so stale cache can be checked later
540
+ const originalGet = cache.get.bind(cache);
541
+ vi.spyOn(cache, "get").mockImplementation(async (key: string) => {
542
+ if (key === cacheKey) {
543
+ // Return null (cache miss) but don't delete expired entry
544
+ // The expired entry will be checked by getStaleCache() later
545
+ return null;
546
+ }
547
+ return originalGet(key);
548
+ });
549
+
550
+ // Set stale entry in internal cache
551
+ (cache as any).cache.set(cacheKey, {
552
+ value: staleConfig,
553
+ expiresAt,
554
+ });
555
+
556
+ (global.fetch as any).mockRejectedValueOnce(new Error("Network error"));
557
+
558
+ const consoleSpy = vi
559
+ .spyOn(console, "warn")
560
+ .mockImplementation(() => {});
561
+
562
+ const result = await service.getToolProtectionConfig(mockAgentDid);
563
+
564
+ expect(result).toEqual(staleConfig);
565
+ expect(consoleSpy).toHaveBeenCalledWith(
566
+ expect.stringContaining("API fetch failed, using stale cache"),
567
+ expect.any(Object)
568
+ );
569
+
570
+ consoleSpy.mockRestore();
571
+ vi.restoreAllMocks();
572
+ });
573
+
574
+ test("should not use stale cache if maxStaleCacheAge exceeded", async () => {
575
+ config.allowStaleCache = true;
576
+ config.maxStaleCacheAge = 5000; // 5 seconds
577
+ service = new ToolProtectionService(config, cache);
578
+
579
+ // Create a stale cache entry (expired beyond maxStaleCacheAge)
580
+ const staleConfig: ToolProtectionConfig = {
581
+ toolProtections: {
582
+ stale_tool: {
583
+ requiresDelegation: true,
584
+ requiredScopes: ["stale"],
585
+ },
586
+ },
587
+ };
588
+
589
+ // Use project-scoped cache key (agent-scoped is deprecated)
590
+ const cacheKey = `config:tool-protections:${config.projectId}`;
591
+ const expiresAt = Date.now() - 10000; // Expired 10 seconds ago (exceeds 5s limit)
592
+ (cache as any).cache.set(cacheKey, {
593
+ value: staleConfig,
594
+ expiresAt,
595
+ });
596
+
597
+ (global.fetch as any).mockRejectedValueOnce(new Error("Network error"));
598
+
599
+ const consoleSpy = vi
600
+ .spyOn(console, "error")
601
+ .mockImplementation(() => {});
602
+
603
+ const result = await service.getToolProtectionConfig(mockAgentDid);
604
+
605
+ // Should use deny-all instead of stale cache
606
+ expect(result.toolProtections["*"]).toBeDefined();
607
+ expect(result.toolProtections["*"]?.requiresDelegation).toBe(true);
608
+ expect(consoleSpy).toHaveBeenCalledWith(
609
+ expect.stringContaining("failing closed (deny-all)"),
610
+ expect.any(Object)
611
+ );
612
+
613
+ consoleSpy.mockRestore();
614
+ });
615
+
616
+ test("should not use stale cache if allowStaleCache is false", async () => {
617
+ config.allowStaleCache = false;
618
+ service = new ToolProtectionService(config, cache);
619
+
620
+ // Create a stale cache entry
621
+ const staleConfig: ToolProtectionConfig = {
622
+ toolProtections: {
623
+ stale_tool: {
624
+ requiresDelegation: true,
625
+ requiredScopes: ["stale"],
626
+ },
627
+ },
628
+ };
629
+
630
+ // Use project-scoped cache key (agent-scoped is deprecated)
631
+ const cacheKey = `config:tool-protections:${config.projectId}`;
632
+ const expiresAt = Date.now() - 10000; // Expired 10 seconds ago
633
+ (cache as any).cache.set(cacheKey, {
634
+ value: staleConfig,
635
+ expiresAt,
636
+ });
637
+
638
+ (global.fetch as any).mockRejectedValueOnce(new Error("Network error"));
639
+
640
+ const consoleSpy = vi
641
+ .spyOn(console, "error")
642
+ .mockImplementation(() => {});
643
+
644
+ const result = await service.getToolProtectionConfig(mockAgentDid);
645
+
646
+ // Should use deny-all instead of stale cache
647
+ expect(result.toolProtections["*"]).toBeDefined();
648
+ expect(result.toolProtections["*"]?.requiresDelegation).toBe(true);
649
+
650
+ consoleSpy.mockRestore();
651
+ });
652
+
653
+ test("should prioritize stale cache over offline fallback config", async () => {
654
+ config.allowStaleCache = true;
655
+ config.maxStaleCacheAge = 86400000;
656
+ const offlineFallbackConfig: ToolProtectionConfig = {
657
+ toolProtections: {
658
+ fallback_tool: {
659
+ requiresDelegation: true,
660
+ requiredScopes: ["fallback"],
661
+ },
662
+ },
663
+ };
664
+ config.offlineFallbackConfig = offlineFallbackConfig;
665
+ service = new ToolProtectionService(config, cache);
666
+
667
+ // Create a stale cache entry AFTER cache.get() is called
668
+ // We need to do this by manually setting an expired entry in the internal cache
669
+ // after the cache miss but before API fetch fails
670
+ const staleConfig: ToolProtectionConfig = {
671
+ toolProtections: {
672
+ stale_tool: {
673
+ requiresDelegation: true,
674
+ requiredScopes: ["stale"],
675
+ },
676
+ },
677
+ };
678
+
679
+ // Use project-scoped cache key (agent-scoped is deprecated)
680
+ const cacheKey = `config:tool-protections:${config.projectId}`;
681
+ const expiresAt = Date.now() - 10000; // Expired 10 seconds ago
682
+
683
+ // Mock cache.get() to NOT delete expired entries, so stale cache can be checked later
684
+ const originalGet = cache.get.bind(cache);
685
+ vi.spyOn(cache, "get").mockImplementation(async (key: string) => {
686
+ if (key === cacheKey) {
687
+ // Return null (cache miss) but don't delete expired entry
688
+ // The expired entry will be checked by getStaleCache() later
689
+ return null;
690
+ }
691
+ return originalGet(key);
692
+ });
693
+
694
+ // Set stale entry in internal cache
695
+ (cache as any).cache.set(cacheKey, {
696
+ value: staleConfig,
697
+ expiresAt,
698
+ });
699
+
700
+ (global.fetch as any).mockRejectedValueOnce(new Error("Network error"));
701
+
702
+ const consoleSpy = vi
703
+ .spyOn(console, "warn")
704
+ .mockImplementation(() => {});
705
+
706
+ const result = await service.getToolProtectionConfig(mockAgentDid);
707
+
708
+ // Should use stale cache (higher priority than fallback)
709
+ expect(result).toEqual(staleConfig);
710
+ expect(consoleSpy).toHaveBeenCalledWith(
711
+ expect.stringContaining("API fetch failed, using stale cache"),
712
+ expect.any(Object)
713
+ );
714
+
715
+ consoleSpy.mockRestore();
716
+ vi.restoreAllMocks();
717
+ });
718
+
719
+ test("should handle network errors gracefully", async () => {
720
+ (global.fetch as any).mockRejectedValueOnce(new Error("ECONNREFUSED"));
721
+
722
+ const result = await service.getToolProtectionConfig(mockAgentDid);
723
+
724
+ // Should fail-closed (deny-all) by default
725
+ expect(result.toolProtections["*"]).toBeDefined();
726
+ expect(result.toolProtections["*"]?.requiresDelegation).toBe(true);
727
+ });
728
+
729
+ test("should handle JSON parsing errors", async () => {
730
+ (global.fetch as any).mockResolvedValueOnce({
731
+ ok: true,
732
+ json: async () => {
733
+ throw new Error("Invalid JSON");
734
+ },
735
+ });
736
+
737
+ await expect(
738
+ service.getToolProtectionConfig(mockAgentDid)
739
+ ).rejects.toThrow();
740
+ });
741
+ });
742
+
743
+ describe("caching behavior", () => {
744
+ test("should cache successful API responses", async () => {
745
+ mockFetchWithTools({
746
+ tool1: {
747
+ requiresDelegation: true,
748
+ requiredScopes: ["scope1"],
749
+ },
750
+ });
751
+
752
+ await service.getToolProtectionConfig(mockAgentDid);
753
+
754
+ // Second call should use cache
755
+ const result = await service.getToolProtectionConfig(mockAgentDid);
756
+
757
+ expect(global.fetch).toHaveBeenCalledTimes(1);
758
+ expect(result.toolProtections.tool1).toBeDefined();
759
+ });
760
+
761
+ test("should use default cache TTL when not specified", async () => {
762
+ delete config.cacheTtl;
763
+ service = new ToolProtectionService(config, cache);
764
+
765
+ mockFetchWithTools({});
766
+
767
+ const setSpy = vi.spyOn(cache, "set");
768
+
769
+ await service.getToolProtectionConfig(mockAgentDid);
770
+
771
+ expect(setSpy).toHaveBeenCalledWith(
772
+ expect.any(String),
773
+ expect.any(Object),
774
+ 300000 // Default 5 minutes
775
+ );
776
+ });
777
+
778
+ test("should use custom cache TTL when specified", async () => {
779
+ config.cacheTtl = 600000; // 10 minutes
780
+ service = new ToolProtectionService(config, cache);
781
+
782
+ mockFetchWithTools({});
783
+
784
+ const setSpy = vi.spyOn(cache, "set");
785
+
786
+ await service.getToolProtectionConfig(mockAgentDid);
787
+
788
+ expect(setSpy).toHaveBeenCalledWith(
789
+ expect.any(String),
790
+ expect.any(Object),
791
+ 600000
792
+ );
793
+ });
794
+ });
795
+
796
+ describe("edge cases", () => {
797
+ test("should handle empty tools object", async () => {
798
+ mockFetchWithTools({});
799
+
800
+ const result = await service.getToolProtectionConfig(mockAgentDid);
801
+
802
+ expect(result.toolProtections).toEqual({});
803
+ });
804
+
805
+ test("should handle null requiredScopes", async () => {
806
+ mockFetchWithTools({
807
+ tool1: {
808
+ requiresDelegation: true,
809
+ // Missing requiredScopes - should default to empty array
810
+ },
811
+ });
812
+
813
+ const result = await service.getToolProtectionConfig(mockAgentDid);
814
+
815
+ expect(result.toolProtections.tool1.requiredScopes).toEqual([]);
816
+ });
817
+
818
+ test("should handle mixed camelCase and snake_case in response", async () => {
819
+ // Create response with snake_case fields manually
820
+ const apiResponse = createMockApiResponse({
821
+ tool1: {
822
+ requiresDelegation: true,
823
+ requiredScopes: ["scope1"],
824
+ },
825
+ tool2: {
826
+ requiresDelegation: false,
827
+ requiredScopes: ["scope2"],
828
+ },
829
+ });
830
+ // Add snake_case variants to test priority
831
+ (
832
+ apiResponse.data.config.toolProtection.tools.tool1 as Record<
833
+ string,
834
+ unknown
835
+ >
836
+ ).required_scopes = ["old-scope1"];
837
+ (
838
+ apiResponse.data.config.toolProtection.tools.tool2 as Record<
839
+ string,
840
+ unknown
841
+ >
842
+ ).requires_delegation = true;
843
+
844
+ (global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
845
+ ok: true,
846
+ json: async () => apiResponse,
847
+ text: async () => JSON.stringify(apiResponse),
848
+ });
849
+
850
+ const result = await service.getToolProtectionConfig(mockAgentDid);
851
+
852
+ // camelCase should take priority over snake_case
853
+ expect(result.toolProtections.tool1.requiresDelegation).toBe(true);
854
+ expect(result.toolProtections.tool1.requiredScopes).toEqual(["scope1"]);
855
+ expect(result.toolProtections.tool2.requiresDelegation).toBe(false);
856
+ expect(result.toolProtections.tool2.requiredScopes).toEqual(["scope2"]);
857
+ });
858
+ });
859
+ });
860
+
861
+ describe("checkToolProtection", () => {
862
+ test("should return null when tool has no protection", async () => {
863
+ const apiResponse = {
864
+ success: true,
865
+ data: {
866
+ toolProtections: {
867
+ unprotected_tool: {
868
+ requiresDelegation: false,
869
+ requiredScopes: [],
870
+ },
871
+ },
872
+ },
873
+ metadata: {},
874
+ };
875
+
876
+ (global.fetch as any).mockResolvedValueOnce({
877
+ ok: true,
878
+ json: async () => apiResponse,
879
+ });
880
+
881
+ const protection = await service.checkToolProtection(
882
+ "unprotected_tool",
883
+ mockAgentDid
884
+ );
885
+
886
+ expect(protection).toBeNull();
887
+ });
888
+
889
+ test("should return null when tool is not in config", async () => {
890
+ const apiResponse = {
891
+ success: true,
892
+ data: {
893
+ toolProtections: {
894
+ other_tool: {
895
+ requiresDelegation: true,
896
+ requiredScopes: ["scope1"],
897
+ },
898
+ },
899
+ },
900
+ metadata: {},
901
+ };
902
+
903
+ (global.fetch as any).mockResolvedValueOnce({
904
+ ok: true,
905
+ json: async () => apiResponse,
906
+ });
907
+
908
+ const protection = await service.checkToolProtection(
909
+ "unknown_tool",
910
+ mockAgentDid
911
+ );
912
+
913
+ expect(protection).toBeNull();
914
+ });
915
+
916
+ test("should return wildcard protection when tool not found and wildcard exists", async () => {
917
+ mockFetchWithTools({
918
+ "*": {
919
+ requiresDelegation: true,
920
+ requiredScopes: ["wildcard:scope"],
921
+ },
922
+ specific_tool: {
923
+ requiresDelegation: false,
924
+ requiredScopes: [],
925
+ },
926
+ });
927
+
928
+ const protection = await service.checkToolProtection(
929
+ "unknown_tool",
930
+ mockAgentDid
931
+ );
932
+
933
+ expect(protection).toBeDefined();
934
+ expect(protection?.requiresDelegation).toBe(true);
935
+ expect(protection?.requiredScopes).toEqual(["wildcard:scope"]);
936
+ });
937
+
938
+ test("should prioritize specific tool protection over wildcard", async () => {
939
+ mockFetchWithTools({
940
+ "*": {
941
+ requiresDelegation: true,
942
+ requiredScopes: ["wildcard:scope"],
943
+ },
944
+ specific_tool: {
945
+ requiresDelegation: false,
946
+ requiredScopes: [],
947
+ },
948
+ });
949
+
950
+ const protection = await service.checkToolProtection(
951
+ "specific_tool",
952
+ mockAgentDid
953
+ );
954
+
955
+ // Should use specific tool (no delegation required), not wildcard
956
+ expect(protection).toBeNull();
957
+ });
958
+
959
+ test("should use wildcard protection in fail-safe deny-all mode", async () => {
960
+ // Simulate fail-safe mode: API fails, no fallback, returns deny-all config
961
+ (global.fetch as any).mockRejectedValueOnce(new Error("Network error"));
962
+
963
+ const protection = await service.checkToolProtection(
964
+ "any_tool",
965
+ mockAgentDid
966
+ );
967
+
968
+ // Should return wildcard protection from deny-all config
969
+ expect(protection).toBeDefined();
970
+ expect(protection?.requiresDelegation).toBe(true);
971
+ expect(protection?.requiredScopes).toEqual([]);
972
+ });
973
+
974
+ test("should return protection config when tool requires delegation", async () => {
975
+ mockFetchWithTools({
976
+ protected_tool: {
977
+ requiresDelegation: true,
978
+ requiredScopes: ["scope1", "scope2"],
979
+ },
980
+ });
981
+
982
+ const protection = await service.checkToolProtection(
983
+ "protected_tool",
984
+ mockAgentDid
985
+ );
986
+
987
+ expect(protection).toBeDefined();
988
+ expect(protection?.requiresDelegation).toBe(true);
989
+ expect(protection?.requiredScopes).toEqual(["scope1", "scope2"]);
990
+ });
991
+
992
+ test("should log protection check when debug is enabled", async () => {
993
+ config.debug = true;
994
+ service = new ToolProtectionService(config, cache);
995
+
996
+ mockFetchWithTools({
997
+ tool1: {
998
+ requiresDelegation: true,
999
+ requiredScopes: ["scope1"],
1000
+ },
1001
+ });
1002
+
1003
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
1004
+
1005
+ await service.checkToolProtection("tool1", mockAgentDid);
1006
+
1007
+ expect(consoleSpy).toHaveBeenCalledWith(
1008
+ expect.stringContaining("Protection check"),
1009
+ expect.any(Object)
1010
+ );
1011
+
1012
+ consoleSpy.mockRestore();
1013
+ });
1014
+
1015
+ test("should log protection check when delegation is required", async () => {
1016
+ mockFetchWithTools({
1017
+ tool1: {
1018
+ requiresDelegation: true,
1019
+ requiredScopes: ["scope1"],
1020
+ },
1021
+ });
1022
+
1023
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
1024
+
1025
+ await service.checkToolProtection("tool1", mockAgentDid);
1026
+
1027
+ expect(consoleSpy).toHaveBeenCalledWith(
1028
+ expect.stringContaining("Protection check"),
1029
+ expect.any(Object)
1030
+ );
1031
+
1032
+ consoleSpy.mockRestore();
1033
+ });
1034
+ });
1035
+
1036
+ describe("clearCache", () => {
1037
+ test("should clear project-scoped cache when projectId is set", async () => {
1038
+ const projectId = "test-project-123";
1039
+ config.projectId = projectId;
1040
+ service = new ToolProtectionService(config, cache);
1041
+
1042
+ const deleteSpy = vi.spyOn(cache, "delete");
1043
+
1044
+ await service.clearCache(mockAgentDid);
1045
+
1046
+ expect(deleteSpy).toHaveBeenCalledWith(
1047
+ `config:tool-protections:${projectId}`
1048
+ );
1049
+ });
1050
+
1051
+ test("should clear project-scoped cache (projectId is always set)", async () => {
1052
+ // ❌ SECURITY FIX: Legacy agent-only fallback has been removed
1053
+ // Service always requires projectId now, so clearCache uses project-scoped key
1054
+ const deleteSpy = vi.spyOn(cache, "delete");
1055
+
1056
+ await service.clearCache(mockAgentDid);
1057
+
1058
+ // Uses project-scoped key since projectId is required
1059
+ expect(deleteSpy).toHaveBeenCalledWith(
1060
+ `config:tool-protections:${config.projectId}`
1061
+ );
1062
+ });
1063
+
1064
+ test("should log cache clear when debug is enabled", async () => {
1065
+ config.debug = true;
1066
+ service = new ToolProtectionService(config, cache);
1067
+
1068
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
1069
+
1070
+ await service.clearCache(mockAgentDid);
1071
+
1072
+ expect(consoleSpy).toHaveBeenCalledWith(
1073
+ expect.stringContaining("Clearing cache"),
1074
+ expect.any(Object)
1075
+ );
1076
+
1077
+ consoleSpy.mockRestore();
1078
+ });
1079
+ });
1080
+
1081
+ describe("integration with NoOpToolProtectionCache", () => {
1082
+ test("should work with NoOpToolProtectionCache", async () => {
1083
+ const noOpCache = new NoOpToolProtectionCache();
1084
+ service = new ToolProtectionService(config, noOpCache);
1085
+
1086
+ const apiResponse = createMockApiResponse({
1087
+ tool1: {
1088
+ requiresDelegation: true,
1089
+ requiredScopes: ["scope1"],
1090
+ },
1091
+ });
1092
+
1093
+ (global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
1094
+ ok: true,
1095
+ json: async () => apiResponse,
1096
+ text: async () => JSON.stringify(apiResponse),
1097
+ });
1098
+
1099
+ // First call - should fetch from API
1100
+ const result1 = await service.getToolProtectionConfig(mockAgentDid);
1101
+
1102
+ // Second call - should fetch again (no cache)
1103
+ const result2 = await service.getToolProtectionConfig(mockAgentDid);
1104
+
1105
+ expect(result1).toEqual(result2);
1106
+ expect(global.fetch).toHaveBeenCalledTimes(2);
1107
+ });
1108
+ });
1109
+
1110
+ describe("debug logging", () => {
1111
+ test("should log cache hits when debug is enabled", async () => {
1112
+ config.debug = true;
1113
+ service = new ToolProtectionService(config, cache);
1114
+
1115
+ const cachedConfig: ToolProtectionConfig = {
1116
+ toolProtections: {
1117
+ tool1: {
1118
+ requiresDelegation: false,
1119
+ requiredScopes: [],
1120
+ },
1121
+ },
1122
+ };
1123
+
1124
+ // Use project-scoped cache key (agent-scoped is deprecated)
1125
+ const cacheKey = `config:tool-protections:${config.projectId}`;
1126
+ await cache.set(cacheKey, cachedConfig, 300000);
1127
+
1128
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
1129
+
1130
+ await service.getToolProtectionConfig(mockAgentDid);
1131
+
1132
+ expect(consoleSpy).toHaveBeenCalledWith(
1133
+ expect.stringContaining("Cache hit"),
1134
+ expect.any(Object)
1135
+ );
1136
+
1137
+ consoleSpy.mockRestore();
1138
+ });
1139
+
1140
+ test("should log cache misses when debug is enabled", async () => {
1141
+ config.debug = true;
1142
+ service = new ToolProtectionService(config, cache);
1143
+
1144
+ mockFetchWithTools({});
1145
+
1146
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
1147
+
1148
+ await service.getToolProtectionConfig(mockAgentDid);
1149
+
1150
+ expect(consoleSpy).toHaveBeenCalledWith(
1151
+ expect.stringContaining("Cache miss"),
1152
+ expect.any(Object)
1153
+ );
1154
+
1155
+ consoleSpy.mockRestore();
1156
+ });
1157
+
1158
+ test("should log API fetch details when debug is enabled", async () => {
1159
+ config.debug = true;
1160
+ config.projectId = "test-project";
1161
+ service = new ToolProtectionService(config, cache);
1162
+
1163
+ mockFetchWithTools({});
1164
+
1165
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
1166
+
1167
+ await service.getToolProtectionConfig(mockAgentDid);
1168
+
1169
+ expect(consoleSpy).toHaveBeenCalledWith(
1170
+ expect.stringContaining("Fetching from API"),
1171
+ expect.any(String),
1172
+ expect.any(Object)
1173
+ );
1174
+
1175
+ consoleSpy.mockRestore();
1176
+ });
1177
+
1178
+ test("should log config loaded when API fetch succeeds", async () => {
1179
+ mockFetchWithTools({
1180
+ tool1: {
1181
+ requiresDelegation: true,
1182
+ requiredScopes: ["scope1"],
1183
+ },
1184
+ });
1185
+
1186
+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
1187
+
1188
+ await service.getToolProtectionConfig(mockAgentDid);
1189
+
1190
+ expect(consoleSpy).toHaveBeenCalledWith(
1191
+ expect.stringContaining("Config loaded"),
1192
+ expect.objectContaining({
1193
+ toolCount: 1,
1194
+ protectedTools: ["tool1"],
1195
+ })
1196
+ );
1197
+
1198
+ consoleSpy.mockRestore();
1199
+ });
1200
+ });
1201
+ });