@kya-os/mcp-i-core 1.2.3-canary.7 → 1.3.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 (225) hide show
  1. package/.claude/settings.local.json +9 -0
  2. package/.turbo/turbo-build.log +4 -0
  3. package/.turbo/turbo-test.log +2979 -0
  4. package/COMPLIANCE_IMPROVEMENT_REPORT.md +483 -0
  5. package/Composer 3.md +615 -0
  6. package/GPT-5.md +1169 -0
  7. package/OPUS-plan.md +352 -0
  8. package/PHASE_3_AND_4.1_SUMMARY.md +585 -0
  9. package/PHASE_3_SUMMARY.md +317 -0
  10. package/PHASE_4.1.3_SUMMARY.md +428 -0
  11. package/PHASE_4.1_COMPLETE.md +525 -0
  12. package/PHASE_4_USER_DID_IDENTITY_LINKING_PLAN.md +1240 -0
  13. package/SCHEMA_COMPLIANCE_REPORT.md +275 -0
  14. package/TEST_PLAN.md +571 -0
  15. package/coverage/coverage-final.json +57 -0
  16. package/dist/__tests__/utils/mock-providers.d.ts +1 -2
  17. package/dist/__tests__/utils/mock-providers.d.ts.map +1 -1
  18. package/dist/__tests__/utils/mock-providers.js.map +1 -1
  19. package/dist/cache/oauth-config-cache.d.ts +69 -0
  20. package/dist/cache/oauth-config-cache.d.ts.map +1 -0
  21. package/dist/cache/oauth-config-cache.js +76 -0
  22. package/dist/cache/oauth-config-cache.js.map +1 -0
  23. package/dist/identity/idp-token-resolver.d.ts +53 -0
  24. package/dist/identity/idp-token-resolver.d.ts.map +1 -0
  25. package/dist/identity/idp-token-resolver.js +108 -0
  26. package/dist/identity/idp-token-resolver.js.map +1 -0
  27. package/dist/identity/idp-token-storage.interface.d.ts +42 -0
  28. package/dist/identity/idp-token-storage.interface.d.ts.map +1 -0
  29. package/dist/identity/idp-token-storage.interface.js +12 -0
  30. package/dist/identity/idp-token-storage.interface.js.map +1 -0
  31. package/dist/identity/user-did-manager.d.ts +39 -1
  32. package/dist/identity/user-did-manager.d.ts.map +1 -1
  33. package/dist/identity/user-did-manager.js +69 -3
  34. package/dist/identity/user-did-manager.js.map +1 -1
  35. package/dist/index.d.ts +22 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +39 -1
  38. package/dist/index.js.map +1 -1
  39. package/dist/runtime/audit-logger.d.ts +37 -0
  40. package/dist/runtime/audit-logger.d.ts.map +1 -0
  41. package/dist/runtime/audit-logger.js +9 -0
  42. package/dist/runtime/audit-logger.js.map +1 -0
  43. package/dist/runtime/base.d.ts +58 -2
  44. package/dist/runtime/base.d.ts.map +1 -1
  45. package/dist/runtime/base.js +266 -11
  46. package/dist/runtime/base.js.map +1 -1
  47. package/dist/services/access-control.service.d.ts.map +1 -1
  48. package/dist/services/access-control.service.js +200 -35
  49. package/dist/services/access-control.service.js.map +1 -1
  50. package/dist/services/authorization/authorization-registry.d.ts +29 -0
  51. package/dist/services/authorization/authorization-registry.d.ts.map +1 -0
  52. package/dist/services/authorization/authorization-registry.js +57 -0
  53. package/dist/services/authorization/authorization-registry.js.map +1 -0
  54. package/dist/services/authorization/types.d.ts +53 -0
  55. package/dist/services/authorization/types.d.ts.map +1 -0
  56. package/dist/services/authorization/types.js +10 -0
  57. package/dist/services/authorization/types.js.map +1 -0
  58. package/dist/services/batch-delegation.service.d.ts +53 -0
  59. package/dist/services/batch-delegation.service.d.ts.map +1 -0
  60. package/dist/services/batch-delegation.service.js +95 -0
  61. package/dist/services/batch-delegation.service.js.map +1 -0
  62. package/dist/services/oauth-config.service.d.ts +53 -0
  63. package/dist/services/oauth-config.service.d.ts.map +1 -0
  64. package/dist/services/oauth-config.service.js +119 -0
  65. package/dist/services/oauth-config.service.js.map +1 -0
  66. package/dist/services/oauth-provider-registry.d.ts +88 -0
  67. package/dist/services/oauth-provider-registry.d.ts.map +1 -0
  68. package/dist/services/oauth-provider-registry.js +128 -0
  69. package/dist/services/oauth-provider-registry.js.map +1 -0
  70. package/dist/services/oauth-service.d.ts +77 -0
  71. package/dist/services/oauth-service.d.ts.map +1 -0
  72. package/dist/services/oauth-service.js +348 -0
  73. package/dist/services/oauth-service.js.map +1 -0
  74. package/dist/services/oauth-token-retrieval.service.d.ts +49 -0
  75. package/dist/services/oauth-token-retrieval.service.d.ts.map +1 -0
  76. package/dist/services/oauth-token-retrieval.service.js +150 -0
  77. package/dist/services/oauth-token-retrieval.service.js.map +1 -0
  78. package/dist/services/provider-resolver.d.ts +48 -0
  79. package/dist/services/provider-resolver.d.ts.map +1 -0
  80. package/dist/services/provider-resolver.js +121 -0
  81. package/dist/services/provider-resolver.js.map +1 -0
  82. package/dist/services/provider-validator.d.ts +55 -0
  83. package/dist/services/provider-validator.d.ts.map +1 -0
  84. package/dist/services/provider-validator.js +135 -0
  85. package/dist/services/provider-validator.js.map +1 -0
  86. package/dist/services/tool-context-builder.d.ts +57 -0
  87. package/dist/services/tool-context-builder.d.ts.map +1 -0
  88. package/dist/services/tool-context-builder.js +125 -0
  89. package/dist/services/tool-context-builder.js.map +1 -0
  90. package/dist/services/tool-protection.service.d.ts +87 -10
  91. package/dist/services/tool-protection.service.d.ts.map +1 -1
  92. package/dist/services/tool-protection.service.js +282 -112
  93. package/dist/services/tool-protection.service.js.map +1 -1
  94. package/dist/types/oauth-required-error.d.ts +40 -0
  95. package/dist/types/oauth-required-error.d.ts.map +1 -0
  96. package/dist/types/oauth-required-error.js +40 -0
  97. package/dist/types/oauth-required-error.js.map +1 -0
  98. package/dist/utils/did-helpers.d.ts +33 -0
  99. package/dist/utils/did-helpers.d.ts.map +1 -1
  100. package/dist/utils/did-helpers.js +40 -0
  101. package/dist/utils/did-helpers.js.map +1 -1
  102. package/dist/utils/index.d.ts +1 -0
  103. package/dist/utils/index.d.ts.map +1 -1
  104. package/dist/utils/index.js +1 -0
  105. package/dist/utils/index.js.map +1 -1
  106. package/docs/API_REFERENCE.md +1362 -0
  107. package/docs/COMPLIANCE_MATRIX.md +691 -0
  108. package/docs/STATUSLIST2021_GUIDE.md +696 -0
  109. package/docs/W3C_VC_DELEGATION_GUIDE.md +710 -0
  110. package/package.json +24 -50
  111. package/scripts/audit-compliance.ts +724 -0
  112. package/src/__tests__/cache/tool-protection-cache.test.ts +640 -0
  113. package/src/__tests__/config/provider-runtime-config.test.ts +309 -0
  114. package/src/__tests__/delegation-e2e.test.ts +690 -0
  115. package/src/__tests__/identity/user-did-manager.test.ts +213 -0
  116. package/src/__tests__/index.test.ts +56 -0
  117. package/src/__tests__/integration/full-flow.test.ts +776 -0
  118. package/src/__tests__/integration.test.ts +281 -0
  119. package/src/__tests__/providers/base.test.ts +173 -0
  120. package/src/__tests__/providers/memory.test.ts +319 -0
  121. package/src/__tests__/regression/phase2-regression.test.ts +429 -0
  122. package/src/__tests__/runtime/audit-logger.test.ts +154 -0
  123. package/src/__tests__/runtime/base-extensions.test.ts +593 -0
  124. package/src/__tests__/runtime/base.test.ts +869 -0
  125. package/src/__tests__/runtime/delegation-flow.test.ts +164 -0
  126. package/src/__tests__/runtime/proof-client-did.test.ts +375 -0
  127. package/src/__tests__/runtime/route-interception.test.ts +686 -0
  128. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +908 -0
  129. package/src/__tests__/services/agentshield-integration.test.ts +784 -0
  130. package/src/__tests__/services/provider-resolver-edge-cases.test.ts +591 -0
  131. package/src/__tests__/services/tool-protection-oauth-provider.test.ts +480 -0
  132. package/src/__tests__/services/tool-protection.service.test.ts +1366 -0
  133. package/src/__tests__/utils/mock-providers.ts +340 -0
  134. package/src/cache/oauth-config-cache.d.ts +69 -0
  135. package/src/cache/oauth-config-cache.d.ts.map +1 -0
  136. package/src/cache/oauth-config-cache.js.map +1 -0
  137. package/src/cache/oauth-config-cache.ts +123 -0
  138. package/src/cache/tool-protection-cache.ts +171 -0
  139. package/src/compliance/EXAMPLE.md +412 -0
  140. package/src/compliance/__tests__/schema-verifier.test.ts +797 -0
  141. package/src/compliance/index.ts +8 -0
  142. package/src/compliance/schema-registry.ts +460 -0
  143. package/src/compliance/schema-verifier.ts +708 -0
  144. package/src/config/__tests__/remote-config.spec.ts +268 -0
  145. package/src/config/remote-config.ts +174 -0
  146. package/src/config.ts +309 -0
  147. package/src/delegation/__tests__/audience-validator.test.ts +112 -0
  148. package/src/delegation/__tests__/bitstring.test.ts +346 -0
  149. package/src/delegation/__tests__/cascading-revocation.test.ts +628 -0
  150. package/src/delegation/__tests__/delegation-graph.test.ts +584 -0
  151. package/src/delegation/__tests__/utils.test.ts +152 -0
  152. package/src/delegation/__tests__/vc-issuer.test.ts +442 -0
  153. package/src/delegation/__tests__/vc-verifier.test.ts +922 -0
  154. package/src/delegation/audience-validator.ts +52 -0
  155. package/src/delegation/bitstring.ts +278 -0
  156. package/src/delegation/cascading-revocation.ts +370 -0
  157. package/src/delegation/delegation-graph.ts +299 -0
  158. package/src/delegation/index.ts +14 -0
  159. package/src/delegation/statuslist-manager.ts +353 -0
  160. package/src/delegation/storage/__tests__/memory-graph-storage.test.ts +366 -0
  161. package/src/delegation/storage/__tests__/memory-statuslist-storage.test.ts +228 -0
  162. package/src/delegation/storage/index.ts +9 -0
  163. package/src/delegation/storage/memory-graph-storage.ts +178 -0
  164. package/src/delegation/storage/memory-statuslist-storage.ts +77 -0
  165. package/src/delegation/utils.ts +42 -0
  166. package/src/delegation/vc-issuer.ts +232 -0
  167. package/src/delegation/vc-verifier.ts +568 -0
  168. package/src/identity/idp-token-resolver.ts +147 -0
  169. package/src/identity/idp-token-storage.interface.ts +59 -0
  170. package/src/identity/user-did-manager.ts +370 -0
  171. package/src/index.ts +260 -0
  172. package/src/providers/base.d.ts +91 -0
  173. package/src/providers/base.d.ts.map +1 -0
  174. package/src/providers/base.js.map +1 -0
  175. package/src/providers/base.ts +96 -0
  176. package/src/providers/memory.ts +142 -0
  177. package/src/runtime/audit-logger.ts +39 -0
  178. package/src/runtime/base.ts +1329 -0
  179. package/src/services/__tests__/access-control.integration.test.ts +443 -0
  180. package/src/services/__tests__/access-control.proof-response-validation.test.ts +578 -0
  181. package/src/services/__tests__/access-control.service.test.ts +970 -0
  182. package/src/services/__tests__/batch-delegation.service.test.ts +351 -0
  183. package/src/services/__tests__/crypto.service.test.ts +531 -0
  184. package/src/services/__tests__/oauth-provider-registry.test.ts +142 -0
  185. package/src/services/__tests__/proof-verifier.integration.test.ts +485 -0
  186. package/src/services/__tests__/proof-verifier.test.ts +489 -0
  187. package/src/services/__tests__/provider-resolution.integration.test.ts +202 -0
  188. package/src/services/__tests__/provider-resolver.test.ts +213 -0
  189. package/src/services/__tests__/storage.service.test.ts +358 -0
  190. package/src/services/access-control.service.ts +990 -0
  191. package/src/services/authorization/authorization-registry.ts +66 -0
  192. package/src/services/authorization/types.ts +71 -0
  193. package/src/services/batch-delegation.service.ts +137 -0
  194. package/src/services/crypto.service.ts +302 -0
  195. package/src/services/errors.ts +76 -0
  196. package/src/services/index.ts +9 -0
  197. package/src/services/oauth-config.service.d.ts +53 -0
  198. package/src/services/oauth-config.service.d.ts.map +1 -0
  199. package/src/services/oauth-config.service.js.map +1 -0
  200. package/src/services/oauth-config.service.ts +169 -0
  201. package/src/services/oauth-provider-registry.d.ts +57 -0
  202. package/src/services/oauth-provider-registry.d.ts.map +1 -0
  203. package/src/services/oauth-provider-registry.js.map +1 -0
  204. package/src/services/oauth-provider-registry.ts +141 -0
  205. package/src/services/oauth-service.ts +510 -0
  206. package/src/services/oauth-token-retrieval.service.ts +245 -0
  207. package/src/services/proof-verifier.ts +478 -0
  208. package/src/services/provider-resolver.d.ts +48 -0
  209. package/src/services/provider-resolver.d.ts.map +1 -0
  210. package/src/services/provider-resolver.js.map +1 -0
  211. package/src/services/provider-resolver.ts +146 -0
  212. package/src/services/provider-validator.ts +170 -0
  213. package/src/services/storage.service.ts +566 -0
  214. package/src/services/tool-context-builder.ts +172 -0
  215. package/src/services/tool-protection.service.ts +958 -0
  216. package/src/types/oauth-required-error.ts +63 -0
  217. package/src/types/tool-protection.ts +155 -0
  218. package/src/utils/__tests__/did-helpers.test.ts +101 -0
  219. package/src/utils/base64.ts +148 -0
  220. package/src/utils/cors.ts +83 -0
  221. package/src/utils/did-helpers.ts +150 -0
  222. package/src/utils/index.ts +8 -0
  223. package/src/utils/storage-keys.ts +278 -0
  224. package/tsconfig.json +21 -0
  225. package/vitest.config.ts +56 -0
