@kya-os/mcp-i-core 1.3.7-canary.0 → 1.3.7-canary.clientinfo.20251126041014

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 (236) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/.turbo/turbo-test$colon$coverage.log +4239 -0
  3. package/.turbo/turbo-test.log +2973 -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 +24 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +43 -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 +19 -2
  44. package/dist/runtime/base.d.ts.map +1 -1
  45. package/dist/runtime/base.js +227 -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 +199 -15
  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/index.d.ts +2 -0
  63. package/dist/services/index.d.ts.map +1 -1
  64. package/dist/services/index.js +4 -1
  65. package/dist/services/index.js.map +1 -1
  66. package/dist/services/oauth-config.service.d.ts +53 -0
  67. package/dist/services/oauth-config.service.d.ts.map +1 -0
  68. package/dist/services/oauth-config.service.js +141 -0
  69. package/dist/services/oauth-config.service.js.map +1 -0
  70. package/dist/services/oauth-provider-registry.d.ts +88 -0
  71. package/dist/services/oauth-provider-registry.d.ts.map +1 -0
  72. package/dist/services/oauth-provider-registry.js +128 -0
  73. package/dist/services/oauth-provider-registry.js.map +1 -0
  74. package/dist/services/oauth-service.d.ts +77 -0
  75. package/dist/services/oauth-service.d.ts.map +1 -0
  76. package/dist/services/oauth-service.js +373 -0
  77. package/dist/services/oauth-service.js.map +1 -0
  78. package/dist/services/oauth-token-retrieval.service.d.ts +49 -0
  79. package/dist/services/oauth-token-retrieval.service.d.ts.map +1 -0
  80. package/dist/services/oauth-token-retrieval.service.js +150 -0
  81. package/dist/services/oauth-token-retrieval.service.js.map +1 -0
  82. package/dist/services/provider-resolver.d.ts +48 -0
  83. package/dist/services/provider-resolver.d.ts.map +1 -0
  84. package/dist/services/provider-resolver.js +121 -0
  85. package/dist/services/provider-resolver.js.map +1 -0
  86. package/dist/services/provider-validator.d.ts +55 -0
  87. package/dist/services/provider-validator.d.ts.map +1 -0
  88. package/dist/services/provider-validator.js +135 -0
  89. package/dist/services/provider-validator.js.map +1 -0
  90. package/dist/services/session-registration.service.d.ts +80 -0
  91. package/dist/services/session-registration.service.d.ts.map +1 -0
  92. package/dist/services/session-registration.service.js +228 -0
  93. package/dist/services/session-registration.service.js.map +1 -0
  94. package/dist/services/tool-context-builder.d.ts +57 -0
  95. package/dist/services/tool-context-builder.d.ts.map +1 -0
  96. package/dist/services/tool-context-builder.js +125 -0
  97. package/dist/services/tool-context-builder.js.map +1 -0
  98. package/dist/services/tool-protection.service.d.ts +27 -0
  99. package/dist/services/tool-protection.service.d.ts.map +1 -1
  100. package/dist/services/tool-protection.service.js +194 -4
  101. package/dist/services/tool-protection.service.js.map +1 -1
  102. package/dist/types/oauth-required-error.d.ts +40 -0
  103. package/dist/types/oauth-required-error.d.ts.map +1 -0
  104. package/dist/types/oauth-required-error.js +40 -0
  105. package/dist/types/oauth-required-error.js.map +1 -0
  106. package/dist/utils/did-helpers.d.ts +33 -0
  107. package/dist/utils/did-helpers.d.ts.map +1 -1
  108. package/dist/utils/did-helpers.js +40 -0
  109. package/dist/utils/did-helpers.js.map +1 -1
  110. package/dist/utils/index.d.ts +1 -0
  111. package/dist/utils/index.d.ts.map +1 -1
  112. package/dist/utils/index.js +1 -0
  113. package/dist/utils/index.js.map +1 -1
  114. package/docs/API_REFERENCE.md +1362 -0
  115. package/docs/COMPLIANCE_MATRIX.md +691 -0
  116. package/docs/STATUSLIST2021_GUIDE.md +696 -0
  117. package/docs/W3C_VC_DELEGATION_GUIDE.md +710 -0
  118. package/package.json +23 -54
  119. package/scripts/audit-compliance.ts +724 -0
  120. package/src/__tests__/cache/tool-protection-cache.test.ts +640 -0
  121. package/src/__tests__/config/provider-runtime-config.test.ts +309 -0
  122. package/src/__tests__/delegation-e2e.test.ts +690 -0
  123. package/src/__tests__/identity/user-did-manager.test.ts +213 -0
  124. package/src/__tests__/index.test.ts +56 -0
  125. package/src/__tests__/integration/full-flow.test.ts +776 -0
  126. package/src/__tests__/integration.test.ts +281 -0
  127. package/src/__tests__/providers/base.test.ts +173 -0
  128. package/src/__tests__/providers/memory.test.ts +319 -0
  129. package/src/__tests__/regression/phase2-regression.test.ts +429 -0
  130. package/src/__tests__/runtime/audit-logger.test.ts +154 -0
  131. package/src/__tests__/runtime/base-extensions.test.ts +593 -0
  132. package/src/__tests__/runtime/base.test.ts +869 -0
  133. package/src/__tests__/runtime/delegation-flow.test.ts +164 -0
  134. package/src/__tests__/runtime/proof-client-did.test.ts +375 -0
  135. package/src/__tests__/runtime/route-interception.test.ts +686 -0
  136. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +908 -0
  137. package/src/__tests__/services/agentshield-integration.test.ts +784 -0
  138. package/src/__tests__/services/cache-busting.test.ts +125 -0
  139. package/src/__tests__/services/oauth-service-pkce.test.ts +556 -0
  140. package/src/__tests__/services/provider-resolver-edge-cases.test.ts +591 -0
  141. package/src/__tests__/services/tool-protection-oauth-provider.test.ts +480 -0
  142. package/src/__tests__/services/tool-protection.service.test.ts +1366 -0
  143. package/src/__tests__/utils/mock-providers.ts +340 -0
  144. package/src/cache/oauth-config-cache.d.ts +69 -0
  145. package/src/cache/oauth-config-cache.d.ts.map +1 -0
  146. package/src/cache/oauth-config-cache.js.map +1 -0
  147. package/src/cache/oauth-config-cache.ts +123 -0
  148. package/src/cache/tool-protection-cache.ts +171 -0
  149. package/src/compliance/EXAMPLE.md +412 -0
  150. package/src/compliance/__tests__/schema-verifier.test.ts +797 -0
  151. package/src/compliance/index.ts +8 -0
  152. package/src/compliance/schema-registry.ts +460 -0
  153. package/src/compliance/schema-verifier.ts +708 -0
  154. package/src/config/__tests__/remote-config.spec.ts +268 -0
  155. package/src/config/remote-config.ts +174 -0
  156. package/src/config.ts +309 -0
  157. package/src/delegation/__tests__/audience-validator.test.ts +112 -0
  158. package/src/delegation/__tests__/bitstring.test.ts +346 -0
  159. package/src/delegation/__tests__/cascading-revocation.test.ts +628 -0
  160. package/src/delegation/__tests__/delegation-graph.test.ts +584 -0
  161. package/src/delegation/__tests__/utils.test.ts +152 -0
  162. package/src/delegation/__tests__/vc-issuer.test.ts +442 -0
  163. package/src/delegation/__tests__/vc-verifier.test.ts +922 -0
  164. package/src/delegation/audience-validator.ts +52 -0
  165. package/src/delegation/bitstring.ts +278 -0
  166. package/src/delegation/cascading-revocation.ts +370 -0
  167. package/src/delegation/delegation-graph.ts +299 -0
  168. package/src/delegation/index.ts +14 -0
  169. package/src/delegation/statuslist-manager.ts +353 -0
  170. package/src/delegation/storage/__tests__/memory-graph-storage.test.ts +366 -0
  171. package/src/delegation/storage/__tests__/memory-statuslist-storage.test.ts +228 -0
  172. package/src/delegation/storage/index.ts +9 -0
  173. package/src/delegation/storage/memory-graph-storage.ts +178 -0
  174. package/src/delegation/storage/memory-statuslist-storage.ts +77 -0
  175. package/src/delegation/utils.ts +42 -0
  176. package/src/delegation/vc-issuer.ts +232 -0
  177. package/src/delegation/vc-verifier.ts +568 -0
  178. package/src/identity/idp-token-resolver.ts +147 -0
  179. package/src/identity/idp-token-storage.interface.ts +59 -0
  180. package/src/identity/user-did-manager.ts +370 -0
  181. package/src/index.ts +271 -0
  182. package/src/providers/base.d.ts +91 -0
  183. package/src/providers/base.d.ts.map +1 -0
  184. package/src/providers/base.js.map +1 -0
  185. package/src/providers/base.ts +96 -0
  186. package/src/providers/memory.ts +142 -0
  187. package/src/runtime/audit-logger.ts +39 -0
  188. package/src/runtime/base.ts +1329 -0
  189. package/src/services/__tests__/access-control.integration.test.ts +443 -0
  190. package/src/services/__tests__/access-control.proof-response-validation.test.ts +578 -0
  191. package/src/services/__tests__/access-control.service.test.ts +970 -0
  192. package/src/services/__tests__/batch-delegation.service.test.ts +351 -0
  193. package/src/services/__tests__/crypto.service.test.ts +531 -0
  194. package/src/services/__tests__/oauth-provider-registry.test.ts +142 -0
  195. package/src/services/__tests__/proof-verifier.integration.test.ts +485 -0
  196. package/src/services/__tests__/proof-verifier.test.ts +489 -0
  197. package/src/services/__tests__/provider-resolution.integration.test.ts +202 -0
  198. package/src/services/__tests__/provider-resolver.test.ts +213 -0
  199. package/src/services/__tests__/storage.service.test.ts +358 -0
  200. package/src/services/access-control.service.ts +990 -0
  201. package/src/services/authorization/authorization-registry.ts +66 -0
  202. package/src/services/authorization/types.ts +71 -0
  203. package/src/services/batch-delegation.service.ts +137 -0
  204. package/src/services/crypto.service.ts +302 -0
  205. package/src/services/errors.ts +76 -0
  206. package/src/services/index.ts +18 -0
  207. package/src/services/oauth-config.service.d.ts +53 -0
  208. package/src/services/oauth-config.service.d.ts.map +1 -0
  209. package/src/services/oauth-config.service.js.map +1 -0
  210. package/src/services/oauth-config.service.ts +192 -0
  211. package/src/services/oauth-provider-registry.d.ts +57 -0
  212. package/src/services/oauth-provider-registry.d.ts.map +1 -0
  213. package/src/services/oauth-provider-registry.js.map +1 -0
  214. package/src/services/oauth-provider-registry.ts +141 -0
  215. package/src/services/oauth-service.ts +544 -0
  216. package/src/services/oauth-token-retrieval.service.ts +245 -0
  217. package/src/services/proof-verifier.ts +478 -0
  218. package/src/services/provider-resolver.d.ts +48 -0
  219. package/src/services/provider-resolver.d.ts.map +1 -0
  220. package/src/services/provider-resolver.js.map +1 -0
  221. package/src/services/provider-resolver.ts +146 -0
  222. package/src/services/provider-validator.ts +170 -0
  223. package/src/services/session-registration.service.ts +317 -0
  224. package/src/services/storage.service.ts +566 -0
  225. package/src/services/tool-context-builder.ts +172 -0
  226. package/src/services/tool-protection.service.ts +982 -0
  227. package/src/types/oauth-required-error.ts +63 -0
  228. package/src/types/tool-protection.ts +155 -0
  229. package/src/utils/__tests__/did-helpers.test.ts +101 -0
  230. package/src/utils/base64.ts +148 -0
  231. package/src/utils/cors.ts +83 -0
  232. package/src/utils/did-helpers.ts +150 -0
  233. package/src/utils/index.ts +8 -0
  234. package/src/utils/storage-keys.ts +278 -0
  235. package/tsconfig.json +21 -0
  236. package/vitest.config.ts +56 -0
