@kya-os/mcp-i-core 1.2.3-canary.6 → 1.3.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 (231) hide show
  1. package/.claude/settings.local.json +9 -0
  2. package/.turbo/turbo-build.log +4 -0
  3. package/.turbo/turbo-test$colon$coverage.log +4514 -0
  4. package/.turbo/turbo-test.log +2973 -0
  5. package/COMPLIANCE_IMPROVEMENT_REPORT.md +483 -0
  6. package/Composer 3.md +615 -0
  7. package/GPT-5.md +1169 -0
  8. package/OPUS-plan.md +352 -0
  9. package/PHASE_3_AND_4.1_SUMMARY.md +585 -0
  10. package/PHASE_3_SUMMARY.md +317 -0
  11. package/PHASE_4.1.3_SUMMARY.md +428 -0
  12. package/PHASE_4.1_COMPLETE.md +525 -0
  13. package/PHASE_4_USER_DID_IDENTITY_LINKING_PLAN.md +1240 -0
  14. package/SCHEMA_COMPLIANCE_REPORT.md +275 -0
  15. package/TEST_PLAN.md +571 -0
  16. package/coverage/coverage-final.json +57 -0
  17. package/dist/__tests__/utils/mock-providers.d.ts +1 -2
  18. package/dist/__tests__/utils/mock-providers.d.ts.map +1 -1
  19. package/dist/__tests__/utils/mock-providers.js.map +1 -1
  20. package/dist/cache/oauth-config-cache.d.ts +69 -0
  21. package/dist/cache/oauth-config-cache.d.ts.map +1 -0
  22. package/dist/cache/oauth-config-cache.js +76 -0
  23. package/dist/cache/oauth-config-cache.js.map +1 -0
  24. package/dist/identity/idp-token-resolver.d.ts +53 -0
  25. package/dist/identity/idp-token-resolver.d.ts.map +1 -0
  26. package/dist/identity/idp-token-resolver.js +108 -0
  27. package/dist/identity/idp-token-resolver.js.map +1 -0
  28. package/dist/identity/idp-token-storage.interface.d.ts +42 -0
  29. package/dist/identity/idp-token-storage.interface.d.ts.map +1 -0
  30. package/dist/identity/idp-token-storage.interface.js +12 -0
  31. package/dist/identity/idp-token-storage.interface.js.map +1 -0
  32. package/dist/identity/user-did-manager.d.ts +39 -1
  33. package/dist/identity/user-did-manager.d.ts.map +1 -1
  34. package/dist/identity/user-did-manager.js +69 -3
  35. package/dist/identity/user-did-manager.js.map +1 -1
  36. package/dist/index.d.ts +22 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +39 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/runtime/audit-logger.d.ts +37 -0
  41. package/dist/runtime/audit-logger.d.ts.map +1 -0
  42. package/dist/runtime/audit-logger.js +9 -0
  43. package/dist/runtime/audit-logger.js.map +1 -0
  44. package/dist/runtime/base.d.ts +58 -2
  45. package/dist/runtime/base.d.ts.map +1 -1
  46. package/dist/runtime/base.js +266 -11
  47. package/dist/runtime/base.js.map +1 -1
  48. package/dist/services/access-control.service.d.ts.map +1 -1
  49. package/dist/services/access-control.service.js +200 -35
  50. package/dist/services/access-control.service.js.map +1 -1
  51. package/dist/services/authorization/authorization-registry.d.ts +29 -0
  52. package/dist/services/authorization/authorization-registry.d.ts.map +1 -0
  53. package/dist/services/authorization/authorization-registry.js +57 -0
  54. package/dist/services/authorization/authorization-registry.js.map +1 -0
  55. package/dist/services/authorization/types.d.ts +53 -0
  56. package/dist/services/authorization/types.d.ts.map +1 -0
  57. package/dist/services/authorization/types.js +10 -0
  58. package/dist/services/authorization/types.js.map +1 -0
  59. package/dist/services/batch-delegation.service.d.ts +53 -0
  60. package/dist/services/batch-delegation.service.d.ts.map +1 -0
  61. package/dist/services/batch-delegation.service.js +95 -0
  62. package/dist/services/batch-delegation.service.js.map +1 -0
  63. package/dist/services/oauth-config.service.d.ts +53 -0
  64. package/dist/services/oauth-config.service.d.ts.map +1 -0
  65. package/dist/services/oauth-config.service.js +117 -0
  66. package/dist/services/oauth-config.service.js.map +1 -0
  67. package/dist/services/oauth-provider-registry.d.ts +77 -0
  68. package/dist/services/oauth-provider-registry.d.ts.map +1 -0
  69. package/dist/services/oauth-provider-registry.js +112 -0
  70. package/dist/services/oauth-provider-registry.js.map +1 -0
  71. package/dist/services/oauth-service.d.ts +77 -0
  72. package/dist/services/oauth-service.d.ts.map +1 -0
  73. package/dist/services/oauth-service.js +348 -0
  74. package/dist/services/oauth-service.js.map +1 -0
  75. package/dist/services/oauth-token-retrieval.service.d.ts +49 -0
  76. package/dist/services/oauth-token-retrieval.service.d.ts.map +1 -0
  77. package/dist/services/oauth-token-retrieval.service.js +150 -0
  78. package/dist/services/oauth-token-retrieval.service.js.map +1 -0
  79. package/dist/services/provider-resolver.d.ts +48 -0
  80. package/dist/services/provider-resolver.d.ts.map +1 -0
  81. package/dist/services/provider-resolver.js +120 -0
  82. package/dist/services/provider-resolver.js.map +1 -0
  83. package/dist/services/provider-validator.d.ts +55 -0
  84. package/dist/services/provider-validator.d.ts.map +1 -0
  85. package/dist/services/provider-validator.js +135 -0
  86. package/dist/services/provider-validator.js.map +1 -0
  87. package/dist/services/tool-context-builder.d.ts +57 -0
  88. package/dist/services/tool-context-builder.d.ts.map +1 -0
  89. package/dist/services/tool-context-builder.js +125 -0
  90. package/dist/services/tool-context-builder.js.map +1 -0
  91. package/dist/services/tool-protection.service.d.ts +87 -10
  92. package/dist/services/tool-protection.service.d.ts.map +1 -1
  93. package/dist/services/tool-protection.service.js +282 -112
  94. package/dist/services/tool-protection.service.js.map +1 -1
  95. package/dist/types/oauth-required-error.d.ts +40 -0
  96. package/dist/types/oauth-required-error.d.ts.map +1 -0
  97. package/dist/types/oauth-required-error.js +40 -0
  98. package/dist/types/oauth-required-error.js.map +1 -0
  99. package/dist/utils/did-helpers.d.ts +33 -0
  100. package/dist/utils/did-helpers.d.ts.map +1 -1
  101. package/dist/utils/did-helpers.js +40 -0
  102. package/dist/utils/did-helpers.js.map +1 -1
  103. package/dist/utils/index.d.ts +1 -0
  104. package/dist/utils/index.d.ts.map +1 -1
  105. package/dist/utils/index.js +1 -0
  106. package/dist/utils/index.js.map +1 -1
  107. package/docs/API_REFERENCE.md +1362 -0
  108. package/docs/COMPLIANCE_MATRIX.md +691 -0
  109. package/docs/STATUSLIST2021_GUIDE.md +696 -0
  110. package/docs/W3C_VC_DELEGATION_GUIDE.md +710 -0
  111. package/package.json +24 -50
  112. package/scripts/audit-compliance.ts +724 -0
  113. package/src/__tests__/cache/tool-protection-cache.test.ts +640 -0
  114. package/src/__tests__/config/provider-runtime-config.test.ts +309 -0
  115. package/src/__tests__/delegation-e2e.test.ts +690 -0
  116. package/src/__tests__/identity/user-did-manager.test.ts +213 -0
  117. package/src/__tests__/index.test.ts +56 -0
  118. package/src/__tests__/integration/full-flow.test.ts +776 -0
  119. package/src/__tests__/integration.test.ts +281 -0
  120. package/src/__tests__/providers/base.test.ts +173 -0
  121. package/src/__tests__/providers/memory.test.ts +319 -0
  122. package/src/__tests__/regression/phase2-regression.test.ts +427 -0
  123. package/src/__tests__/runtime/audit-logger.test.ts +154 -0
  124. package/src/__tests__/runtime/base-extensions.test.ts +593 -0
  125. package/src/__tests__/runtime/base.test.ts +869 -0
  126. package/src/__tests__/runtime/delegation-flow.test.ts +164 -0
  127. package/src/__tests__/runtime/proof-client-did.test.ts +375 -0
  128. package/src/__tests__/runtime/route-interception.test.ts +686 -0
  129. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +908 -0
  130. package/src/__tests__/services/agentshield-integration.test.ts +784 -0
  131. package/src/__tests__/services/provider-resolver-edge-cases.test.ts +487 -0
  132. package/src/__tests__/services/tool-protection-oauth-provider.test.ts +480 -0
  133. package/src/__tests__/services/tool-protection.service.test.ts +1366 -0
  134. package/src/__tests__/utils/mock-providers.ts +340 -0
  135. package/src/cache/oauth-config-cache.d.ts +69 -0
  136. package/src/cache/oauth-config-cache.d.ts.map +1 -0
  137. package/src/cache/oauth-config-cache.js +71 -0
  138. package/src/cache/oauth-config-cache.js.map +1 -0
  139. package/src/cache/oauth-config-cache.ts +123 -0
  140. package/src/cache/tool-protection-cache.ts +171 -0
  141. package/src/compliance/EXAMPLE.md +412 -0
  142. package/src/compliance/__tests__/schema-verifier.test.ts +797 -0
  143. package/src/compliance/index.ts +8 -0
  144. package/src/compliance/schema-registry.ts +460 -0
  145. package/src/compliance/schema-verifier.ts +708 -0
  146. package/src/config/__tests__/remote-config.spec.ts +268 -0
  147. package/src/config/remote-config.ts +174 -0
  148. package/src/config.ts +309 -0
  149. package/src/delegation/__tests__/audience-validator.test.ts +112 -0
  150. package/src/delegation/__tests__/bitstring.test.ts +346 -0
  151. package/src/delegation/__tests__/cascading-revocation.test.ts +628 -0
  152. package/src/delegation/__tests__/delegation-graph.test.ts +584 -0
  153. package/src/delegation/__tests__/utils.test.ts +152 -0
  154. package/src/delegation/__tests__/vc-issuer.test.ts +442 -0
  155. package/src/delegation/__tests__/vc-verifier.test.ts +922 -0
  156. package/src/delegation/audience-validator.ts +52 -0
  157. package/src/delegation/bitstring.ts +278 -0
  158. package/src/delegation/cascading-revocation.ts +370 -0
  159. package/src/delegation/delegation-graph.ts +299 -0
  160. package/src/delegation/index.ts +14 -0
  161. package/src/delegation/statuslist-manager.ts +353 -0
  162. package/src/delegation/storage/__tests__/memory-graph-storage.test.ts +366 -0
  163. package/src/delegation/storage/__tests__/memory-statuslist-storage.test.ts +228 -0
  164. package/src/delegation/storage/index.ts +9 -0
  165. package/src/delegation/storage/memory-graph-storage.ts +178 -0
  166. package/src/delegation/storage/memory-statuslist-storage.ts +77 -0
  167. package/src/delegation/utils.ts +42 -0
  168. package/src/delegation/vc-issuer.ts +232 -0
  169. package/src/delegation/vc-verifier.ts +568 -0
  170. package/src/identity/idp-token-resolver.ts +147 -0
  171. package/src/identity/idp-token-storage.interface.ts +59 -0
  172. package/src/identity/user-did-manager.ts +370 -0
  173. package/src/index.ts +260 -0
  174. package/src/providers/base.d.ts +91 -0
  175. package/src/providers/base.d.ts.map +1 -0
  176. package/src/providers/base.js +38 -0
  177. package/src/providers/base.js.map +1 -0
  178. package/src/providers/base.ts +96 -0
  179. package/src/providers/memory.ts +142 -0
  180. package/src/runtime/audit-logger.ts +39 -0
  181. package/src/runtime/base.ts +1329 -0
  182. package/src/services/__tests__/access-control.integration.test.ts +443 -0
  183. package/src/services/__tests__/access-control.proof-response-validation.test.ts +578 -0
  184. package/src/services/__tests__/access-control.service.test.ts +970 -0
  185. package/src/services/__tests__/batch-delegation.service.test.ts +351 -0
  186. package/src/services/__tests__/crypto.service.test.ts +531 -0
  187. package/src/services/__tests__/oauth-provider-registry.test.ts +142 -0
  188. package/src/services/__tests__/proof-verifier.integration.test.ts +485 -0
  189. package/src/services/__tests__/proof-verifier.test.ts +489 -0
  190. package/src/services/__tests__/provider-resolution.integration.test.ts +198 -0
  191. package/src/services/__tests__/provider-resolver.test.ts +217 -0
  192. package/src/services/__tests__/storage.service.test.ts +358 -0
  193. package/src/services/access-control.service.ts +990 -0
  194. package/src/services/authorization/authorization-registry.ts +66 -0
  195. package/src/services/authorization/types.ts +71 -0
  196. package/src/services/batch-delegation.service.ts +137 -0
  197. package/src/services/crypto.service.ts +302 -0
  198. package/src/services/errors.ts +76 -0
  199. package/src/services/index.ts +9 -0
  200. package/src/services/oauth-config.service.d.ts +53 -0
  201. package/src/services/oauth-config.service.d.ts.map +1 -0
  202. package/src/services/oauth-config.service.js +113 -0
  203. package/src/services/oauth-config.service.js.map +1 -0
  204. package/src/services/oauth-config.service.ts +166 -0
  205. package/src/services/oauth-provider-registry.d.ts +57 -0
  206. package/src/services/oauth-provider-registry.d.ts.map +1 -0
  207. package/src/services/oauth-provider-registry.js +73 -0
  208. package/src/services/oauth-provider-registry.js.map +1 -0
  209. package/src/services/oauth-provider-registry.ts +123 -0
  210. package/src/services/oauth-service.ts +510 -0
  211. package/src/services/oauth-token-retrieval.service.ts +245 -0
  212. package/src/services/proof-verifier.ts +478 -0
  213. package/src/services/provider-resolver.d.ts +48 -0
  214. package/src/services/provider-resolver.d.ts.map +1 -0
  215. package/src/services/provider-resolver.js +106 -0
  216. package/src/services/provider-resolver.js.map +1 -0
  217. package/src/services/provider-resolver.ts +144 -0
  218. package/src/services/provider-validator.ts +170 -0
  219. package/src/services/storage.service.ts +566 -0
  220. package/src/services/tool-context-builder.ts +172 -0
  221. package/src/services/tool-protection.service.ts +958 -0
  222. package/src/types/oauth-required-error.ts +63 -0
  223. package/src/types/tool-protection.ts +155 -0
  224. package/src/utils/__tests__/did-helpers.test.ts +101 -0
  225. package/src/utils/base64.ts +148 -0
  226. package/src/utils/cors.ts +83 -0
  227. package/src/utils/did-helpers.ts +150 -0
  228. package/src/utils/index.ts +8 -0
  229. package/src/utils/storage-keys.ts +278 -0
  230. package/tsconfig.json +21 -0
  231. package/vitest.config.ts +56 -0
