@lobu/gateway 3.0.5 → 3.0.6

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 (175) hide show
  1. package/package.json +2 -2
  2. package/src/__tests__/agent-config-routes.test.ts +254 -0
  3. package/src/__tests__/agent-history-routes.test.ts +72 -0
  4. package/src/__tests__/agent-routes.test.ts +68 -0
  5. package/src/__tests__/agent-schedules-routes.test.ts +59 -0
  6. package/src/__tests__/agent-settings-store.test.ts +323 -0
  7. package/src/__tests__/chat-instance-manager-slack.test.ts +204 -0
  8. package/src/__tests__/chat-response-bridge.test.ts +131 -0
  9. package/src/__tests__/config-memory-plugins.test.ts +92 -0
  10. package/src/__tests__/config-request-store.test.ts +127 -0
  11. package/src/__tests__/connection-routes.test.ts +144 -0
  12. package/src/__tests__/core-services-store-selection.test.ts +92 -0
  13. package/src/__tests__/docker-deployment.test.ts +1211 -0
  14. package/src/__tests__/embedded-deployment.test.ts +342 -0
  15. package/src/__tests__/grant-store.test.ts +148 -0
  16. package/src/__tests__/http-proxy.test.ts +281 -0
  17. package/src/__tests__/instruction-service.test.ts +37 -0
  18. package/src/__tests__/link-buttons.test.ts +112 -0
  19. package/src/__tests__/lobu.test.ts +32 -0
  20. package/src/__tests__/mcp-config-service.test.ts +347 -0
  21. package/src/__tests__/mcp-proxy.test.ts +696 -0
  22. package/src/__tests__/message-handler-bridge.test.ts +17 -0
  23. package/src/__tests__/model-selection.test.ts +172 -0
  24. package/src/__tests__/oauth-templates.test.ts +39 -0
  25. package/src/__tests__/platform-adapter-slack-send.test.ts +114 -0
  26. package/src/__tests__/platform-helpers-model-resolution.test.ts +253 -0
  27. package/src/__tests__/provider-inheritance.test.ts +212 -0
  28. package/src/__tests__/routes/cli-auth.test.ts +337 -0
  29. package/src/__tests__/routes/interactions.test.ts +121 -0
  30. package/src/__tests__/secret-proxy.test.ts +85 -0
  31. package/src/__tests__/session-manager.test.ts +572 -0
  32. package/src/__tests__/setup.ts +133 -0
  33. package/src/__tests__/skill-and-mcp-registry.test.ts +203 -0
  34. package/src/__tests__/slack-routes.test.ts +161 -0
  35. package/src/__tests__/system-config-resolver.test.ts +75 -0
  36. package/src/__tests__/system-message-limiter.test.ts +89 -0
  37. package/src/__tests__/system-skills-service.test.ts +362 -0
  38. package/src/__tests__/transcription-service.test.ts +222 -0
  39. package/src/__tests__/utils/rate-limiter.test.ts +102 -0
  40. package/src/__tests__/worker-connection-manager.test.ts +497 -0
  41. package/src/__tests__/worker-job-router.test.ts +722 -0
  42. package/src/api/index.ts +1 -0
  43. package/src/api/platform.ts +292 -0
  44. package/src/api/response-renderer.ts +157 -0
  45. package/src/auth/agent-metadata-store.ts +168 -0
  46. package/src/auth/api-auth-middleware.ts +69 -0
  47. package/src/auth/api-key-provider-module.ts +213 -0
  48. package/src/auth/base-provider-module.ts +201 -0
  49. package/src/auth/chatgpt/chatgpt-oauth-module.ts +185 -0
  50. package/src/auth/chatgpt/device-code-client.ts +218 -0
  51. package/src/auth/chatgpt/index.ts +1 -0
  52. package/src/auth/claude/oauth-module.ts +280 -0
  53. package/src/auth/cli/token-service.ts +249 -0
  54. package/src/auth/external/client.ts +560 -0
  55. package/src/auth/external/device-code-client.ts +225 -0
  56. package/src/auth/mcp/config-service.ts +392 -0
  57. package/src/auth/mcp/proxy.ts +1088 -0
  58. package/src/auth/mcp/string-substitution.ts +17 -0
  59. package/src/auth/mcp/tool-cache.ts +90 -0
  60. package/src/auth/oauth/base-client.ts +267 -0
  61. package/src/auth/oauth/client.ts +153 -0
  62. package/src/auth/oauth/credentials.ts +7 -0
  63. package/src/auth/oauth/providers.ts +69 -0
  64. package/src/auth/oauth/state-store.ts +150 -0
  65. package/src/auth/oauth-templates.ts +179 -0
  66. package/src/auth/provider-catalog.ts +220 -0
  67. package/src/auth/provider-model-options.ts +41 -0
  68. package/src/auth/settings/agent-settings-store.ts +565 -0
  69. package/src/auth/settings/auth-profiles-manager.ts +216 -0
  70. package/src/auth/settings/index.ts +12 -0
  71. package/src/auth/settings/model-preference-store.ts +52 -0
  72. package/src/auth/settings/model-selection.ts +135 -0
  73. package/src/auth/settings/resolved-settings-view.ts +298 -0
  74. package/src/auth/settings/template-utils.ts +44 -0
  75. package/src/auth/settings/token-service.ts +88 -0
  76. package/src/auth/system-env-store.ts +98 -0
  77. package/src/auth/user-agents-store.ts +68 -0
  78. package/src/channels/binding-service.ts +214 -0
  79. package/src/channels/index.ts +4 -0
  80. package/src/cli/gateway.ts +1304 -0
  81. package/src/cli/index.ts +74 -0
  82. package/src/commands/built-in-commands.ts +80 -0
  83. package/src/commands/command-dispatcher.ts +94 -0
  84. package/src/commands/command-reply-adapters.ts +27 -0
  85. package/src/config/file-loader.ts +618 -0
  86. package/src/config/index.ts +588 -0
  87. package/src/config/network-allowlist.ts +71 -0
  88. package/src/connections/chat-instance-manager.ts +1284 -0
  89. package/src/connections/chat-response-bridge.ts +618 -0
  90. package/src/connections/index.ts +7 -0
  91. package/src/connections/interaction-bridge.ts +831 -0
  92. package/src/connections/message-handler-bridge.ts +415 -0
  93. package/src/connections/platform-auth-methods.ts +15 -0
  94. package/src/connections/types.ts +84 -0
  95. package/src/gateway/connection-manager.ts +291 -0
  96. package/src/gateway/index.ts +700 -0
  97. package/src/gateway/job-router.ts +201 -0
  98. package/src/gateway-main.ts +200 -0
  99. package/src/index.ts +41 -0
  100. package/src/infrastructure/queue/index.ts +12 -0
  101. package/src/infrastructure/queue/queue-producer.ts +148 -0
  102. package/src/infrastructure/queue/redis-queue.ts +361 -0
  103. package/src/infrastructure/queue/types.ts +133 -0
  104. package/src/infrastructure/redis/system-message-limiter.ts +94 -0
  105. package/src/interactions/config-request-store.ts +198 -0
  106. package/src/interactions.ts +363 -0
  107. package/src/lobu.ts +311 -0
  108. package/src/metrics/prometheus.ts +159 -0
  109. package/src/modules/module-system.ts +179 -0
  110. package/src/orchestration/base-deployment-manager.ts +900 -0
  111. package/src/orchestration/deployment-utils.ts +98 -0
  112. package/src/orchestration/impl/docker-deployment.ts +620 -0
  113. package/src/orchestration/impl/embedded-deployment.ts +268 -0
  114. package/src/orchestration/impl/index.ts +8 -0
  115. package/src/orchestration/impl/k8s/deployment.ts +1061 -0
  116. package/src/orchestration/impl/k8s/helpers.ts +610 -0
  117. package/src/orchestration/impl/k8s/index.ts +1 -0
  118. package/src/orchestration/index.ts +333 -0
  119. package/src/orchestration/message-consumer.ts +584 -0
  120. package/src/orchestration/scheduled-wakeup.ts +704 -0
  121. package/src/permissions/approval-policy.ts +36 -0
  122. package/src/permissions/grant-store.ts +219 -0
  123. package/src/platform/file-handler.ts +66 -0
  124. package/src/platform/link-buttons.ts +57 -0
  125. package/src/platform/renderer-utils.ts +44 -0
  126. package/src/platform/response-renderer.ts +84 -0
  127. package/src/platform/unified-thread-consumer.ts +187 -0
  128. package/src/platform.ts +318 -0
  129. package/src/proxy/http-proxy.ts +752 -0
  130. package/src/proxy/proxy-manager.ts +81 -0
  131. package/src/proxy/secret-proxy.ts +402 -0
  132. package/src/proxy/token-refresh-job.ts +143 -0
  133. package/src/routes/internal/audio.ts +141 -0
  134. package/src/routes/internal/device-auth.ts +566 -0
  135. package/src/routes/internal/files.ts +226 -0
  136. package/src/routes/internal/history.ts +69 -0
  137. package/src/routes/internal/images.ts +127 -0
  138. package/src/routes/internal/interactions.ts +84 -0
  139. package/src/routes/internal/middleware.ts +23 -0
  140. package/src/routes/internal/schedule.ts +226 -0
  141. package/src/routes/internal/types.ts +22 -0
  142. package/src/routes/openapi-auto.ts +239 -0
  143. package/src/routes/public/agent-access.ts +23 -0
  144. package/src/routes/public/agent-config.ts +675 -0
  145. package/src/routes/public/agent-history.ts +422 -0
  146. package/src/routes/public/agent-schedules.ts +296 -0
  147. package/src/routes/public/agent.ts +1086 -0
  148. package/src/routes/public/agents.ts +373 -0
  149. package/src/routes/public/channels.ts +191 -0
  150. package/src/routes/public/cli-auth.ts +883 -0
  151. package/src/routes/public/connections.ts +574 -0
  152. package/src/routes/public/landing.ts +16 -0
  153. package/src/routes/public/oauth.ts +147 -0
  154. package/src/routes/public/settings-auth.ts +104 -0
  155. package/src/routes/public/slack.ts +173 -0
  156. package/src/routes/shared/agent-ownership.ts +101 -0
  157. package/src/routes/shared/token-verifier.ts +34 -0
  158. package/src/services/core-services.ts +1053 -0
  159. package/src/services/image-generation-service.ts +257 -0
  160. package/src/services/instruction-service.ts +318 -0
  161. package/src/services/mcp-registry.ts +94 -0
  162. package/src/services/platform-helpers.ts +287 -0
  163. package/src/services/session-manager.ts +262 -0
  164. package/src/services/settings-resolver.ts +74 -0
  165. package/src/services/system-config-resolver.ts +90 -0
  166. package/src/services/system-skills-service.ts +229 -0
  167. package/src/services/transcription-service.ts +684 -0
  168. package/src/session.ts +110 -0
  169. package/src/spaces/index.ts +1 -0
  170. package/src/spaces/space-resolver.ts +17 -0
  171. package/src/stores/in-memory-agent-store.ts +403 -0
  172. package/src/stores/redis-agent-store.ts +279 -0
  173. package/src/utils/public-url.ts +44 -0
  174. package/src/utils/rate-limiter.ts +94 -0
  175. package/tsconfig.json +33 -0
