@kya-os/mcp-i-core 1.8.0 → 1.8.1

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 (111) hide show
  1. package/dist/conformance/capability-verifier-adapter.d.ts +66 -0
  2. package/dist/conformance/capability-verifier-adapter.js +61 -0
  3. package/dist/conformance/index.d.ts +3 -1
  4. package/dist/conformance/index.js +7 -1
  5. package/dist/conformance/validate-level2.d.ts +13 -3
  6. package/dist/conformance/validate-level2.js +15 -5
  7. package/dist/conformance/vc-jwt-verifier.d.ts +55 -0
  8. package/dist/conformance/vc-jwt-verifier.js +147 -0
  9. package/dist/delegation/did-web-resolver.d.ts +60 -0
  10. package/dist/delegation/did-web-resolver.js +129 -0
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.js +9 -1
  13. package/package.json +3 -3
  14. package/dist/auth/handshake.d.ts +0 -119
  15. package/dist/auth/handshake.js +0 -250
  16. package/dist/auth/index.d.ts +0 -6
  17. package/dist/auth/index.js +0 -11
  18. package/dist/auth/types.d.ts +0 -46
  19. package/dist/auth/types.js +0 -10
  20. package/dist/cache/oauth-config-cache.d.ts +0 -69
  21. package/dist/cache/oauth-config-cache.js +0 -76
  22. package/dist/cache/tool-protection-cache.d.ts +0 -89
  23. package/dist/cache/tool-protection-cache.js +0 -118
  24. package/dist/compliance/index.d.ts +0 -8
  25. package/dist/compliance/index.js +0 -24
  26. package/dist/compliance/schema-registry.d.ts +0 -50
  27. package/dist/compliance/schema-registry.js +0 -438
  28. package/dist/compliance/schema-verifier.d.ts +0 -110
  29. package/dist/compliance/schema-verifier.js +0 -518
  30. package/dist/config/remote-config.d.ts +0 -173
  31. package/dist/config/remote-config.js +0 -253
  32. package/dist/config.d.ts +0 -182
  33. package/dist/config.js +0 -148
  34. package/dist/identity/idp-token-resolver.d.ts +0 -69
  35. package/dist/identity/idp-token-resolver.js +0 -136
  36. package/dist/identity/idp-token-storage.interface.d.ts +0 -80
  37. package/dist/identity/idp-token-storage.interface.js +0 -14
  38. package/dist/identity/user-did-manager.d.ts +0 -228
  39. package/dist/identity/user-did-manager.js +0 -356
  40. package/dist/logging/index.d.ts +0 -5
  41. package/dist/logging/index.js +0 -10
  42. package/dist/logging/logger.d.ts +0 -33
  43. package/dist/logging/logger.js +0 -104
  44. package/dist/proof/generator.d.ts +0 -109
  45. package/dist/proof/generator.js +0 -236
  46. package/dist/proof/index.d.ts +0 -5
  47. package/dist/proof/index.js +0 -11
  48. package/dist/providers/base.d.ts +0 -95
  49. package/dist/providers/base.js +0 -47
  50. package/dist/providers/memory.d.ts +0 -42
  51. package/dist/providers/memory.js +0 -121
  52. package/dist/runtime/audit-logger.d.ts +0 -37
  53. package/dist/runtime/audit-logger.js +0 -9
  54. package/dist/runtime/base.d.ts +0 -375
  55. package/dist/runtime/base.js +0 -1491
  56. package/dist/runtime/ext-apps-constants.d.ts +0 -14
  57. package/dist/runtime/ext-apps-constants.js +0 -17
  58. package/dist/services/access-control.service.d.ts +0 -138
  59. package/dist/services/access-control.service.js +0 -721
  60. package/dist/services/authorization/authorization-registry.d.ts +0 -29
  61. package/dist/services/authorization/authorization-registry.js +0 -58
  62. package/dist/services/authorization/types.d.ts +0 -53
  63. package/dist/services/authorization/types.js +0 -10
  64. package/dist/services/batch-delegation.service.d.ts +0 -53
  65. package/dist/services/batch-delegation.service.js +0 -95
  66. package/dist/services/crypto.service.d.ts +0 -69
  67. package/dist/services/crypto.service.js +0 -225
  68. package/dist/services/delegation-error-formatter.d.ts +0 -124
  69. package/dist/services/delegation-error-formatter.js +0 -214
  70. package/dist/services/errors.d.ts +0 -49
  71. package/dist/services/errors.js +0 -66
  72. package/dist/services/index.d.ts +0 -9
  73. package/dist/services/index.js +0 -15
  74. package/dist/services/oauth-config.service.d.ts +0 -53
  75. package/dist/services/oauth-config.service.js +0 -141
  76. package/dist/services/oauth-provider-registry.d.ts +0 -88
  77. package/dist/services/oauth-provider-registry.js +0 -128
  78. package/dist/services/oauth-service.d.ts +0 -122
  79. package/dist/services/oauth-service.js +0 -442
  80. package/dist/services/oauth-token-retrieval.service.d.ts +0 -49
  81. package/dist/services/oauth-token-retrieval.service.js +0 -150
  82. package/dist/services/policy.service.d.ts +0 -130
  83. package/dist/services/policy.service.js +0 -399
  84. package/dist/services/proof-verifier.d.ts +0 -98
  85. package/dist/services/proof-verifier.js +0 -319
  86. package/dist/services/provider-resolver.d.ts +0 -89
  87. package/dist/services/provider-resolver.js +0 -196
  88. package/dist/services/provider-validator.d.ts +0 -55
  89. package/dist/services/provider-validator.js +0 -135
  90. package/dist/services/session-registration.service.d.ts +0 -80
  91. package/dist/services/session-registration.service.js +0 -174
  92. package/dist/services/storage.service.d.ts +0 -116
  93. package/dist/services/storage.service.js +0 -411
  94. package/dist/services/tool-context-builder.d.ts +0 -74
  95. package/dist/services/tool-context-builder.js +0 -215
  96. package/dist/services/tool-protection.service.d.ts +0 -193
  97. package/dist/services/tool-protection.service.js +0 -736
  98. package/dist/session/index.d.ts +0 -5
  99. package/dist/session/index.js +0 -11
  100. package/dist/session/manager.d.ts +0 -113
  101. package/dist/session/manager.js +0 -273
  102. package/dist/types/oauth-required-error.d.ts +0 -46
  103. package/dist/types/oauth-required-error.js +0 -42
  104. package/dist/types/tool-protection.d.ts +0 -144
  105. package/dist/types/tool-protection.js +0 -48
  106. package/dist/utils/cors.d.ts +0 -44
  107. package/dist/utils/cors.js +0 -71
  108. package/dist/utils/index.d.ts +0 -8
  109. package/dist/utils/index.js +0 -24
  110. package/dist/utils/storage-keys.d.ts +0 -120
  111. package/dist/utils/storage-keys.js +0 -217