@@ -0,0 +1,63 @@
1
+ /**
2
+ * OAuth Required Error
3
+ *
4
+ * Error thrown when a tool requires an IDP token (OAuth) but none is available.
5
+ * This triggers the OAuth flow to obtain the necessary token.
6
+ *
7
+ * @package @kya-os/mcp-i-core
8
+ */
9
+
10
+ export interface OAuthRequiredErrorOptions {
11
+ /** Name of the tool requiring OAuth */
12
+ toolName: string;
13
+
14
+ /** Required OAuth scopes */
15
+ requiredScopes: string[];
16
+
17
+ /** OAuth provider name (e.g., "github", "google") */
18
+ provider: string;
19
+
20
+ /** OAuth authorization URL */
21
+ oauthUrl: string;
22
+
23
+ /** Optional resume token for continuing after OAuth */
24
+ resumeToken?: string;
25
+
26
+ /** Optional user DID */
27
+ userDid?: string;
28
+
29
+ /** Optional session ID */
30
+ sessionId?: string;
31
+ }
32
+
33
+ /**
34
+ * Error thrown when a tool requires OAuth but IDP token is not available
35
+ *
36
+ * This error should trigger the OAuth flow to obtain the necessary IDP token.
37
+ */
38
+ export class OAuthRequiredError extends Error {
39
+ public readonly toolName: string;
40
+ public readonly requiredScopes: string[];
41
+ public readonly provider: string;
42
+ public readonly oauthUrl: string;
43
+ public readonly resumeToken?: string;
44
+ public readonly userDid?: string;
45
+ public readonly sessionId?: string;
46
+
47
+ constructor(options: OAuthRequiredErrorOptions) {
48
+ const { toolName, requiredScopes, provider, oauthUrl } = options;
49
+ super(
50
+ `OAuth required for tool "${toolName}" with provider "${provider}". ` +
51
+ `Required scopes: ${requiredScopes.join(", ")}`
52
+ );
53
+ this.name = "OAuthRequiredError";
54
+ this.toolName = toolName;
55
+ this.requiredScopes = requiredScopes;
56
+ this.provider = provider;
57
+ this.oauthUrl = oauthUrl;
58
+ this.resumeToken = options.resumeToken;
59
+ this.userDid = options.userDid;
60
+ this.sessionId = options.sessionId;
61
+ }
62
+ }
63
+
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Tool Protection Types
3
+ *
4
+ * Implementation-specific type definitions for tool protection services.
5
+ * Core spec types are imported from @kya-os/contracts/tool-protection.
6
+ *
7
+ * @package @kya-os/mcp-i-core
8
+ * @version 1.0.0
9
+ */
10
+
11
+ // Import spec types from contracts
12
+ import type {
13
+ ToolProtection,
14
+ ToolProtectionMap,
15
+ } from "@kya-os/contracts/tool-protection";
16
+
17
+ // Re-export for backward compatibility
18
+ export type { ToolProtection };
19
+
20
+ /**
21
+ * Complete tool protection configuration for a project
22
+ * @deprecated Use ToolProtectionMap from @kya-os/contracts/tool-protection
23
+ */
24
+ export interface ToolProtectionConfig {
25
+ /**
26
+ * Map of tool names to their protection settings
27
+ */
28
+ toolProtections: ToolProtectionMap;
29
+ }
30
+
31
+ /**
32
+ * Configuration for the ToolProtectionService
33
+ */
34
+ export interface ToolProtectionServiceConfig {
35
+ /**
36
+ * AgentShield API base URL
37
+ * @example "https://kya.vouched.id"
38
+ */
39
+ apiUrl: string;
40
+
41
+ /**
42
+ * AgentShield API key for authentication
43
+ * @example "sk_..."
44
+ */
45
+ apiKey: string;
46
+
47
+ /**
48
+ * Project ID (optional, used for backward compatibility)
49
+ * The service now fetches config by agent DID instead
50
+ * @deprecated Use agent DID from runtime identity
51
+ * @example "mcp-i-ieu0ro"
52
+ */
53
+ projectId?: string;
54
+
55
+ /**
56
+ * Cache TTL in milliseconds
57
+ * @default 300000 (5 minutes)
58
+ */
59
+ cacheTtl?: number;
60
+
61
+ /**
62
+ * Fallback configuration to use if API is unavailable
63
+ * @optional
64
+ */
65
+ fallbackConfig?: ToolProtectionConfig;
66
+
67
+ /**
68
+ * Fail-safe behavior when API is unavailable and no fallback is provided
69
+ * - 'deny-all': Block all tools by default (secure, recommended for production)
70
+ * - 'allow-all': Allow all tools (insecure, not recommended for production)
71
+ * @default 'deny-all'
72
+ */
73
+ failSafeBehavior?: 'deny-all' | 'allow-all';
74
+
75
+ /**
76
+ * Maximum age (in milliseconds) for stale cache to be used during outages
77
+ * Stale cache is used when API fails and no fallback is provided
78
+ * @default 86400000 (24 hours)
79
+ */
80
+ maxStaleCacheAge?: number;
81
+
82
+ /**
83
+ * Allow using stale cache during outages
84
+ * @default true
85
+ */
86
+ allowStaleCache?: boolean;
87
+
88
+ /**
89
+ * Enable debug logging
90
+ * @default false
91
+ */
92
+ debug?: boolean;
93
+ }
94
+
95
+ /**
96
+ * API response from /api/v1/bouncer/projects/{projectId}/tool-protections
97
+ */
98
+ export interface ToolProtectionApiResponse {
99
+ success: boolean;
100
+ data: {
101
+ toolProtections: Record<string, ToolProtection>;
102
+ };
103
+ metadata: {
104
+ timestamp: string;
105
+ cachedUntil: string;
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Error thrown when a tool requires delegation but none is provided
111
+ *
112
+ * Note: Resume token generation is handled by MCPIRuntimeBase.generateResumeToken().
113
+ * The runtime should generate the token and pass it to this constructor.
114
+ */
115
+ export class DelegationRequiredError extends Error {
116
+ public resumeToken?: string;
117
+ public interceptedCall?: InterceptedToolCall;
118
+
119
+ constructor(
120
+ public toolName: string,
121
+ public requiredScopes: string[],
122
+ public consentUrl?: string,
123
+ interceptedCall?: InterceptedToolCall,
124
+ resumeToken?: string
125
+ ) {
126
+ super(`Delegation required for tool "${toolName}"`);
127
+ this.name = "DelegationRequiredError";
128
+ this.interceptedCall = interceptedCall;
129
+ this.resumeToken = resumeToken;
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Context for an intercepted tool call that needs authorization
135
+ */
136
+ export interface InterceptedToolCall {
137
+ toolName: string;
138
+ args: any;
139
+ sessionId: string;
140
+ timestamp: number;
141
+ expiresAt: number;
142
+ }
143
+
144
+ /**
145
+ * Error thrown when the tool protection service fails
146
+ */
147
+ export class ToolProtectionServiceError extends Error {
148
+ constructor(
149
+ message: string,
150
+ public cause?: Error
151
+ ) {
152
+ super(message);
153
+ this.name = "ToolProtectionServiceError";
154
+ }
155
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Tests for DID Helper Utilities
3
+ *
4
+ * @package @kya-os/mcp-i-core/utils/__tests__
5
+ */
6
+
7
+ import { describe, it, expect } from "vitest";
8
+ import {
9
+ isValidDid,
10
+ getDidMethod,
11
+ normalizeDid,
12
+ compareDids,
13
+ getServerDid,
14
+ } from "../did-helpers";
15
+
16
+ describe("DID Helpers", () => {
17
+ describe("isValidDid", () => {
18
+ it("should return true for valid DIDs", () => {
19
+ expect(isValidDid("did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK")).toBe(true);
20
+ expect(isValidDid("did:web:example.com")).toBe(true);
21
+ expect(isValidDid("did:web:example.com:path")).toBe(true);
22
+ });
23
+
24
+ it("should return false for invalid DIDs", () => {
25
+ expect(isValidDid("not-a-did")).toBe(false);
26
+ expect(isValidDid("")).toBe(false);
27
+ expect(isValidDid("did")).toBe(false);
28
+ expect(isValidDid("key:z6Mk...")).toBe(false);
29
+ });
30
+ });
31
+
32
+ describe("getDidMethod", () => {
33
+ it("should extract DID method correctly", () => {
34
+ expect(getDidMethod("did:key:z6Mk...")).toBe("key");
35
+ expect(getDidMethod("did:web:example.com")).toBe("web");
36
+ expect(getDidMethod("did:ion:...")).toBe("ion");
37
+ });
38
+
39
+ it("should return null for invalid DIDs", () => {
40
+ expect(getDidMethod("not-a-did")).toBeNull();
41
+ expect(getDidMethod("")).toBeNull();
42
+ expect(getDidMethod("did")).toBeNull();
43
+ });
44
+ });
45
+
46
+ describe("normalizeDid", () => {
47
+ it("should trim whitespace", () => {
48
+ expect(normalizeDid(" did:key:z6Mk... ")).toBe("did:key:z6Mk...");
49
+ expect(normalizeDid("did:key:z6Mk...")).toBe("did:key:z6Mk...");
50
+ });
51
+ });
52
+
53
+ describe("compareDids", () => {
54
+ it("should compare DIDs correctly", () => {
55
+ expect(compareDids("did:key:z6Mk...", "did:key:z6Mk...")).toBe(true);
56
+ expect(compareDids("did:key:z6Mk...", "did:web:example.com")).toBe(false);
57
+ });
58
+
59
+ it("should normalize before comparing", () => {
60
+ expect(compareDids(" did:key:z6Mk... ", "did:key:z6Mk...")).toBe(true);
61
+ });
62
+ });
63
+
64
+ describe("getServerDid", () => {
65
+ it("should return serverDid when present", () => {
66
+ const config = {
67
+ identity: {
68
+ serverDid: "did:web:server.com",
69
+ },
70
+ };
71
+ expect(getServerDid(config)).toBe("did:web:server.com");
72
+ });
73
+
74
+ it("should return agentDid when serverDid not present (backward compatibility)", () => {
75
+ const config = {
76
+ identity: {
77
+ agentDid: "did:web:old-server.com",
78
+ },
79
+ };
80
+ expect(getServerDid(config)).toBe("did:web:old-server.com");
81
+ });
82
+
83
+ it("should prefer serverDid over agentDid", () => {
84
+ const config = {
85
+ identity: {
86
+ serverDid: "did:web:new-server.com",
87
+ agentDid: "did:web:old-server.com",
88
+ },
89
+ };
90
+ expect(getServerDid(config)).toBe("did:web:new-server.com");
91
+ });
92
+
93
+ it("should throw error when neither serverDid nor agentDid present", () => {
94
+ const config = {
95
+ identity: {},
96
+ };
97
+ expect(() => getServerDid(config)).toThrow("Server DID not configured");
98
+ });
99
+ });
100
+ });
101
+
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Base64URL Encoding/Decoding Utilities
3
+ *
4
+ * Environment-aware base64url helpers that work in both Node.js and Cloudflare Workers.
5
+ * Uses Buffer in Node.js, TextEncoder/Decoder fallback for Workers.
6
+ */
7
+
8
+ /**
9
+ * Decode base64url string to string
10
+ */
11
+ export function base64urlDecodeToString(input: string): string {
12
+ const padded = addPadding(input);
13
+ const base64 = padded.replace(/-/g, "+").replace(/_/g, "/");
14
+
15
+ // For platforms that don't have Buffer (e.g., Cloudflare Workers)
16
+ if (typeof atob !== "undefined") {
17
+ try {
18
+ return atob(base64);
19
+ } catch (error) {
20
+ throw new Error(
21
+ `Invalid base64url string: ${error instanceof Error ? error.message : String(error)}`
22
+ );
23
+ }
24
+ }
25
+
26
+ // For Node.js environments - Buffer.from doesn't throw for invalid base64
27
+ // We need to validate by checking if the input contains only valid base64 characters
28
+ // Base64 characters: A-Z, a-z, 0-9, +, /, = (padding)
29
+ const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/;
30
+ if (!base64Regex.test(base64)) {
31
+ throw new Error("Invalid base64url string: contains invalid characters");
32
+ }
33
+
34
+ try {
35
+ const decoded = Buffer.from(base64, "base64").toString("utf-8");
36
+ return decoded;
37
+ } catch (error) {
38
+ throw new Error(
39
+ `Invalid base64url string: ${error instanceof Error ? error.message : String(error)}`
40
+ );
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Decode base64url string to Uint8Array
46
+ */
47
+ export function base64urlDecodeToBytes(input: string): Uint8Array {
48
+ const padded = addPadding(input);
49
+ const base64 = padded.replace(/-/g, "+").replace(/_/g, "/");
50
+
51
+ // For platforms that don't have Buffer (e.g., Cloudflare Workers)
52
+ if (typeof atob !== "undefined") {
53
+ try {
54
+ const binaryString = atob(base64);
55
+ const bytes = new Uint8Array(binaryString.length);
56
+ for (let i = 0; i < binaryString.length; i++) {
57
+ bytes[i] = binaryString.charCodeAt(i);
58
+ }
59
+ return bytes;
60
+ } catch (error) {
61
+ throw new Error(
62
+ `Invalid base64url string: ${error instanceof Error ? error.message : String(error)}`
63
+ );
64
+ }
65
+ }
66
+
67
+ // For Node.js environments - Buffer.from doesn't throw, so we can't validate here
68
+ // The caller should validate the result if needed
69
+ return new Uint8Array(Buffer.from(base64, "base64"));
70
+ }
71
+
72
+ /**
73
+ * Encode string to base64url
74
+ */
75
+ export function base64urlEncodeFromString(input: string): string {
76
+ // For platforms that don't have Buffer
77
+ if (typeof btoa !== "undefined") {
78
+ const base64 = btoa(input);
79
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
80
+ }
81
+
82
+ // For Node.js environments
83
+ const base64 = Buffer.from(input, "utf-8").toString("base64");
84
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
85
+ }
86
+
87
+ /**
88
+ * Encode Uint8Array to base64url
89
+ */
90
+ export function base64urlEncodeFromBytes(bytes: Uint8Array): string {
91
+ // For platforms that don't have Buffer
92
+ if (typeof btoa !== "undefined") {
93
+ const binaryString = Array.from(bytes)
94
+ .map((byte) => String.fromCharCode(byte))
95
+ .join("");
96
+ const base64 = btoa(binaryString);
97
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
98
+ }
99
+
100
+ // For Node.js environments
101
+ const base64 = Buffer.from(bytes).toString("base64");
102
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
103
+ }
104
+
105
+ /**
106
+ * Convert bytes to standard base64 (not base64url)
107
+ */
108
+ export function bytesToBase64(bytes: Uint8Array): string {
109
+ // For platforms that don't have Buffer
110
+ if (typeof btoa !== "undefined") {
111
+ const binaryString = Array.from(bytes)
112
+ .map((byte) => String.fromCharCode(byte))
113
+ .join("");
114
+ return btoa(binaryString);
115
+ }
116
+
117
+ // For Node.js environments
118
+ return Buffer.from(bytes).toString("base64");
119
+ }
120
+
121
+ /**
122
+ * Convert standard base64 to bytes
123
+ */
124
+ export function base64ToBytes(base64: string): Uint8Array {
125
+ // For platforms that don't have Buffer
126
+ if (typeof atob !== "undefined") {
127
+ const binaryString = atob(base64);
128
+ const bytes = new Uint8Array(binaryString.length);
129
+ for (let i = 0; i < binaryString.length; i++) {
130
+ bytes[i] = binaryString.charCodeAt(i);
131
+ }
132
+ return bytes;
133
+ }
134
+
135
+ // For Node.js environments
136
+ return new Uint8Array(Buffer.from(base64, "base64"));
137
+ }
138
+
139
+ /**
140
+ * Add padding to base64url string if needed
141
+ */
142
+ function addPadding(input: string): string {
143
+ const remainder = input.length % 4;
144
+ if (remainder === 0) {
145
+ return input;
146
+ }
147
+ return input + "=".repeat((4 - remainder) % 4);
148
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * CORS Header Utilities
3
+ *
4
+ * Centralized CORS header management for MCP-I services.
5
+ * Includes Vary: Origin for cache optimization when origin scoping is implemented.
6
+ */
7
+
8
+ /**
9
+ * Type-safe CORS headers
10
+ * Compatible with Response headers and HeadersInit
11
+ */
12
+ export type CORSHeaders = Record<string, string>;
13
+
14
+ /**
15
+ * Standard CORS headers for well-known endpoints (.well-known/*)
16
+ * Includes Vary: Origin for future cache optimization when origin scoping is added
17
+ */
18
+ export const WELL_KNOWN_CORS_HEADERS: CORSHeaders = {
19
+ 'Access-Control-Allow-Origin': '*',
20
+ 'Vary': 'Origin'
21
+ };
22
+
23
+ /**
24
+ * CORS headers for MCP protocol responses
25
+ * Includes exposed headers for session management
26
+ */
27
+ export const MCP_CORS_HEADERS: CORSHeaders = {
28
+ 'Access-Control-Allow-Origin': '*',
29
+ 'Access-Control-Expose-Headers': 'mcp-session-id',
30
+ 'Vary': 'Origin'
31
+ };
32
+
33
+ /**
34
+ * CORS preflight headers for OPTIONS requests
35
+ * Comprehensive header allowlist for MCP protocol
36
+ */
37
+ export const PREFLIGHT_CORS_HEADERS: CORSHeaders = {
38
+ 'Access-Control-Allow-Origin': '*',
39
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
40
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, mcp-session-id, mcp-protocol-version',
41
+ 'Vary': 'Origin'
42
+ };
43
+
44
+ /**
45
+ * CORS headers for OAuth endpoints
46
+ * Includes additional headers required for OAuth 2.0 flows
47
+ */
48
+ export const OAUTH_CORS_HEADERS: CORSHeaders = {
49
+ 'Access-Control-Allow-Origin': '*',
50
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
51
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Accept, mcp-protocol-version',
52
+ 'Access-Control-Expose-Headers': 'Content-Type',
53
+ 'Vary': 'Origin'
54
+ };
55
+
56
+ /**
57
+ * Merge CORS headers with existing headers
58
+ * Ensures CORS headers take precedence
59
+ */
60
+ export function mergeCORSHeaders(
61
+ existingHeaders: Record<string, string>,
62
+ corsHeaders: CORSHeaders = WELL_KNOWN_CORS_HEADERS
63
+ ): Record<string, string> {
64
+ return {
65
+ ...existingHeaders,
66
+ ...corsHeaders
67
+ };
68
+ }
69
+
70
+ /**
71
+ * Apply CORS headers to an Express Response object
72
+ * For use with Express middleware
73
+ */
74
+ export function applyCORSHeaders(
75
+ res: { setHeader: (name: string, value: string) => void },
76
+ corsHeaders: CORSHeaders = MCP_CORS_HEADERS
77
+ ): void {
78
+ Object.entries(corsHeaders).forEach(([key, value]) => {
79
+ if (value !== undefined) {
80
+ res.setHeader(key, value);
81
+ }
82
+ });
83
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * DID Validation and Helper Utilities
3
+ *
4
+ * Centralized utilities for DID validation, normalization, and handling.
5
+ * Promotes DRY principle and consistency across the codebase.
6
+ *
7
+ * @package @kya-os/mcp-i-core/utils
8
+ */
9
+
10
+ /**
11
+ * Check if a string is a valid DID format
12
+ *
13
+ * @param did - String to validate
14
+ * @returns true if string starts with "did:"
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * isValidDid("did:key:z6Mk...") // true
19
+ * isValidDid("not-a-did") // false
20
+ * ```
21
+ */
22
+ export function isValidDid(did: string): boolean {
23
+ return typeof did === "string" && did.startsWith("did:");
24
+ }
25
+
26
+ /**
27
+ * Get the DID method from a DID string
28
+ *
29
+ * @param did - DID string
30
+ * @returns DID method (e.g., "key", "web") or null if invalid
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * getDidMethod("did:key:z6Mk...") // "key"
35
+ * getDidMethod("did:web:example.com") // "web"
36
+ * getDidMethod("invalid") // null
37
+ * ```
38
+ */
39
+ export function getDidMethod(did: string): string | null {
40
+ if (!isValidDid(did)) {
41
+ return null;
42
+ }
43
+ const match = did.match(/^did:([^:]+):/);
44
+ return match ? match[1] : null;
45
+ }
46
+
47
+ /**
48
+ * Normalize a DID string (trim whitespace)
49
+ *
50
+ * @param did - DID string to normalize
51
+ * @returns Normalized DID string
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * normalizeDid(" did:key:z6Mk... ") // "did:key:z6Mk..."
56
+ * ```
57
+ */
58
+ export function normalizeDid(did: string): string {
59
+ return did.trim();
60
+ }
61
+
62
+ /**
63
+ * Compare two DIDs for equality (case-sensitive)
64
+ *
65
+ * @param did1 - First DID
66
+ * @param did2 - Second DID
67
+ * @returns true if DIDs are equal (after normalization)
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * compareDids("did:key:z6Mk...", "did:key:z6Mk...") // true
72
+ * compareDids("did:key:z6Mk...", "did:web:example.com") // false
73
+ * ```
74
+ */
75
+ export function compareDids(did1: string, did2: string): boolean {
76
+ return normalizeDid(did1) === normalizeDid(did2);
77
+ }
78
+
79
+ /**
80
+ * Extract server DID from config (supports both old and new field names)
81
+ *
82
+ * Supports backward compatibility by reading both `serverDid` and deprecated `agentDid`.
83
+ * Prefers `serverDid` if both are present.
84
+ *
85
+ * @param config - Config object with identity field
86
+ * @returns Server DID string
87
+ * @throws Error if neither serverDid nor agentDid is configured
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * // New config
92
+ * getServerDid({ identity: { serverDid: "did:web:server.com" } }) // "did:web:server.com"
93
+ *
94
+ * // Old config (backward compatibility)
95
+ * getServerDid({ identity: { agentDid: "did:web:server.com" } }) // "did:web:server.com"
96
+ *
97
+ * // Prefers serverDid over agentDid
98
+ * getServerDid({ identity: { serverDid: "new", agentDid: "old" } }) // "new"
99
+ * ```
100
+ */
101
+ export function getServerDid(config: {
102
+ identity: { serverDid?: string; agentDid?: string };
103
+ }): string {
104
+ const serverDid = config.identity.serverDid || config.identity.agentDid;
105
+ if (!serverDid) {
106
+ throw new Error("Server DID not configured");
107
+ }
108
+ return serverDid;
109
+ }
110
+
111
+ /**
112
+ * Extract agent ID from DID
113
+ *
114
+ * The agent ID is the last component of the DID.
115
+ *
116
+ * @param did - DID string
117
+ * @returns Agent ID (last component of DID)
118
+ *
119
+ * @example
120
+ * ```typescript
121
+ * extractAgentId("did:web:knowthat.ai:agents:my-agent") // "my-agent"
122
+ * extractAgentId("did:web:localhost:3000:agents:12912feb") // "12912feb"
123
+ * extractAgentId("did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK") // "z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
124
+ * ```
125
+ */
126
+ export function extractAgentId(did: string): string {
127
+ const parts = did.split(':');
128
+ return parts[parts.length - 1];
129
+ }
130
+
131
+ /**
132
+ * Extract agent slug from DID
133
+ *
134
+ * Agent slug is the same as agent ID - the last component of the DID.
135
+ * For DID format: did:web:knowthat.ai:agents:my-agent
136
+ * Returns: my-agent
137
+ *
138
+ * @param did - DID string
139
+ * @returns Agent slug (last component of DID)
140
+ *
141
+ * @example
142
+ * ```typescript
143
+ * extractAgentSlug("did:web:knowthat.ai:agents:my-agent") // "my-agent"
144
+ * extractAgentSlug("did:web:localhost:3000:agents:12912feb") // "12912feb"
145
+ * ```
146
+ */
147
+ export function extractAgentSlug(did: string): string {
148
+ return extractAgentId(did);
149
+ }
150
+
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Utility exports
3
+ */
4
+
5
+ export * from "./cors";
6
+ export * from "./base64";
7
+ export * from "./storage-keys";
8
+ export * from "./did-helpers";