@@ -0,0 +1,544 @@
1
+ /**
2
+ * OAuth Service
3
+ *
4
+ * Handles OAuth token exchange and refresh using PKCE (Proof Key for Code Exchange).
5
+ * Supports both direct PKCE exchange with OAuth providers and proxy mode via AgentShield.
6
+ *
7
+ * @package @kya-os/mcp-i-core
8
+ */
9
+
10
+ import type { FetchProvider } from "../providers/base.js";
11
+ import type { OAuthConfigService } from "./oauth-config.service.js";
12
+ import type { IdpTokens, OAuthProvider } from "@kya-os/contracts/config";
13
+
14
+ export interface OAuthServiceConfig {
15
+ /** OAuth config service for fetching provider configurations */
16
+ configService: OAuthConfigService;
17
+
18
+ /** Fetch provider for making HTTP requests */
19
+ fetchProvider: FetchProvider;
20
+
21
+ /** AgentShield API URL (for proxy mode) */
22
+ agentShieldApiUrl: string;
23
+
24
+ /** AgentShield API key (for proxy mode) */
25
+ agentShieldApiKey: string;
26
+
27
+ /** Project ID for fetching OAuth config */
28
+ projectId: string;
29
+
30
+ /** Optional logger callback for diagnostics */
31
+ logger?: (message: string, data?: unknown) => void;
32
+ }
33
+
34
+ /**
35
+ * Service for OAuth token exchange and refresh
36
+ */
37
+ export class OAuthService {
38
+ private config: Required<Omit<OAuthServiceConfig, "logger">> & {
39
+ logger: (message: string, data?: unknown) => void;
40
+ };
41
+
42
+ constructor(config: OAuthServiceConfig) {
43
+ this.config = {
44
+ configService: config.configService,
45
+ fetchProvider: config.fetchProvider,
46
+ agentShieldApiUrl: config.agentShieldApiUrl,
47
+ agentShieldApiKey: config.agentShieldApiKey,
48
+ projectId: config.projectId,
49
+ logger: config.logger || (() => {}),
50
+ };
51
+ }
52
+
53
+ /**
54
+ * Exchange authorization code for IDP tokens using PKCE
55
+ *
56
+ * For PKCE providers: Exchanges code directly with OAuth provider (no client secret)
57
+ * For proxy mode: Exchanges code via AgentShield API
58
+ *
59
+ * @param provider - OAuth provider name (e.g., "github", "google")
60
+ * @param code - Authorization code from OAuth callback
61
+ * @param codeVerifier - PKCE code verifier (optional for non-PKCE providers in proxy mode)
62
+ * @param redirectUri - Redirect URI used in authorization request
63
+ * @returns IDP tokens (access_token, refresh_token, expires_at, etc.)
64
+ */
65
+ async exchangeToken(
66
+ provider: string,
67
+ code: string,
68
+ codeVerifier?: string,
69
+ redirectUri?: string
70
+ ): Promise<IdpTokens> {
71
+ // Fetch provider config
72
+ const oauthConfig = await this.config.configService.getOAuthConfig(
73
+ this.config.projectId
74
+ );
75
+ const providerConfig = oauthConfig.providers[provider];
76
+
77
+ if (!providerConfig) {
78
+ throw new Error(`Provider "${provider}" not configured for project "${this.config.projectId}"`);
79
+ }
80
+
81
+ // For PKCE providers, require codeVerifier
82
+ if (providerConfig.supportsPKCE && !providerConfig.proxyMode) {
83
+ if (!codeVerifier) {
84
+ throw new Error(
85
+ `Provider "${provider}" requires PKCE code_verifier for token exchange`
86
+ );
87
+ }
88
+ return this.exchangeTokenPKCE(
89
+ providerConfig,
90
+ code,
91
+ codeVerifier,
92
+ redirectUri || ""
93
+ );
94
+ }
95
+
96
+ // For proxy mode, codeVerifier is optional (only included if PKCE is supported)
97
+ if (providerConfig.proxyMode) {
98
+ return this.exchangeTokenProxy(
99
+ providerConfig,
100
+ code,
101
+ codeVerifier,
102
+ redirectUri || ""
103
+ );
104
+ }
105
+
106
+ throw new Error(
107
+ `Provider "${provider}" configuration is invalid: must support PKCE or use proxy mode`
108
+ );
109
+ }
110
+
111
+ /**
112
+ * Exchange token directly with OAuth provider using PKCE
113
+ */
114
+ private async exchangeTokenPKCE(
115
+ providerConfig: OAuthProvider,
116
+ code: string,
117
+ codeVerifier: string,
118
+ redirectUri: string
119
+ ): Promise<IdpTokens> {
120
+ this.config.logger("[OAuthService] Exchanging token with PKCE", {
121
+ provider: providerConfig.authorizationUrl,
122
+ tokenUrl: providerConfig.tokenUrl,
123
+ hasClientSecret: !!providerConfig.clientSecret,
124
+ });
125
+
126
+ // Build token exchange parameters
127
+ // Note: GitHub OAuth Apps require client_secret even with PKCE
128
+ // (GitHub Apps can use PKCE without client_secret, but OAuth Apps cannot)
129
+ const params: Record<string, string> = {
130
+ grant_type: "authorization_code",
131
+ code,
132
+ redirect_uri: redirectUri,
133
+ client_id: providerConfig.clientId,
134
+ code_verifier: codeVerifier,
135
+ };
136
+
137
+ // Include client_secret if provider has one configured
138
+ // This is required for GitHub OAuth Apps and other providers that need it
139
+ if (providerConfig.clientSecret) {
140
+ params.client_secret = providerConfig.clientSecret;
141
+ }
142
+
143
+ const response = await this.config.fetchProvider.fetch(providerConfig.tokenUrl, {
144
+ method: "POST",
145
+ headers: {
146
+ "Content-Type": "application/x-www-form-urlencoded",
147
+ Accept: "application/json",
148
+ },
149
+ body: new URLSearchParams(params).toString(),
150
+ });
151
+
152
+ if (!response.ok) {
153
+ const errorText = await response.text().catch(() => "Unknown error");
154
+ let errorData: any;
155
+ try {
156
+ errorData = JSON.parse(errorText);
157
+ } catch {
158
+ errorData = { error: errorText };
159
+ }
160
+
161
+ const errorMessage =
162
+ errorData.error_description || errorData.error || errorText;
163
+
164
+ this.config.logger("[OAuthService] Token exchange failed", {
165
+ status: response.status,
166
+ error: errorMessage,
167
+ provider: providerConfig.tokenUrl,
168
+ });
169
+
170
+ throw new Error(
171
+ `Token exchange failed: ${errorMessage} (${response.status})`
172
+ );
173
+ }
174
+
175
+ const tokens = await response.json() as {
176
+ access_token?: string;
177
+ refresh_token?: string;
178
+ expires_in?: number;
179
+ token_type?: string;
180
+ scope?: string;
181
+ // GitHub returns errors with 200 status!
182
+ error?: string;
183
+ error_description?: string;
184
+ error_uri?: string;
185
+ };
186
+
187
+ // GitHub returns errors with 200 status - check for error field first
188
+ if (tokens.error) {
189
+ this.config.logger("[OAuthService] Token exchange returned error (200 status)", {
190
+ error: tokens.error,
191
+ errorDescription: tokens.error_description,
192
+ errorUri: tokens.error_uri,
193
+ provider: providerConfig.tokenUrl,
194
+ responseKeys: Object.keys(tokens),
195
+ });
196
+ throw new Error(
197
+ `Token exchange failed: ${tokens.error_description || tokens.error}`
198
+ );
199
+ }
200
+
201
+ // Validate required fields
202
+ if (!tokens.access_token) {
203
+ this.config.logger("[OAuthService] Token response missing access_token", {
204
+ responseKeys: Object.keys(tokens),
205
+ provider: providerConfig.tokenUrl,
206
+ });
207
+ throw new Error("Token response missing access_token");
208
+ }
209
+
210
+ // Calculate expiration timestamp
211
+ const expiresIn = tokens.expires_in || 3600; // Default 1 hour
212
+ const expiresAt = Date.now() + expiresIn * 1000;
213
+
214
+ const idpTokens: IdpTokens = {
215
+ access_token: tokens.access_token,
216
+ refresh_token: tokens.refresh_token,
217
+ expires_in: expiresIn,
218
+ expires_at: expiresAt,
219
+ token_type: tokens.token_type || "Bearer",
220
+ scope: tokens.scope,
221
+ };
222
+
223
+ this.config.logger("[OAuthService] Token exchange successful", {
224
+ provider: providerConfig.tokenUrl,
225
+ expiresAt: new Date(expiresAt).toISOString(),
226
+ hasRefreshToken: !!idpTokens.refresh_token,
227
+ });
228
+
229
+ return idpTokens;
230
+ }
231
+
232
+ /**
233
+ * Exchange token via AgentShield proxy (for providers that require proxy mode)
234
+ *
235
+ * Note: For Phase 3 two-step flow, OAuth tokens are retrieved separately via
236
+ * OAuthTokenRetrievalService in the callback handler. This method maintains
237
+ * backward compatibility for direct proxy mode usage.
238
+ */
239
+ private async exchangeTokenProxy(
240
+ providerConfig: OAuthProvider,
241
+ code: string,
242
+ codeVerifier?: string,
243
+ redirectUri?: string
244
+ ): Promise<IdpTokens> {
245
+ // Exchange via AgentShield proxy endpoint
246
+ const proxyUrl = `${this.config.agentShieldApiUrl}/api/v1/oauth/token`;
247
+
248
+ this.config.logger("[OAuthService] Exchanging token via proxy", {
249
+ proxyUrl,
250
+ provider: providerConfig.authorizationUrl,
251
+ hasCodeVerifier: !!codeVerifier,
252
+ supportsPKCE: providerConfig.supportsPKCE,
253
+ });
254
+
255
+ // Build request body - only include code_verifier if PKCE is supported and provided
256
+ const requestBody: Record<string, string> = {
257
+ grant_type: "authorization_code",
258
+ code,
259
+ redirect_uri: redirectUri || "",
260
+ provider: providerConfig.authorizationUrl,
261
+ project_id: this.config.projectId,
262
+ };
263
+
264
+ // Include code_verifier only if provider supports PKCE and verifier is provided
265
+ if (providerConfig.supportsPKCE && codeVerifier) {
266
+ requestBody.code_verifier = codeVerifier;
267
+ }
268
+
269
+ const response = await this.config.fetchProvider.fetch(proxyUrl, {
270
+ method: "POST",
271
+ headers: {
272
+ "Content-Type": "application/json",
273
+ Authorization: `Bearer ${this.config.agentShieldApiKey}`,
274
+ },
275
+ body: JSON.stringify(requestBody),
276
+ });
277
+
278
+ if (!response.ok) {
279
+ const errorText = await response.text().catch(() => "Unknown error");
280
+ let errorData: any;
281
+ try {
282
+ errorData = JSON.parse(errorText);
283
+ } catch {
284
+ errorData = { error: errorText };
285
+ }
286
+
287
+ const errorMessage =
288
+ errorData.error_description || errorData.error || errorText;
289
+
290
+ this.config.logger("[OAuthService] Proxy token exchange failed", {
291
+ status: response.status,
292
+ error: errorMessage,
293
+ proxyUrl,
294
+ });
295
+
296
+ throw new Error(
297
+ `Proxy token exchange failed: ${errorMessage} (${response.status})`
298
+ );
299
+ }
300
+
301
+ const result = await response.json() as {
302
+ data?: {
303
+ access_token: string;
304
+ refresh_token?: string;
305
+ expires_in?: number;
306
+ token_type?: string;
307
+ scope?: string;
308
+ };
309
+ access_token?: string;
310
+ refresh_token?: string;
311
+ expires_in?: number;
312
+ token_type?: string;
313
+ scope?: string;
314
+ };
315
+ const tokens = result.data || result;
316
+
317
+ // Validate required fields
318
+ if (!tokens.access_token) {
319
+ throw new Error("Proxy token response missing access_token");
320
+ }
321
+
322
+ // Calculate expiration timestamp
323
+ const expiresIn = tokens.expires_in || 3600; // Default 1 hour
324
+ const expiresAt = Date.now() + expiresIn * 1000;
325
+
326
+ const idpTokens: IdpTokens = {
327
+ access_token: tokens.access_token,
328
+ refresh_token: tokens.refresh_token,
329
+ expires_in: expiresIn,
330
+ expires_at: expiresAt,
331
+ token_type: tokens.token_type || "Bearer",
332
+ scope: tokens.scope,
333
+ };
334
+
335
+ this.config.logger("[OAuthService] Proxy token exchange successful", {
336
+ proxyUrl,
337
+ expiresAt: new Date(expiresAt).toISOString(),
338
+ hasRefreshToken: !!idpTokens.refresh_token,
339
+ });
340
+
341
+ return idpTokens;
342
+ }
343
+
344
+ /**
345
+ * Refresh IDP access token using refresh token
346
+ *
347
+ * For PKCE providers: Refreshes directly with OAuth provider
348
+ * For proxy mode: Refreshes via AgentShield API
349
+ *
350
+ * @param provider - OAuth provider name
351
+ * @param refreshToken - Refresh token from previous token exchange
352
+ * @returns New IDP tokens or null if refresh failed
353
+ */
354
+ async refreshToken(
355
+ provider: string,
356
+ refreshToken: string
357
+ ): Promise<IdpTokens | null> {
358
+ // Fetch provider config
359
+ const oauthConfig = await this.config.configService.getOAuthConfig(
360
+ this.config.projectId
361
+ );
362
+ const providerConfig = oauthConfig.providers[provider];
363
+
364
+ if (!providerConfig) {
365
+ this.config.logger("[OAuthService] Provider not found for refresh", {
366
+ provider,
367
+ });
368
+ return null;
369
+ }
370
+
371
+ // For PKCE providers, refresh directly with OAuth provider
372
+ if (providerConfig.supportsPKCE && !providerConfig.proxyMode) {
373
+ return this.refreshTokenPKCE(providerConfig, refreshToken);
374
+ }
375
+
376
+ // For proxy mode, refresh via AgentShield
377
+ if (providerConfig.proxyMode) {
378
+ return this.refreshTokenProxy(providerConfig, refreshToken);
379
+ }
380
+
381
+ return null;
382
+ }
383
+
384
+ /**
385
+ * Refresh token directly with OAuth provider using PKCE
386
+ */
387
+ private async refreshTokenPKCE(
388
+ providerConfig: OAuthProvider,
389
+ refreshToken: string
390
+ ): Promise<IdpTokens | null> {
391
+ this.config.logger("[OAuthService] Refreshing token with PKCE", {
392
+ provider: providerConfig.tokenUrl,
393
+ });
394
+
395
+ try {
396
+ const response = await this.config.fetchProvider.fetch(providerConfig.tokenUrl, {
397
+ method: "POST",
398
+ headers: {
399
+ "Content-Type": "application/x-www-form-urlencoded",
400
+ Accept: "application/json",
401
+ },
402
+ body: new URLSearchParams({
403
+ grant_type: "refresh_token",
404
+ refresh_token: refreshToken,
405
+ client_id: providerConfig.clientId,
406
+ }).toString(),
407
+ });
408
+
409
+ if (!response.ok) {
410
+ this.config.logger("[OAuthService] Token refresh failed", {
411
+ status: response.status,
412
+ provider: providerConfig.tokenUrl,
413
+ });
414
+ return null;
415
+ }
416
+
417
+ const tokens = await response.json() as {
418
+ access_token: string;
419
+ refresh_token?: string;
420
+ expires_in?: number;
421
+ token_type?: string;
422
+ scope?: string;
423
+ };
424
+
425
+ if (!tokens.access_token) {
426
+ this.config.logger("[OAuthService] Token refresh response missing access_token");
427
+ return null;
428
+ }
429
+
430
+ // Calculate expiration timestamp
431
+ const expiresIn = tokens.expires_in || 3600; // Default 1 hour
432
+ const expiresAt = Date.now() + expiresIn * 1000;
433
+
434
+ const idpTokens: IdpTokens = {
435
+ access_token: tokens.access_token,
436
+ refresh_token: tokens.refresh_token || refreshToken, // Use new refresh token if provided, otherwise keep old one
437
+ expires_in: expiresIn,
438
+ expires_at: expiresAt,
439
+ token_type: tokens.token_type || "Bearer",
440
+ scope: tokens.scope,
441
+ };
442
+
443
+ this.config.logger("[OAuthService] Token refresh successful", {
444
+ provider: providerConfig.tokenUrl,
445
+ expiresAt: new Date(expiresAt).toISOString(),
446
+ });
447
+
448
+ return idpTokens;
449
+ } catch (error) {
450
+ this.config.logger("[OAuthService] Token refresh error", {
451
+ error: error instanceof Error ? error.message : String(error),
452
+ provider: providerConfig.tokenUrl,
453
+ });
454
+ return null;
455
+ }
456
+ }
457
+
458
+ /**
459
+ * Refresh token via AgentShield proxy
460
+ */
461
+ private async refreshTokenProxy(
462
+ providerConfig: OAuthProvider,
463
+ refreshToken: string
464
+ ): Promise<IdpTokens | null> {
465
+ const proxyUrl = `${this.config.agentShieldApiUrl}/api/v1/oauth/token`;
466
+
467
+ this.config.logger("[OAuthService] Refreshing token via proxy", {
468
+ proxyUrl,
469
+ provider: providerConfig.authorizationUrl,
470
+ });
471
+
472
+ try {
473
+ const response = await this.config.fetchProvider.fetch(proxyUrl, {
474
+ method: "POST",
475
+ headers: {
476
+ "Content-Type": "application/json",
477
+ Authorization: `Bearer ${this.config.agentShieldApiKey}`,
478
+ },
479
+ body: JSON.stringify({
480
+ grant_type: "refresh_token",
481
+ refresh_token: refreshToken,
482
+ provider: providerConfig.authorizationUrl,
483
+ project_id: this.config.projectId,
484
+ }),
485
+ });
486
+
487
+ if (!response.ok) {
488
+ this.config.logger("[OAuthService] Proxy token refresh failed", {
489
+ status: response.status,
490
+ proxyUrl,
491
+ });
492
+ return null;
493
+ }
494
+
495
+ const result = await response.json() as {
496
+ data?: {
497
+ access_token: string;
498
+ refresh_token?: string;
499
+ expires_in?: number;
500
+ token_type?: string;
501
+ scope?: string;
502
+ };
503
+ access_token?: string;
504
+ refresh_token?: string;
505
+ expires_in?: number;
506
+ token_type?: string;
507
+ scope?: string;
508
+ };
509
+ const tokens = result.data || result;
510
+
511
+ if (!tokens.access_token) {
512
+ this.config.logger("[OAuthService] Proxy token refresh response missing access_token");
513
+ return null;
514
+ }
515
+
516
+ // Calculate expiration timestamp
517
+ const expiresIn = tokens.expires_in || 3600; // Default 1 hour
518
+ const expiresAt = Date.now() + expiresIn * 1000;
519
+
520
+ const idpTokens: IdpTokens = {
521
+ access_token: tokens.access_token,
522
+ refresh_token: tokens.refresh_token || refreshToken,
523
+ expires_in: expiresIn,
524
+ expires_at: expiresAt,
525
+ token_type: tokens.token_type || "Bearer",
526
+ scope: tokens.scope,
527
+ };
528
+
529
+ this.config.logger("[OAuthService] Proxy token refresh successful", {
530
+ proxyUrl,
531
+ expiresAt: new Date(expiresAt).toISOString(),
532
+ });
533
+
534
+ return idpTokens;
535
+ } catch (error) {
536
+ this.config.logger("[OAuthService] Proxy token refresh error", {
537
+ error: error instanceof Error ? error.message : String(error),
538
+ proxyUrl,
539
+ });
540
+ return null;
541
+ }
542
+ }
543
+ }
544
+