@@ -0,0 +1,17 @@
1
+ let envResolver: ((key: string) => string | undefined) | null = null;
2
+
3
+ /**
4
+ * Register a custom env resolver that takes priority over process.env.
5
+ * Used by SystemEnvStore to inject Redis-backed env vars.
6
+ */
7
+ export function setEnvResolver(fn: (key: string) => string | undefined): void {
8
+ envResolver = fn;
9
+ }
10
+
11
+ /**
12
+ * Resolve an environment variable using the registered envResolver (Redis)
13
+ * with process.env as fallback. Reusable by provider modules.
14
+ */
15
+ export function resolveEnv(key: string): string | undefined {
16
+ return envResolver?.(key) ?? process.env[key];
17
+ }
@@ -0,0 +1,90 @@
1
+ import { createLogger } from "@lobu/core";
2
+
3
+ const logger = createLogger("mcp-tool-cache");
4
+
5
+ export interface McpTool {
6
+ name: string;
7
+ description?: string;
8
+ inputSchema?: Record<string, unknown>;
9
+ annotations?: {
10
+ readOnlyHint?: boolean;
11
+ destructiveHint?: boolean;
12
+ idempotentHint?: boolean;
13
+ openWorldHint?: boolean;
14
+ };
15
+ }
16
+
17
+ export interface CachedMcpServer {
18
+ tools: McpTool[];
19
+ instructions?: string;
20
+ }
21
+
22
+ const CACHE_TTL_SECONDS = 300; // 5 minutes
23
+
24
+ export class McpToolCache {
25
+ constructor(private readonly redisClient: any) {}
26
+
27
+ async get(mcpId: string, agentId?: string): Promise<McpTool[] | null> {
28
+ const info = await this.getServerInfo(mcpId, agentId);
29
+ return info ? info.tools : null;
30
+ }
31
+
32
+ async set(mcpId: string, tools: McpTool[], agentId?: string): Promise<void> {
33
+ await this.setServerInfo(mcpId, { tools }, agentId);
34
+ }
35
+
36
+ async getServerInfo(
37
+ mcpId: string,
38
+ agentId?: string
39
+ ): Promise<CachedMcpServer | null> {
40
+ const key = this.buildKey(mcpId, agentId);
41
+ try {
42
+ const cached = await this.redisClient.get(key);
43
+ if (cached) {
44
+ const parsed = JSON.parse(cached);
45
+ // Backward compat: if cached value is an array, it's old format (tools only)
46
+ if (Array.isArray(parsed)) {
47
+ return { tools: parsed as McpTool[] };
48
+ }
49
+ return parsed as CachedMcpServer;
50
+ }
51
+ return null;
52
+ } catch (error) {
53
+ logger.error("Failed to read tool cache", { key, error });
54
+ return null;
55
+ }
56
+ }
57
+
58
+ async setServerInfo(
59
+ mcpId: string,
60
+ info: CachedMcpServer,
61
+ agentId?: string
62
+ ): Promise<void> {
63
+ const key = this.buildKey(mcpId, agentId);
64
+ try {
65
+ await this.redisClient.set(
66
+ key,
67
+ JSON.stringify(info),
68
+ "EX",
69
+ CACHE_TTL_SECONDS
70
+ );
71
+ } catch (error) {
72
+ logger.error("Failed to write tool cache", { key, error });
73
+ }
74
+ }
75
+
76
+ async getInstructions(
77
+ mcpId: string,
78
+ agentId?: string
79
+ ): Promise<string | undefined> {
80
+ const info = await this.getServerInfo(mcpId, agentId);
81
+ return info?.instructions;
82
+ }
83
+
84
+ private buildKey(mcpId: string, agentId?: string): string {
85
+ if (agentId) {
86
+ return `mcp:tools:${agentId}:${mcpId}`;
87
+ }
88
+ return `mcp:tools:${mcpId}`;
89
+ }
90
+ }
@@ -0,0 +1,267 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { createLogger, type Logger } from "@lobu/core";
3
+
4
+ /**
5
+ * Base OAuth2 client with shared token exchange and refresh logic
6
+ * Supports standard OAuth 2.0 flows including PKCE (RFC 7636)
7
+ * Subclasses customize authorization URL building and request formatting
8
+ */
9
+ export abstract class BaseOAuth2Client {
10
+ protected logger: Logger;
11
+
12
+ constructor(loggerName: string) {
13
+ this.logger = createLogger(loggerName);
14
+ }
15
+
16
+ // ============================================================================
17
+ // PKCE Support (RFC 7636) - For public clients
18
+ // ============================================================================
19
+
20
+ /**
21
+ * Generate PKCE code verifier (43-128 characters, base64url encoded)
22
+ * Used for public OAuth clients (mobile apps, CLIs, SPAs)
23
+ */
24
+ generateCodeVerifier(): string {
25
+ return randomBytes(32).toString("base64url");
26
+ }
27
+
28
+ /**
29
+ * Generate PKCE code challenge from verifier using SHA256
30
+ * The challenge is sent in authorization request, verifier in token exchange
31
+ */
32
+ generateCodeChallenge(codeVerifier: string): string {
33
+ return createHash("sha256").update(codeVerifier).digest("base64url");
34
+ }
35
+
36
+ // ============================================================================
37
+ // Generic OAuth Token Operations
38
+ // ============================================================================
39
+
40
+ /**
41
+ * Generic refresh token method using provider configuration
42
+ * Supports both public clients (PKCE) and confidential clients (with secret)
43
+ *
44
+ * @param tokenUrl - Token endpoint URL
45
+ * @param clientId - OAuth client ID
46
+ * @param refreshToken - Refresh token from initial authorization
47
+ * @param options - Optional parameters (client secret, custom headers, content type)
48
+ */
49
+ async refreshTokenWithConfig<T>(
50
+ tokenUrl: string,
51
+ clientId: string,
52
+ refreshToken: string,
53
+ options?: {
54
+ clientSecret?: string;
55
+ customHeaders?: Record<string, string>;
56
+ contentType?: "json" | "form";
57
+ tokenEndpointAuthMethod?: string;
58
+ }
59
+ ): Promise<T> {
60
+ const body: Record<string, string> = {
61
+ grant_type: "refresh_token",
62
+ refresh_token: refreshToken,
63
+ client_id: clientId,
64
+ };
65
+
66
+ // Add client_secret if not using PKCE (tokenEndpointAuthMethod !== "none")
67
+ if (options?.clientSecret && options?.tokenEndpointAuthMethod !== "none") {
68
+ body.client_secret = options.clientSecret;
69
+ }
70
+
71
+ return this.refreshAccessToken<T>(
72
+ tokenUrl,
73
+ body,
74
+ options?.contentType || "json",
75
+ options?.customHeaders
76
+ );
77
+ }
78
+
79
+ // ============================================================================
80
+ // Low-level HTTP Operations (protected for subclasses)
81
+ // ============================================================================
82
+
83
+ /**
84
+ * Common token exchange implementation
85
+ * Subclasses must implement buildTokenExchangeRequest
86
+ */
87
+ protected async exchangeToken<T>(
88
+ tokenUrl: string,
89
+ requestBody: Record<string, string> | URLSearchParams,
90
+ contentType: "json" | "form" = "json",
91
+ additionalHeaders?: Record<string, string>
92
+ ): Promise<T> {
93
+ this.logger.info(`Exchanging code for token at ${tokenUrl}`, {
94
+ contentType,
95
+ });
96
+
97
+ try {
98
+ const body =
99
+ contentType === "json"
100
+ ? JSON.stringify(requestBody)
101
+ : requestBody instanceof URLSearchParams
102
+ ? requestBody.toString()
103
+ : new URLSearchParams(
104
+ requestBody as Record<string, string>
105
+ ).toString();
106
+
107
+ const headers: Record<string, string> = {
108
+ Accept: "application/json",
109
+ ...additionalHeaders,
110
+ };
111
+
112
+ if (contentType === "json") {
113
+ headers["Content-Type"] = "application/json";
114
+ } else {
115
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
116
+ }
117
+
118
+ this.logger.debug(`Token exchange request`, {
119
+ contentType,
120
+ tokenUrl,
121
+ });
122
+
123
+ const response = await fetch(tokenUrl, {
124
+ method: "POST",
125
+ headers,
126
+ body,
127
+ });
128
+
129
+ if (!response.ok) {
130
+ const errorText = await response.text();
131
+ this.logger.error(`Token exchange failed: ${response.status}`, {
132
+ errorText,
133
+ });
134
+ throw new Error(
135
+ `Token exchange failed: ${response.status} ${response.statusText}`
136
+ );
137
+ }
138
+
139
+ const responseContentType = response.headers.get("content-type") || "";
140
+ let tokenData: any;
141
+
142
+ // Parse response based on content type
143
+ if (responseContentType.includes("application/json")) {
144
+ tokenData = await response.json();
145
+ } else {
146
+ // Handle form-encoded responses (e.g., some OAuth providers)
147
+ const text = await response.text();
148
+ const params = new URLSearchParams(text);
149
+ tokenData = {
150
+ access_token: params.get("access_token") || "",
151
+ token_type: params.get("token_type") || "Bearer",
152
+ expires_in: params.get("expires_in")
153
+ ? parseInt(params.get("expires_in")!, 10)
154
+ : undefined,
155
+ refresh_token: params.get("refresh_token") || undefined,
156
+ scope: params.get("scope") || undefined,
157
+ };
158
+ }
159
+
160
+ // Check for OAuth error response
161
+ if ("error" in tokenData) {
162
+ throw new Error(
163
+ `OAuth error: ${tokenData.error} - ${tokenData.error_description || ""}`
164
+ );
165
+ }
166
+
167
+ if (!tokenData.access_token) {
168
+ throw new Error("No access token in response");
169
+ }
170
+
171
+ this.logger.info(
172
+ `Token exchange successful, expires_in: ${tokenData.expires_in}s`
173
+ );
174
+
175
+ return tokenData as T;
176
+ } catch (error) {
177
+ this.logger.error("Token exchange failed", { error });
178
+ throw error;
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Common token refresh implementation
184
+ * Subclasses must implement buildRefreshRequest
185
+ */
186
+ protected async refreshAccessToken<T>(
187
+ tokenUrl: string,
188
+ requestBody: Record<string, string> | URLSearchParams,
189
+ contentType: "json" | "form" = "json",
190
+ additionalHeaders?: Record<string, string>
191
+ ): Promise<T> {
192
+ this.logger.info(`Refreshing token at ${tokenUrl}`);
193
+
194
+ try {
195
+ const body =
196
+ contentType === "json"
197
+ ? JSON.stringify(requestBody)
198
+ : requestBody instanceof URLSearchParams
199
+ ? requestBody.toString()
200
+ : new URLSearchParams(
201
+ requestBody as Record<string, string>
202
+ ).toString();
203
+
204
+ const headers: Record<string, string> = {
205
+ Accept: "application/json",
206
+ ...additionalHeaders,
207
+ };
208
+
209
+ if (contentType === "json") {
210
+ headers["Content-Type"] = "application/json";
211
+ } else {
212
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
213
+ }
214
+
215
+ const response = await fetch(tokenUrl, {
216
+ method: "POST",
217
+ headers,
218
+ body,
219
+ });
220
+
221
+ if (!response.ok) {
222
+ const errorText = await response.text();
223
+ this.logger.error(`Token refresh failed: ${response.status}`, {
224
+ errorText,
225
+ });
226
+ throw new Error(
227
+ `Token refresh failed: ${response.status} ${response.statusText}`
228
+ );
229
+ }
230
+
231
+ const tokenData = (await response.json()) as any;
232
+
233
+ if ("error" in tokenData) {
234
+ throw new Error(
235
+ `OAuth error: ${tokenData.error} - ${tokenData.error_description || ""}`
236
+ );
237
+ }
238
+
239
+ if (!tokenData.access_token) {
240
+ throw new Error("No access token in refresh response");
241
+ }
242
+
243
+ this.logger.info(
244
+ `Token refresh successful, expires_in: ${tokenData.expires_in}s`
245
+ );
246
+
247
+ return tokenData as T;
248
+ } catch (error) {
249
+ this.logger.error("Token refresh failed", { error });
250
+ throw error;
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Calculate token expiration timestamp
256
+ */
257
+ protected calculateExpiresAt(expiresIn?: number): number | undefined {
258
+ return expiresIn ? Date.now() + expiresIn * 1000 : undefined;
259
+ }
260
+
261
+ /**
262
+ * Parse scopes from string or array
263
+ */
264
+ protected parseScopes(scope?: string): string[] {
265
+ return scope ? scope.split(" ") : [];
266
+ }
267
+ }
@@ -0,0 +1,153 @@
1
+ import { BaseOAuth2Client } from "./base-client";
2
+ import type { OAuthCredentials } from "./credentials";
3
+ import type { OAuthProviderConfig } from "./providers";
4
+
5
+ interface OAuthTokenResponse {
6
+ access_token: string;
7
+ refresh_token?: string;
8
+ token_type?: string;
9
+ expires_in: number;
10
+ scope?: string;
11
+ }
12
+
13
+ /**
14
+ * Config-driven OAuth client for any provider
15
+ * Extends BaseOAuth2Client with provider configuration
16
+ *
17
+ * Features:
18
+ * - PKCE support (RFC 7636) for public client security
19
+ * - Browser-like headers for anti-bot protection
20
+ * - Configurable via OAuthProviderConfig
21
+ */
22
+ export class OAuthClient extends BaseOAuth2Client {
23
+ private config: OAuthProviderConfig;
24
+
25
+ constructor(config: OAuthProviderConfig) {
26
+ super(`${config.id ?? "oauth"}-client`);
27
+ this.config = config;
28
+ }
29
+
30
+ /**
31
+ * Build authorization URL with PKCE parameters
32
+ */
33
+ buildAuthUrl(
34
+ state: string,
35
+ codeVerifier: string,
36
+ customRedirectUri?: string
37
+ ): string {
38
+ const codeChallenge = this.generateCodeChallenge(codeVerifier);
39
+ const redirectUri = customRedirectUri || this.config.redirectUri;
40
+
41
+ const url = new URL(this.config.authUrl);
42
+ url.searchParams.set("client_id", this.config.clientId);
43
+ url.searchParams.set("redirect_uri", redirectUri);
44
+ url.searchParams.set("response_type", this.config.responseType || "code");
45
+ url.searchParams.set("state", state);
46
+ url.searchParams.set("scope", this.config.scope);
47
+ url.searchParams.set("code_challenge", codeChallenge);
48
+ url.searchParams.set("code_challenge_method", "S256");
49
+
50
+ return url.toString();
51
+ }
52
+
53
+ /**
54
+ * Exchange authorization code for access token using PKCE
55
+ */
56
+ async exchangeCodeForToken(
57
+ code: string,
58
+ codeVerifier: string,
59
+ customRedirectUri?: string,
60
+ state?: string
61
+ ): Promise<OAuthCredentials> {
62
+ const redirectUri = customRedirectUri || this.config.redirectUri;
63
+
64
+ const body: Record<string, string> = {
65
+ grant_type: this.config.grantType || "authorization_code",
66
+ client_id: this.config.clientId,
67
+ code,
68
+ redirect_uri: redirectUri,
69
+ code_verifier: codeVerifier,
70
+ };
71
+
72
+ // Include state if provided (required by Claude OAuth)
73
+ if (state) {
74
+ body.state = state;
75
+ }
76
+
77
+ // Add provider-specific custom headers
78
+ const tokenData = await this.exchangeToken<OAuthTokenResponse>(
79
+ this.config.tokenUrl,
80
+ body,
81
+ "json",
82
+ this.config.customHeaders
83
+ );
84
+
85
+ const credentials = this.buildCredentials(tokenData);
86
+ this.logger.info(
87
+ `Token exchange successful, expires_in: ${tokenData.expires_in}s`,
88
+ { scopes: credentials.scopes }
89
+ );
90
+
91
+ return credentials;
92
+ }
93
+
94
+ /**
95
+ * Refresh access token using refresh token
96
+ * Uses generic refresh method from base client with Claude-specific config
97
+ */
98
+ async refreshToken(refreshToken: string): Promise<OAuthCredentials> {
99
+ const tokenData = await this.refreshTokenWithConfig<OAuthTokenResponse>(
100
+ this.config.tokenUrl,
101
+ this.config.clientId,
102
+ refreshToken,
103
+ {
104
+ customHeaders: this.config.customHeaders,
105
+ contentType: "json",
106
+ tokenEndpointAuthMethod: this.config.tokenEndpointAuthMethod,
107
+ }
108
+ );
109
+
110
+ const credentials = this.buildCredentials(tokenData, refreshToken);
111
+ this.logger.info(
112
+ `Token refresh successful, expires_in: ${tokenData.expires_in}s`
113
+ );
114
+
115
+ return credentials;
116
+ }
117
+
118
+ private buildCredentials(
119
+ tokenData: {
120
+ access_token: string;
121
+ refresh_token?: string;
122
+ token_type?: string;
123
+ expires_in: number;
124
+ scope?: string;
125
+ },
126
+ fallbackRefreshToken?: string
127
+ ): OAuthCredentials {
128
+ const expiresAt = this.calculateExpiresAt(tokenData.expires_in)!;
129
+ const scopes = this.parseScopes(tokenData.scope);
130
+ const refreshToken = tokenData.refresh_token ?? fallbackRefreshToken;
131
+
132
+ if (!refreshToken && this.config.requireRefreshToken !== false) {
133
+ throw new Error(
134
+ `${this.config.name} OAuth response missing refresh token`
135
+ );
136
+ }
137
+
138
+ return {
139
+ accessToken: tokenData.access_token,
140
+ refreshToken,
141
+ tokenType: tokenData.token_type || "Bearer",
142
+ expiresAt,
143
+ scopes,
144
+ };
145
+ }
146
+
147
+ /**
148
+ * Get the provider configuration (useful for debugging)
149
+ */
150
+ getConfig(): OAuthProviderConfig {
151
+ return { ...this.config };
152
+ }
153
+ }
@@ -0,0 +1,7 @@
1
+ export interface OAuthCredentials {
2
+ accessToken: string;
3
+ refreshToken?: string;
4
+ tokenType: string;
5
+ expiresAt: number; // Unix timestamp in milliseconds
6
+ scopes: string[];
7
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * OAuth 2.0 Provider Configurations
3
+ *
4
+ * Centralizes OAuth provider settings for easy addition of new providers.
5
+ * Each provider defines its endpoints, client credentials, and OAuth-specific settings.
6
+ */
7
+
8
+ export interface OAuthProviderConfig {
9
+ /** Unique provider identifier */
10
+ id: string;
11
+ /** Human-readable provider name */
12
+ name: string;
13
+ /** OAuth 2.0 client ID (public identifier) */
14
+ clientId: string;
15
+ /** OAuth 2.0 client secret (optional - not used for public clients with PKCE) */
16
+ clientSecret?: string;
17
+ /** Authorization endpoint URL */
18
+ authUrl: string;
19
+ /** Token exchange endpoint URL */
20
+ tokenUrl: string;
21
+ /** OAuth redirect URI */
22
+ redirectUri: string;
23
+ /** OAuth scopes (space-separated) */
24
+ scope: string;
25
+ /** Use PKCE for public clients (RFC 7636) */
26
+ usePKCE: boolean;
27
+ /** Response type (default: "code") */
28
+ responseType?: string;
29
+ /** Grant type (default: "authorization_code") */
30
+ grantType?: string;
31
+ /** Custom headers to include in token requests */
32
+ customHeaders?: Record<string, string>;
33
+ /** Token endpoint auth method */
34
+ tokenEndpointAuthMethod?:
35
+ | "none"
36
+ | "client_secret_post"
37
+ | "client_secret_basic";
38
+ /** Whether auth-code exchange must include refresh_token */
39
+ requireRefreshToken?: boolean;
40
+ }
41
+
42
+ /**
43
+ * Claude OAuth Configuration
44
+ * - Public client (no client secret)
45
+ * - Uses PKCE for security
46
+ * - Requires browser-like headers (anti-bot protection)
47
+ */
48
+ export const CLAUDE_PROVIDER: OAuthProviderConfig = {
49
+ id: "claude",
50
+ name: "Claude",
51
+ clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
52
+ authUrl: "https://claude.ai/oauth/authorize",
53
+ tokenUrl: "https://console.anthropic.com/v1/oauth/token",
54
+ redirectUri: "https://console.anthropic.com/oauth/code/callback",
55
+ scope: "user:inference",
56
+ usePKCE: true,
57
+ responseType: "code",
58
+ grantType: "authorization_code",
59
+ tokenEndpointAuthMethod: "none",
60
+ requireRefreshToken: true,
61
+ customHeaders: {
62
+ "User-Agent":
63
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
64
+ Accept: "application/json, text/plain, */*",
65
+ "Accept-Language": "en-US,en;q=0.9",
66
+ Referer: "https://claude.ai/",
67
+ Origin: "https://claude.ai",
68
+ },
69
+ };