@@ -1,215 +0,0 @@
1
- "use strict";
2
- /**
3
- * Tool Context Builder
4
- *
5
- * Builds ToolExecutionContext for tool handlers by resolving IDP tokens
6
- * based on tool protection configuration and user identity.
7
- *
8
- * Updated for CRED-003: Builds idpHeaders based on tokenUsage metadata
9
- * to support credential providers with custom token usage patterns.
10
- *
11
- * @package @kya-os/mcp-i-core
12
- */
13
- Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.ToolContextBuilder = void 0;
15
- const oauth_required_error_js_1 = require("../types/oauth-required-error.js");
16
- const provider_resolver_js_1 = require("./provider-resolver.js");
17
- /**
18
- * Builder for tool execution context
19
- *
20
- * Resolves IDP tokens and builds context for tool handlers.
21
- * Phase 1: Uses configured provider as temporary fallback.
22
- * Phase 2+: Requires explicit oauthProvider on tool protection.
23
- */
24
- class ToolContextBuilder {
25
- config;
26
- constructor(config) {
27
- this.config = {
28
- tokenResolver: config.tokenResolver,
29
- configService: config.configService,
30
- providerResolver: config.providerResolver,
31
- projectId: config.projectId,
32
- logger: config.logger || (() => { }),
33
- };
34
- }
35
- /**
36
- * Build tool execution context
37
- *
38
- * @param toolName - Name of the tool being executed
39
- * @param userDid - User DID (optional, required for OAuth/credentials)
40
- * @param sessionId - Session ID (optional)
41
- * @param delegationToken - Delegation token (optional)
42
- * @param toolProtection - Tool protection configuration (optional)
43
- * @returns Tool execution context or undefined if not needed
44
- */
45
- async buildContext(toolName, userDid, sessionId, delegationToken, toolProtection) {
46
- // Only build context if tool requires OAuth/credentials
47
- if (!toolProtection?.requiredScopes?.length || !userDid) {
48
- return undefined;
49
- }
50
- // Phase 2: Resolve provider using ProviderResolver
51
- // ProviderResolver handles priority-based resolution with fallbacks
52
- let provider;
53
- try {
54
- provider = await this.resolveProvider(toolProtection);
55
- }
56
- catch (error) {
57
- // ConsentOnlyModeError and CredentialAuthModeError are NOT errors
58
- // They're signals about what auth flow to use - re-throw for caller to handle
59
- if (error instanceof provider_resolver_js_1.ConsentOnlyModeError ||
60
- error instanceof provider_resolver_js_1.CredentialAuthModeError) {
61
- this.config.logger("[ToolContextBuilder] Special auth mode detected, re-throwing", {
62
- toolName,
63
- errorType: error.name,
64
- message: error.message,
65
- });
66
- throw error;
67
- }
68
- // Other provider resolution errors - cannot build context
69
- this.config.logger("[ToolContextBuilder] Provider not resolved", {
70
- toolName,
71
- userDid: userDid.substring(0, 20) + "...",
72
- error: error instanceof Error ? error.message : String(error),
73
- });
74
- return undefined;
75
- }
76
- // CRED-003: Resolve full token data (not just access_token)
77
- // This includes tokenUsage, cookieFormat, apiHeaders for credential providers
78
- const tokenData = await this.config.tokenResolver.resolveTokenDataFromDid(userDid, provider, toolProtection.requiredScopes);
79
- if (!tokenData) {
80
- // IDP token not available - check if delegation token exists
81
- // If delegation exists, tool can still execute without IDP token
82
- // (the tool handler should check for idpToken if it needs external API access)
83
- if (delegationToken) {
84
- this.config.logger("[ToolContextBuilder] IDP token not found, but delegation exists - returning minimal context", {
85
- toolName,
86
- userDid: userDid.substring(0, 20) + "...",
87
- provider,
88
- scopes: toolProtection.requiredScopes,
89
- note: "Tool can execute with delegation-only authorization",
90
- });
91
- // Return minimal context with delegation info
92
- // Tools that need IDP token for external API calls should check for idpToken
93
- return {
94
- provider,
95
- scopes: toolProtection.requiredScopes,
96
- userDid,
97
- sessionId,
98
- delegationToken,
99
- };
100
- }
101
- // No delegation token either - throw OAuthRequiredError to trigger auth flow
102
- this.config.logger("[ToolContextBuilder] Token not available, throwing OAuthRequiredError", {
103
- toolName,
104
- userDid: userDid.substring(0, 20) + "...",
105
- provider,
106
- scopes: toolProtection.requiredScopes,
107
- });
108
- // Throw error with provider and scopes info
109
- // Auth URL will be built by the Cloudflare layer (agent.ts)
110
- throw new oauth_required_error_js_1.OAuthRequiredError({
111
- toolName,
112
- requiredScopes: toolProtection.requiredScopes,
113
- provider,
114
- oauthUrl: "", // Will be populated by Cloudflare layer
115
- userDid,
116
- sessionId,
117
- });
118
- }
119
- // CRED-003: Build headers based on tokenUsage
120
- const idpHeaders = this.buildAuthHeaders(tokenData);
121
- // Build context with token and headers
122
- // Include userId from token metadata (extracted from credential provider response)
123
- const context = {
124
- idpToken: tokenData.access_token,
125
- idpHeaders,
126
- provider,
127
- scopes: toolProtection.requiredScopes,
128
- userDid,
129
- sessionId,
130
- delegationToken,
131
- // CRED-003: Include userId from credential provider's extracted user ID
132
- userId: tokenData.userId,
133
- };
134
- this.config.logger("[ToolContextBuilder] Context built successfully", {
135
- toolName,
136
- userDid: userDid.substring(0, 20) + "...",
137
- provider,
138
- hasToken: !!tokenData.access_token,
139
- hasUserId: !!tokenData.userId,
140
- tokenUsage: tokenData.tokenUsage,
141
- headerKeys: Object.keys(idpHeaders),
142
- });
143
- return context;
144
- }
145
- /**
146
- * Build authentication headers based on token usage metadata (CRED-003)
147
- *
148
- * Supports three modes:
149
- * - "cookie": Cookie header (with optional cookieFormat template)
150
- * - "bearer": Authorization: Bearer xxx
151
- * - "header": Custom header name
152
- *
153
- * Also includes any apiHeaders from provider config.
154
- *
155
- * @param tokenData - Token data with usage metadata
156
- * @returns Headers object for API calls
157
- */
158
- buildAuthHeaders(tokenData) {
159
- const authHeaders = {};
160
- const tokenUsage = tokenData.tokenUsage || "bearer"; // Default to bearer for OAuth
161
- const token = tokenData.access_token;
162
- switch (tokenUsage) {
163
- case "cookie":
164
- // Use cookieFormat if specified, otherwise send raw token
165
- if (tokenData.cookieFormat) {
166
- authHeaders["Cookie"] = tokenData.cookieFormat.replace(/\{\{token\}\}/g, token);
167
- }
168
- else {
169
- authHeaders["Cookie"] = token;
170
- }
171
- break;
172
- case "bearer":
173
- authHeaders["Authorization"] = `Bearer ${token}`;
174
- break;
175
- case "header":
176
- const headerName = tokenData.tokenHeader || "X-Session-Token";
177
- authHeaders[headerName] = token;
178
- break;
179
- default:
180
- // Unknown usage - default to bearer
181
- authHeaders["Authorization"] = `Bearer ${token}`;
182
- }
183
- // Add any additional API headers from provider config
184
- if (tokenData.apiHeaders) {
185
- Object.assign(authHeaders, tokenData.apiHeaders);
186
- }
187
- return authHeaders;
188
- }
189
- /**
190
- * Resolve OAuth provider for a tool
191
- *
192
- * Phase 2: Uses ProviderResolver with priority-based resolution
193
- *
194
- * @param toolProtection - Tool protection configuration
195
- * @returns Provider name or throws error if not found
196
- */
197
- async resolveProvider(toolProtection) {
198
- try {
199
- const provider = await this.config.providerResolver.resolveProvider(toolProtection, this.config.projectId);
200
- this.config.logger("[ToolContextBuilder] Provider resolved", {
201
- provider,
202
- });
203
- return provider;
204
- }
205
- catch (error) {
206
- this.config.logger("[ToolContextBuilder] Provider resolution failed", {
207
- error: error instanceof Error ? error.message : String(error),
208
- projectId: this.config.projectId,
209
- });
210
- throw error; // Re-throw to let caller handle
211
- }
212
- }
213
- }
214
- exports.ToolContextBuilder = ToolContextBuilder;
215
- //# sourceMappingURL=tool-context-builder.js.map
@@ -1,193 +0,0 @@
1
- /**
2
- * ToolProtectionService - Fetches and caches tool protection configurations
3
- *
4
- * This service manages tool protection configuration from AgentShield API with
5
- * efficient caching and automatic synchronization support.
6
- *
7
- * CONFIGURATION PRECEDENCE (highest to lowest):
8
- * ---------------------------------------------
9
- * 1. Remote config (AgentShield API) - WINS (source of truth)
10
- * 2. Local config (localConfig) - Base defaults, overridden by remote
11
- * 3. Framework defaults
12
- *
13
- * OFFLINE FALLBACK (only when API unavailable):
14
- * ---------------------------------------------
15
- * 1. Stale cache (if allowStaleCache=true and within maxStaleCacheAge)
16
- * 2. offlineFallbackConfig (explicit offline-only config)
17
- * 3. failSafeBehavior (deny-all or allow-all)
18
- *
19
- * CORE FUNCTIONALITY:
20
- * -------------------
21
- * 1. Fetches tool protection config from AgentShield API (remote wins)
22
- * 2. Merges with local config (local serves as base defaults)
23
- * 3. Caches responses with configurable TTL (default 5 minutes)
24
- * 4. Provides delegation requirement checking before tool execution
25
- *
26
- * SYNCHRONIZATION WITH AGENTSHIELD:
27
- * ----------------------------------
28
- * When you update tool protection settings in the AgentShield dashboard:
29
- *
30
- * 1. Dashboard sends PATCH /api/internal/bouncer/tools/{projectId}/{toolName}
31
- * 2. AgentShield updates the database immediately (PostgreSQL JSONB column)
32
- * 3. Dashboard sends POST /admin/clear-cache to this service (automatic)
33
- * 4. This service clears the cached config from KV storage
34
- * 5. Next tool call fetches fresh config from AgentShield API
35
- * 6. New config is cached for the configured TTL period
36
- *
37
- * CACHE INVALIDATION:
38
- * -------------------
39
- * Cache is invalidated via POST /admin/clear-cache endpoint:
40
- * - Triggered automatically by AgentShield dashboard when tool protection changes
41
- * - Can be triggered manually for testing/debugging
42
- * - Requires API key authentication for security
43
- *
44
- * If cache is NOT cleared:
45
- * - Stale config is served until TTL expires (default 5 minutes)
46
- * - Configure shorter TTL via TOOL_PROTECTION_CACHE_TTL env var for faster updates
47
- * - Set to 0 for no cache (not recommended for production)
48
- *
49
- * TOOL DISCOVERY PREREQUISITE:
50
- * ----------------------------
51
- * IMPORTANT: Tools must be discovered before they can be protected!
52
- *
53
- * Discovery happens when:
54
- * - Agent makes first tool call with proof submission
55
- * - AgentShield extracts tool info from cryptographic proof
56
- * - Tool is added to bouncerConfigs.discoveredTools in database
57
- *
58
- * If tool not discovered:
59
- * - Tool won't appear in dashboard
60
- * - Protection settings can't be configured
61
- * - GET /config returns empty toolProtection.tools object
62
- *
63
- * DEBUGGING:
64
- * ----------
65
- * Enable debug logging with:
66
- * toolProtection: { debug: true }
67
- *
68
- * Debug logs show:
69
- * - Cache hits vs API fetches
70
- * - Full API responses
71
- * - Tool protection status for each tool
72
- * - Cache TTL and expiration times
73
- * - Source of config data (cache, api, or fallback)
74
- *
75
- * TROUBLESHOOTING:
76
- * ----------------
77
- * Problem: Dashboard shows protection but tool still executes
78
- * Cause: Stale cache not invalidated
79
- * Solution: POST /admin/clear-cache or wait for TTL expiration
80
- *
81
- * Problem: Empty toolProtections returned from API
82
- * Cause: Tool not discovered yet (no proof submissions)
83
- * Solution: Make at least one tool call to trigger discovery
84
- *
85
- * Problem: Updates take 5+ minutes to apply
86
- * Cause: Long cache TTL and cache clear failed
87
- * Solution: Configure MCP server URL in AgentShield for auto cache clear
88
- *
89
- * @see https://github.com/modelcontextprotocol-identity/agent-shield/docs/bouncer/tool-protection-sync.md
90
- * @package @kya-os/mcp-i-core
91
- */
92
- import type { ToolProtection, ToolProtectionConfig, ToolProtectionServiceConfig } from "../types/tool-protection.js";
93
- import type { ToolProtectionCache } from "../cache/tool-protection-cache.js";
94
- /**
95
- * Service for fetching and checking tool protection configurations
96
- */
97
- export declare class ToolProtectionService {
98
- private config;
99
- private cache;
100
- constructor(config: ToolProtectionServiceConfig, cache: ToolProtectionCache);
101
- /**
102
- * Get the project ID from the service configuration
103
- * @returns Project ID or undefined if not configured
104
- */
105
- getProjectId(): string | undefined;
106
- /**
107
- * Get stale cache entry if available and within maxStaleCacheAge
108
- * Only works with InMemoryToolProtectionCache (has internal access to expiresAt)
109
- *
110
- * NOTE: This checks stale cache BEFORE calling cache.get() to avoid deletion of expired entries
111
- *
112
- * @param cacheKey Cache key to check
113
- * @returns Stale cache entry or null if not available/too old
114
- */
115
- private getStaleCache;
116
- /**
117
- * Get tool protection configuration for the agent
118
- *
119
- * Flow:
120
- * 1. Check cache (project-scoped if projectId available)
121
- * 2. If cache miss, fetch from API
122
- * 3. If API fails, use fallback config
123
- * 4. Cache successful API responses
124
- *
125
- * @param agentDid DID of the agent to fetch config for
126
- */
127
- getToolProtectionConfig(agentDid: string): Promise<ToolProtectionConfig>;
128
- /**
129
- * Check if a tool requires delegation
130
- *
131
- * @param toolName Name of the tool to check
132
- * @param agentDid DID of the agent executing the tool
133
- * @returns Tool protection config or null if no protection required
134
- */
135
- checkToolProtection(toolName: string, agentDid: string): Promise<ToolProtection | null>;
136
- /**
137
- * Fetch tool protection config from AgentShield API
138
- *
139
- * Uses the merged /config endpoint which returns tool protections embedded
140
- * at config.toolProtection.tools. Falls back to legacy formats for backward
141
- * compatibility.
142
- *
143
- * @param agentDid DID of the agent to fetch config for
144
- * @param options Optional fetch options
145
- * @param options.bypassCDNCache When true, adds cache-busting to bypass CDN caches (used by clearAndRefresh)
146
- */
147
- private fetchFromApi;
148
- /**
149
- * Parse tool protections from API response
150
- *
151
- * Extracts tool protection configs from merged config format:
152
- * { data: { config: { toolProtection: { tools: {...} } } } }
153
- *
154
- * @param response API response from AgentShield
155
- * @returns Record of tool name to ToolProtection
156
- */
157
- private parseToolProtectionsFromResponse;
158
- /**
159
- * Clear the cache for a project or agent (useful for testing or manual refresh)
160
- *
161
- * If projectId is configured, clears project-scoped cache.
162
- * Otherwise, clears agent-scoped cache.
163
- *
164
- * @param agentDid DID of the agent (used for fallback if projectId not available)
165
- */
166
- clearCache(agentDid: string): Promise<void>;
167
- /**
168
- * Clear cache and immediately fetch fresh config from API
169
- *
170
- * This method is designed for Cloudflare Workers where KV has edge caching.
171
- * After clearing the KV entry, it fetches fresh data from the API and writes
172
- * it back to KV. This ensures:
173
- * 1. The global KV entry is deleted
174
- * 2. Fresh data is fetched from API (with CDN cache bypass!)
175
- * 3. New data is written to KV (updating edge cache)
176
- *
177
- * The next request from the same edge location will get the fresh data.
178
- *
179
- * IMPORTANT: This method uses bypassCDNCache to ensure we get fresh data
180
- * from AgentShield's origin server, not stale CDN-cached data. This is
181
- * critical for instant cache invalidation when tool protection settings
182
- * are changed in the AgentShield dashboard.
183
- *
184
- * @param agentDid DID of the agent (used for cache key)
185
- * @returns The fresh tool protection config from API
186
- */
187
- clearAndRefresh(agentDid: string): Promise<{
188
- config: ToolProtectionConfig;
189
- cacheKey: string;
190
- source: "api" | "fallback";
191
- }>;
192
- }
193
- //# sourceMappingURL=tool-protection.service.d.ts.map