@@ -0,0 +1,784 @@
1
+ /**
2
+ * AgentShield Integration Tests
3
+ *
4
+ * Tests for AgentShield API integration including:
5
+ * - Tool protection config fetching
6
+ * - API authentication
7
+ * - Error handling
8
+ * - Response format compatibility
9
+ */
10
+
11
+ import { describe, test, expect, beforeEach, vi, afterEach } from 'vitest';
12
+ import { ToolProtectionService } from '../../services/tool-protection.service';
13
+ import { InMemoryToolProtectionCache } from '../../cache/tool-protection-cache';
14
+ import type { ToolProtectionServiceConfig } from '../../types/tool-protection';
15
+
16
+ // Mock global fetch
17
+ global.fetch = vi.fn();
18
+
19
+ describe('AgentShield Integration', () => {
20
+ let service: ToolProtectionService;
21
+ let cache: InMemoryToolProtectionCache;
22
+ let config: ToolProtectionServiceConfig;
23
+ const mockAgentDid = 'did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK';
24
+ const baseUrl = 'https://kya.vouched.id';
25
+
26
+ beforeEach(() => {
27
+ vi.clearAllMocks();
28
+ cache = new InMemoryToolProtectionCache();
29
+ config = {
30
+ apiUrl: baseUrl,
31
+ apiKey: 'test-api-key-12345',
32
+ projectId: 'test-project-123',
33
+ cacheTtl: 300000,
34
+ debug: false,
35
+ };
36
+ service = new ToolProtectionService(config, cache);
37
+ });
38
+
39
+ afterEach(() => {
40
+ vi.restoreAllMocks();
41
+ });
42
+
43
+ describe('API Authentication', () => {
44
+ test('should use X-API-Key header for new endpoint', async () => {
45
+ const apiResponse = {
46
+ success: true,
47
+ data: {
48
+ toolProtections: {},
49
+ },
50
+ metadata: {},
51
+ };
52
+
53
+ (global.fetch as any).mockResolvedValueOnce({
54
+ ok: true,
55
+ json: async () => apiResponse,
56
+ });
57
+
58
+ await service.getToolProtectionConfig(mockAgentDid);
59
+
60
+ expect(global.fetch).toHaveBeenCalledWith(
61
+ expect.any(String),
62
+ expect.objectContaining({
63
+ headers: expect.objectContaining({
64
+ 'X-API-Key': 'test-api-key-12345',
65
+ 'X-Project-Id': 'test-project-123',
66
+ }),
67
+ })
68
+ );
69
+ });
70
+
71
+ test('should use Authorization Bearer header for old endpoint', async () => {
72
+ delete config.projectId;
73
+ service = new ToolProtectionService(config, cache);
74
+
75
+ const apiResponse = {
76
+ success: true,
77
+ data: {
78
+ tools: [],
79
+ },
80
+ metadata: {},
81
+ };
82
+
83
+ (global.fetch as any).mockResolvedValueOnce({
84
+ ok: true,
85
+ json: async () => apiResponse,
86
+ });
87
+
88
+ await service.getToolProtectionConfig(mockAgentDid);
89
+
90
+ expect(global.fetch).toHaveBeenCalledWith(
91
+ expect.any(String),
92
+ expect.objectContaining({
93
+ headers: expect.objectContaining({
94
+ Authorization: 'Bearer test-api-key-12345',
95
+ }),
96
+ })
97
+ );
98
+ });
99
+
100
+ test('should reject requests without API key', async () => {
101
+ config.apiKey = '';
102
+ service = new ToolProtectionService(config, cache);
103
+
104
+ await expect(service.getToolProtectionConfig(mockAgentDid)).rejects.toThrow(
105
+ 'API key is missing or empty'
106
+ );
107
+ });
108
+
109
+ test('should mask API key in debug logs', async () => {
110
+ config.debug = true;
111
+ config.apiKey = 'sk_live_1234567890abcdef';
112
+ service = new ToolProtectionService(config, cache);
113
+
114
+ const apiResponse = {
115
+ success: true,
116
+ data: {
117
+ toolProtections: {},
118
+ },
119
+ metadata: {},
120
+ };
121
+
122
+ (global.fetch as any).mockResolvedValueOnce({
123
+ ok: true,
124
+ json: async () => apiResponse,
125
+ });
126
+
127
+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
128
+
129
+ await service.getToolProtectionConfig(mockAgentDid);
130
+
131
+ const logCalls = consoleSpy.mock.calls;
132
+ const debugLog = logCalls.find((call) =>
133
+ call[0].includes('Fetching from API')
134
+ );
135
+
136
+ if (debugLog && debugLog[2]) {
137
+ const logData = debugLog[2] as any;
138
+ expect(logData.apiKeyMasked).toMatch(/^sk_live\.\.\./);
139
+ expect(logData.apiKeyMasked).not.toContain('1234567890abcdef');
140
+ }
141
+
142
+ consoleSpy.mockRestore();
143
+ });
144
+ });
145
+
146
+ describe('Endpoint Selection', () => {
147
+ test('should use project-scoped endpoint when projectId is available', async () => {
148
+ const apiResponse = {
149
+ success: true,
150
+ data: {
151
+ toolProtections: {},
152
+ },
153
+ metadata: {},
154
+ };
155
+
156
+ (global.fetch as any).mockResolvedValueOnce({
157
+ ok: true,
158
+ json: async () => apiResponse,
159
+ });
160
+
161
+ await service.getToolProtectionConfig(mockAgentDid);
162
+
163
+ expect(global.fetch).toHaveBeenCalledWith(
164
+ `${baseUrl}/api/v1/bouncer/projects/test-project-123/tool-protections`,
165
+ expect.any(Object)
166
+ );
167
+ });
168
+
169
+ test('should use agent-scoped endpoint when projectId is not available', async () => {
170
+ delete config.projectId;
171
+ service = new ToolProtectionService(config, cache);
172
+
173
+ const apiResponse = {
174
+ success: true,
175
+ data: {
176
+ tools: [],
177
+ },
178
+ metadata: {},
179
+ };
180
+
181
+ (global.fetch as any).mockResolvedValueOnce({
182
+ ok: true,
183
+ json: async () => apiResponse,
184
+ });
185
+
186
+ await service.getToolProtectionConfig(mockAgentDid);
187
+
188
+ expect(global.fetch).toHaveBeenCalledWith(
189
+ `${baseUrl}/api/v1/bouncer/config?agent_did=${encodeURIComponent(mockAgentDid)}`,
190
+ expect.any(Object)
191
+ );
192
+ });
193
+
194
+ test('should encode projectId in URL', async () => {
195
+ config.projectId = 'project/with/special-chars';
196
+ service = new ToolProtectionService(config, cache);
197
+
198
+ const apiResponse = {
199
+ success: true,
200
+ data: {
201
+ toolProtections: {},
202
+ },
203
+ metadata: {},
204
+ };
205
+
206
+ (global.fetch as any).mockResolvedValueOnce({
207
+ ok: true,
208
+ json: async () => apiResponse,
209
+ });
210
+
211
+ await service.getToolProtectionConfig(mockAgentDid);
212
+
213
+ expect(global.fetch).toHaveBeenCalledWith(
214
+ expect.stringContaining(encodeURIComponent('project/with/special-chars')),
215
+ expect.any(Object)
216
+ );
217
+ });
218
+
219
+ test('should encode agent DID in URL', async () => {
220
+ delete config.projectId;
221
+ service = new ToolProtectionService(config, cache);
222
+
223
+ const apiResponse = {
224
+ success: true,
225
+ data: {
226
+ tools: [],
227
+ },
228
+ metadata: {},
229
+ };
230
+
231
+ (global.fetch as any).mockResolvedValueOnce({
232
+ ok: true,
233
+ json: async () => apiResponse,
234
+ });
235
+
236
+ await service.getToolProtectionConfig(mockAgentDid);
237
+
238
+ expect(global.fetch).toHaveBeenCalledWith(
239
+ expect.stringContaining(encodeURIComponent(mockAgentDid)),
240
+ expect.any(Object)
241
+ );
242
+ });
243
+ });
244
+
245
+ describe('Response Format Compatibility', () => {
246
+ test('should handle new endpoint format (toolProtections object)', async () => {
247
+ const apiResponse = {
248
+ success: true,
249
+ data: {
250
+ toolProtections: {
251
+ checkout: {
252
+ requiresDelegation: true,
253
+ requiredScopes: ['cart:write'],
254
+ },
255
+ search: {
256
+ requiresDelegation: false,
257
+ requiredScopes: [],
258
+ },
259
+ },
260
+ },
261
+ metadata: {
262
+ timestamp: new Date().toISOString(),
263
+ cachedUntil: new Date(Date.now() + 300000).toISOString(),
264
+ },
265
+ };
266
+
267
+ (global.fetch as any).mockResolvedValueOnce({
268
+ ok: true,
269
+ json: async () => apiResponse,
270
+ });
271
+
272
+ const result = await service.getToolProtectionConfig(mockAgentDid);
273
+
274
+ expect(result.toolProtections.checkout).toBeDefined();
275
+ expect(result.toolProtections.checkout.requiresDelegation).toBe(true);
276
+ expect(result.toolProtections.search.requiresDelegation).toBe(false);
277
+ });
278
+
279
+ test('should handle old endpoint format (tools array)', async () => {
280
+ delete config.projectId;
281
+ service = new ToolProtectionService(config, cache);
282
+
283
+ const apiResponse = {
284
+ success: true,
285
+ data: {
286
+ tools: [
287
+ {
288
+ name: 'checkout',
289
+ requiresDelegation: true,
290
+ scopes: ['cart:write'],
291
+ },
292
+ {
293
+ name: 'search',
294
+ requiresDelegation: false,
295
+ scopes: [],
296
+ },
297
+ ],
298
+ },
299
+ metadata: {},
300
+ };
301
+
302
+ (global.fetch as any).mockResolvedValueOnce({
303
+ ok: true,
304
+ json: async () => apiResponse,
305
+ });
306
+
307
+ const result = await service.getToolProtectionConfig(mockAgentDid);
308
+
309
+ expect(result.toolProtections.checkout).toBeDefined();
310
+ expect(result.toolProtections.checkout.requiresDelegation).toBe(true);
311
+ expect(result.toolProtections.search.requiresDelegation).toBe(false);
312
+ });
313
+
314
+ test('should handle old endpoint format (tools object)', async () => {
315
+ delete config.projectId;
316
+ service = new ToolProtectionService(config, cache);
317
+
318
+ const apiResponse = {
319
+ success: true,
320
+ data: {
321
+ tools: {
322
+ checkout: {
323
+ requiresDelegation: true,
324
+ scopes: ['cart:write'],
325
+ },
326
+ search: {
327
+ requiresDelegation: false,
328
+ scopes: [],
329
+ },
330
+ },
331
+ },
332
+ metadata: {},
333
+ };
334
+
335
+ (global.fetch as any).mockResolvedValueOnce({
336
+ ok: true,
337
+ json: async () => apiResponse,
338
+ });
339
+
340
+ const result = await service.getToolProtectionConfig(mockAgentDid);
341
+
342
+ expect(result.toolProtections.checkout).toBeDefined();
343
+ expect(result.toolProtections.checkout.requiresDelegation).toBe(true);
344
+ expect(result.toolProtections.search.requiresDelegation).toBe(false);
345
+ });
346
+
347
+ test('should handle snake_case field names', async () => {
348
+ const apiResponse = {
349
+ success: true,
350
+ data: {
351
+ toolProtections: {
352
+ tool1: {
353
+ requires_delegation: true,
354
+ required_scopes: ['scope1', 'scope2'],
355
+ },
356
+ },
357
+ },
358
+ metadata: {},
359
+ };
360
+
361
+ (global.fetch as any).mockResolvedValueOnce({
362
+ ok: true,
363
+ json: async () => apiResponse,
364
+ });
365
+
366
+ const result = await service.getToolProtectionConfig(mockAgentDid);
367
+
368
+ expect(result.toolProtections.tool1.requiresDelegation).toBe(true);
369
+ expect(result.toolProtections.tool1.requiredScopes).toEqual(['scope1', 'scope2']);
370
+ });
371
+
372
+ test('should handle camelCase field names', async () => {
373
+ const apiResponse = {
374
+ success: true,
375
+ data: {
376
+ toolProtections: {
377
+ tool1: {
378
+ requiresDelegation: true,
379
+ requiredScopes: ['scope1', 'scope2'],
380
+ },
381
+ },
382
+ },
383
+ metadata: {},
384
+ };
385
+
386
+ (global.fetch as any).mockResolvedValueOnce({
387
+ ok: true,
388
+ json: async () => apiResponse,
389
+ });
390
+
391
+ const result = await service.getToolProtectionConfig(mockAgentDid);
392
+
393
+ expect(result.toolProtections.tool1.requiresDelegation).toBe(true);
394
+ expect(result.toolProtections.tool1.requiredScopes).toEqual(['scope1', 'scope2']);
395
+ });
396
+
397
+ test('should prefer camelCase over snake_case when both present', async () => {
398
+ const apiResponse = {
399
+ success: true,
400
+ data: {
401
+ toolProtections: {
402
+ tool1: {
403
+ requires_delegation: false,
404
+ requiresDelegation: true,
405
+ required_scopes: ['old'],
406
+ requiredScopes: ['new'],
407
+ },
408
+ },
409
+ },
410
+ metadata: {},
411
+ };
412
+
413
+ (global.fetch as any).mockResolvedValueOnce({
414
+ ok: true,
415
+ json: async () => apiResponse,
416
+ });
417
+
418
+ const result = await service.getToolProtectionConfig(mockAgentDid);
419
+
420
+ expect(result.toolProtections.tool1.requiresDelegation).toBe(true);
421
+ expect(result.toolProtections.tool1.requiredScopes).toEqual(['new']);
422
+ });
423
+ });
424
+
425
+ describe('Error Handling', () => {
426
+ test('should handle 401 Unauthorized', async () => {
427
+ (global.fetch as any).mockResolvedValueOnce({
428
+ ok: false,
429
+ status: 401,
430
+ statusText: 'Unauthorized',
431
+ text: async () => 'Invalid API key',
432
+ });
433
+
434
+ await expect(service.getToolProtectionConfig(mockAgentDid)).rejects.toThrow(
435
+ 'Failed to fetch bouncer config: 401 Unauthorized'
436
+ );
437
+ });
438
+
439
+ test('should handle 403 Forbidden', async () => {
440
+ (global.fetch as any).mockResolvedValueOnce({
441
+ ok: false,
442
+ status: 403,
443
+ statusText: 'Forbidden',
444
+ text: async () => 'Access denied',
445
+ });
446
+
447
+ await expect(service.getToolProtectionConfig(mockAgentDid)).rejects.toThrow(
448
+ 'Failed to fetch bouncer config: 403 Forbidden'
449
+ );
450
+ });
451
+
452
+ test('should handle 404 Not Found', async () => {
453
+ (global.fetch as any).mockResolvedValueOnce({
454
+ ok: false,
455
+ status: 404,
456
+ statusText: 'Not Found',
457
+ text: async () => 'Project not found',
458
+ });
459
+
460
+ await expect(service.getToolProtectionConfig(mockAgentDid)).rejects.toThrow(
461
+ 'Failed to fetch bouncer config: 404 Not Found'
462
+ );
463
+ });
464
+
465
+ test('should handle 500 Internal Server Error', async () => {
466
+ (global.fetch as any).mockResolvedValueOnce({
467
+ ok: false,
468
+ status: 500,
469
+ statusText: 'Internal Server Error',
470
+ text: async () => 'Server error',
471
+ });
472
+
473
+ await expect(service.getToolProtectionConfig(mockAgentDid)).rejects.toThrow(
474
+ 'Failed to fetch bouncer config: 500 Internal Server Error'
475
+ );
476
+ });
477
+
478
+ test('should handle network timeout', async () => {
479
+ (global.fetch as any).mockRejectedValueOnce(new Error('Network timeout'));
480
+
481
+ const fallbackConfig = {
482
+ toolProtections: {
483
+ fallback: {
484
+ requiresDelegation: true,
485
+ requiredScopes: ['fallback'],
486
+ },
487
+ },
488
+ };
489
+
490
+ config.fallbackConfig = fallbackConfig;
491
+ service = new ToolProtectionService(config, cache);
492
+
493
+ const result = await service.getToolProtectionConfig(mockAgentDid);
494
+
495
+ expect(result).toEqual(fallbackConfig);
496
+ });
497
+
498
+ test('should handle malformed JSON response', async () => {
499
+ (global.fetch as any).mockResolvedValueOnce({
500
+ ok: true,
501
+ json: async () => {
502
+ throw new Error('Unexpected token');
503
+ },
504
+ });
505
+
506
+ await expect(service.getToolProtectionConfig(mockAgentDid)).rejects.toThrow();
507
+ });
508
+
509
+ test('should handle response with success: false', async () => {
510
+ (global.fetch as any).mockResolvedValueOnce({
511
+ ok: true,
512
+ json: async () => ({
513
+ success: false,
514
+ error: {
515
+ code: 'INVALID_REQUEST',
516
+ message: 'Invalid project ID',
517
+ },
518
+ }),
519
+ });
520
+
521
+ await expect(service.getToolProtectionConfig(mockAgentDid)).rejects.toThrow(
522
+ 'API returned success: false'
523
+ );
524
+ });
525
+
526
+ test('should handle empty response body', async () => {
527
+ (global.fetch as any).mockResolvedValueOnce({
528
+ ok: false,
529
+ status: 500,
530
+ statusText: 'Internal Server Error',
531
+ text: async () => '',
532
+ });
533
+
534
+ await expect(service.getToolProtectionConfig(mockAgentDid)).rejects.toThrow(
535
+ 'Failed to fetch bouncer config: 500 Internal Server Error - '
536
+ );
537
+ });
538
+ });
539
+
540
+ describe('Fallback Behavior', () => {
541
+ test('should use fallback config when API is unavailable', async () => {
542
+ const fallbackConfig = {
543
+ toolProtections: {
544
+ fallback_tool: {
545
+ requiresDelegation: true,
546
+ requiredScopes: ['fallback'],
547
+ },
548
+ },
549
+ };
550
+
551
+ config.fallbackConfig = fallbackConfig;
552
+ service = new ToolProtectionService(config, cache);
553
+
554
+ (global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
555
+
556
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
557
+
558
+ const result = await service.getToolProtectionConfig(mockAgentDid);
559
+
560
+ expect(result).toEqual(fallbackConfig);
561
+ expect(consoleSpy).toHaveBeenCalledWith(
562
+ expect.stringContaining('using fallback config'),
563
+ expect.any(Object)
564
+ );
565
+
566
+ consoleSpy.mockRestore();
567
+ });
568
+
569
+ test('should return deny-all config when no fallback is available (fail-safe)', async () => {
570
+ (global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
571
+
572
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
573
+
574
+ const result = await service.getToolProtectionConfig(mockAgentDid);
575
+
576
+ expect(result.toolProtections['*']).toBeDefined();
577
+ expect(result.toolProtections['*']?.requiresDelegation).toBe(true);
578
+ expect(consoleSpy).toHaveBeenCalledWith(
579
+ expect.stringContaining('API fetch failed, no fallback, failing closed (deny-all)'),
580
+ expect.any(Object)
581
+ );
582
+
583
+ consoleSpy.mockRestore();
584
+ });
585
+
586
+ test('should cache fallback config', async () => {
587
+ const fallbackConfig = {
588
+ toolProtections: {
589
+ fallback_tool: {
590
+ requiresDelegation: true,
591
+ requiredScopes: ['fallback'],
592
+ },
593
+ },
594
+ };
595
+
596
+ config.fallbackConfig = fallbackConfig;
597
+ service = new ToolProtectionService(config, cache);
598
+
599
+ (global.fetch as any).mockRejectedValue(new Error('Network error'));
600
+
601
+ // First call - should use fallback
602
+ const result1 = await service.getToolProtectionConfig(mockAgentDid);
603
+
604
+ // Second call - should use cached fallback (no API call)
605
+ const result2 = await service.getToolProtectionConfig(mockAgentDid);
606
+
607
+ expect(result1).toEqual(result2);
608
+ expect(result1).toEqual(fallbackConfig);
609
+ // Should only attempt API call once (both calls use cached fallback)
610
+ expect(global.fetch).toHaveBeenCalledTimes(1);
611
+ });
612
+ });
613
+
614
+ describe('Caching Integration', () => {
615
+ test('should cache successful API responses', async () => {
616
+ const apiResponse = {
617
+ success: true,
618
+ data: {
619
+ toolProtections: {
620
+ tool1: {
621
+ requiresDelegation: true,
622
+ requiredScopes: ['scope1'],
623
+ },
624
+ },
625
+ },
626
+ metadata: {},
627
+ };
628
+
629
+ (global.fetch as any).mockResolvedValueOnce({
630
+ ok: true,
631
+ json: async () => apiResponse,
632
+ });
633
+
634
+ // First call - should fetch from API
635
+ await service.getToolProtectionConfig(mockAgentDid);
636
+
637
+ // Second call - should use cache
638
+ const result = await service.getToolProtectionConfig(mockAgentDid);
639
+
640
+ expect(global.fetch).toHaveBeenCalledTimes(1);
641
+ expect(result.toolProtections.tool1).toBeDefined();
642
+ });
643
+
644
+ test('should respect cache TTL', async () => {
645
+ config.cacheTtl = 1000; // 1 second
646
+ service = new ToolProtectionService(config, cache);
647
+
648
+ const apiResponse = {
649
+ success: true,
650
+ data: {
651
+ toolProtections: {},
652
+ },
653
+ metadata: {},
654
+ };
655
+
656
+ (global.fetch as any).mockResolvedValueOnce({
657
+ ok: true,
658
+ json: async () => apiResponse,
659
+ });
660
+
661
+ await service.getToolProtectionConfig(mockAgentDid);
662
+
663
+ // Wait for cache to expire
664
+ await new Promise((resolve) => setTimeout(resolve, 1100));
665
+
666
+ (global.fetch as any).mockResolvedValueOnce({
667
+ ok: true,
668
+ json: async () => apiResponse,
669
+ });
670
+
671
+ await service.getToolProtectionConfig(mockAgentDid);
672
+
673
+ expect(global.fetch).toHaveBeenCalledTimes(2);
674
+ });
675
+ });
676
+
677
+ describe('Real-world Scenarios', () => {
678
+ test('should handle typical e-commerce tool protection config', async () => {
679
+ const apiResponse = {
680
+ success: true,
681
+ data: {
682
+ toolProtections: {
683
+ search_products: {
684
+ requiresDelegation: false,
685
+ requiredScopes: [],
686
+ },
687
+ add_to_cart: {
688
+ requiresDelegation: true,
689
+ requiredScopes: ['cart:write'],
690
+ },
691
+ checkout: {
692
+ requiresDelegation: true,
693
+ requiredScopes: ['cart:write', 'payment:process'],
694
+ },
695
+ view_order: {
696
+ requiresDelegation: false,
697
+ requiredScopes: [],
698
+ },
699
+ },
700
+ },
701
+ metadata: {
702
+ timestamp: new Date().toISOString(),
703
+ cachedUntil: new Date(Date.now() + 300000).toISOString(),
704
+ },
705
+ };
706
+
707
+ (global.fetch as any).mockResolvedValueOnce({
708
+ ok: true,
709
+ json: async () => apiResponse,
710
+ });
711
+
712
+ const result = await service.getToolProtectionConfig(mockAgentDid);
713
+
714
+ expect(result.toolProtections.search_products.requiresDelegation).toBe(false);
715
+ expect(result.toolProtections.add_to_cart.requiresDelegation).toBe(true);
716
+ expect(result.toolProtections.add_to_cart.requiredScopes).toContain('cart:write');
717
+ expect(result.toolProtections.checkout.requiredScopes).toContain('payment:process');
718
+ });
719
+
720
+ test('should handle API rate limiting gracefully', async () => {
721
+ (global.fetch as any).mockResolvedValueOnce({
722
+ ok: false,
723
+ status: 429,
724
+ statusText: 'Too Many Requests',
725
+ text: async () => 'Rate limit exceeded',
726
+ });
727
+
728
+ const fallbackConfig = {
729
+ toolProtections: {
730
+ tool1: {
731
+ requiresDelegation: true,
732
+ requiredScopes: ['scope1'],
733
+ },
734
+ },
735
+ };
736
+
737
+ config.fallbackConfig = fallbackConfig;
738
+ service = new ToolProtectionService(config, cache);
739
+
740
+ const result = await service.getToolProtectionConfig(mockAgentDid);
741
+
742
+ expect(result).toEqual(fallbackConfig);
743
+ });
744
+
745
+ test('should handle concurrent requests', async () => {
746
+ const apiResponse = {
747
+ success: true,
748
+ data: {
749
+ toolProtections: {
750
+ tool1: {
751
+ requiresDelegation: true,
752
+ requiredScopes: ['scope1'],
753
+ },
754
+ },
755
+ },
756
+ metadata: {},
757
+ };
758
+
759
+ (global.fetch as any).mockResolvedValue({
760
+ ok: true,
761
+ json: async () => apiResponse,
762
+ });
763
+
764
+ // Make concurrent requests
765
+ const promises = [
766
+ service.getToolProtectionConfig(mockAgentDid),
767
+ service.getToolProtectionConfig(mockAgentDid),
768
+ service.getToolProtectionConfig(mockAgentDid),
769
+ ];
770
+
771
+ const results = await Promise.all(promises);
772
+
773
+ // All should return same config
774
+ results.forEach((result) => {
775
+ expect(result.toolProtections.tool1).toBeDefined();
776
+ });
777
+
778
+ // Should only fetch once (cache prevents duplicate fetches)
779
+ // Note: Due to race conditions, multiple fetches might occur
780
+ expect(global.fetch).toHaveBeenCalled();
781
+ });
782
+ });
783
+ });
784
+