@lobu/gateway 3.0.9 → 3.0.12

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 (210) hide show
  1. package/dist/api/platform.d.ts.map +1 -1
  2. package/dist/api/platform.js +7 -26
  3. package/dist/api/platform.js.map +1 -1
  4. package/dist/auth/mcp/proxy.d.ts +14 -0
  5. package/dist/auth/mcp/proxy.d.ts.map +1 -1
  6. package/dist/auth/mcp/proxy.js +149 -13
  7. package/dist/auth/mcp/proxy.js.map +1 -1
  8. package/dist/cli/gateway.d.ts.map +1 -1
  9. package/dist/cli/gateway.js +29 -0
  10. package/dist/cli/gateway.js.map +1 -1
  11. package/dist/connections/chat-instance-manager.d.ts.map +1 -1
  12. package/dist/connections/chat-instance-manager.js +2 -1
  13. package/dist/connections/chat-instance-manager.js.map +1 -1
  14. package/dist/connections/interaction-bridge.d.ts +9 -2
  15. package/dist/connections/interaction-bridge.d.ts.map +1 -1
  16. package/dist/connections/interaction-bridge.js +121 -261
  17. package/dist/connections/interaction-bridge.js.map +1 -1
  18. package/dist/interactions.d.ts +9 -43
  19. package/dist/interactions.d.ts.map +1 -1
  20. package/dist/interactions.js +10 -52
  21. package/dist/interactions.js.map +1 -1
  22. package/dist/routes/public/agent.d.ts +4 -0
  23. package/dist/routes/public/agent.d.ts.map +1 -1
  24. package/dist/routes/public/agent.js +21 -0
  25. package/dist/routes/public/agent.js.map +1 -1
  26. package/dist/services/core-services.d.ts.map +1 -1
  27. package/dist/services/core-services.js +4 -0
  28. package/dist/services/core-services.js.map +1 -1
  29. package/package.json +9 -9
  30. package/src/__tests__/agent-config-routes.test.ts +0 -254
  31. package/src/__tests__/agent-history-routes.test.ts +0 -72
  32. package/src/__tests__/agent-routes.test.ts +0 -68
  33. package/src/__tests__/agent-schedules-routes.test.ts +0 -59
  34. package/src/__tests__/agent-settings-store.test.ts +0 -323
  35. package/src/__tests__/bedrock-model-catalog.test.ts +0 -40
  36. package/src/__tests__/bedrock-openai-service.test.ts +0 -157
  37. package/src/__tests__/bedrock-provider-module.test.ts +0 -56
  38. package/src/__tests__/chat-instance-manager-slack.test.ts +0 -204
  39. package/src/__tests__/chat-response-bridge.test.ts +0 -131
  40. package/src/__tests__/config-memory-plugins.test.ts +0 -92
  41. package/src/__tests__/config-request-store.test.ts +0 -127
  42. package/src/__tests__/connection-routes.test.ts +0 -144
  43. package/src/__tests__/core-services-store-selection.test.ts +0 -92
  44. package/src/__tests__/docker-deployment.test.ts +0 -1211
  45. package/src/__tests__/embedded-deployment.test.ts +0 -342
  46. package/src/__tests__/grant-store.test.ts +0 -148
  47. package/src/__tests__/http-proxy.test.ts +0 -281
  48. package/src/__tests__/instruction-service.test.ts +0 -37
  49. package/src/__tests__/link-buttons.test.ts +0 -112
  50. package/src/__tests__/lobu.test.ts +0 -32
  51. package/src/__tests__/mcp-config-service.test.ts +0 -347
  52. package/src/__tests__/mcp-proxy.test.ts +0 -694
  53. package/src/__tests__/message-handler-bridge.test.ts +0 -17
  54. package/src/__tests__/model-selection.test.ts +0 -172
  55. package/src/__tests__/oauth-templates.test.ts +0 -39
  56. package/src/__tests__/platform-adapter-slack-send.test.ts +0 -114
  57. package/src/__tests__/platform-helpers-model-resolution.test.ts +0 -253
  58. package/src/__tests__/provider-inheritance.test.ts +0 -212
  59. package/src/__tests__/routes/cli-auth.test.ts +0 -337
  60. package/src/__tests__/routes/interactions.test.ts +0 -121
  61. package/src/__tests__/secret-proxy.test.ts +0 -85
  62. package/src/__tests__/session-manager.test.ts +0 -572
  63. package/src/__tests__/setup.ts +0 -133
  64. package/src/__tests__/skill-and-mcp-registry.test.ts +0 -203
  65. package/src/__tests__/slack-routes.test.ts +0 -161
  66. package/src/__tests__/system-config-resolver.test.ts +0 -75
  67. package/src/__tests__/system-message-limiter.test.ts +0 -89
  68. package/src/__tests__/system-skills-service.test.ts +0 -362
  69. package/src/__tests__/transcription-service.test.ts +0 -222
  70. package/src/__tests__/utils/rate-limiter.test.ts +0 -102
  71. package/src/__tests__/worker-connection-manager.test.ts +0 -497
  72. package/src/__tests__/worker-job-router.test.ts +0 -722
  73. package/src/api/index.ts +0 -1
  74. package/src/api/platform.ts +0 -292
  75. package/src/api/response-renderer.ts +0 -157
  76. package/src/auth/agent-metadata-store.ts +0 -168
  77. package/src/auth/api-auth-middleware.ts +0 -69
  78. package/src/auth/api-key-provider-module.ts +0 -213
  79. package/src/auth/base-provider-module.ts +0 -201
  80. package/src/auth/bedrock/provider-module.ts +0 -110
  81. package/src/auth/chatgpt/chatgpt-oauth-module.ts +0 -185
  82. package/src/auth/chatgpt/device-code-client.ts +0 -218
  83. package/src/auth/chatgpt/index.ts +0 -1
  84. package/src/auth/claude/oauth-module.ts +0 -280
  85. package/src/auth/cli/token-service.ts +0 -249
  86. package/src/auth/external/client.ts +0 -560
  87. package/src/auth/external/device-code-client.ts +0 -235
  88. package/src/auth/mcp/config-service.ts +0 -420
  89. package/src/auth/mcp/proxy.ts +0 -1086
  90. package/src/auth/mcp/string-substitution.ts +0 -17
  91. package/src/auth/mcp/tool-cache.ts +0 -90
  92. package/src/auth/oauth/base-client.ts +0 -267
  93. package/src/auth/oauth/client.ts +0 -153
  94. package/src/auth/oauth/credentials.ts +0 -7
  95. package/src/auth/oauth/providers.ts +0 -69
  96. package/src/auth/oauth/state-store.ts +0 -150
  97. package/src/auth/oauth-templates.ts +0 -179
  98. package/src/auth/provider-catalog.ts +0 -220
  99. package/src/auth/provider-model-options.ts +0 -41
  100. package/src/auth/settings/agent-settings-store.ts +0 -565
  101. package/src/auth/settings/auth-profiles-manager.ts +0 -216
  102. package/src/auth/settings/index.ts +0 -12
  103. package/src/auth/settings/model-preference-store.ts +0 -52
  104. package/src/auth/settings/model-selection.ts +0 -135
  105. package/src/auth/settings/resolved-settings-view.ts +0 -298
  106. package/src/auth/settings/template-utils.ts +0 -44
  107. package/src/auth/settings/token-service.ts +0 -88
  108. package/src/auth/system-env-store.ts +0 -98
  109. package/src/auth/user-agents-store.ts +0 -68
  110. package/src/channels/binding-service.ts +0 -214
  111. package/src/channels/index.ts +0 -4
  112. package/src/cli/gateway.ts +0 -1312
  113. package/src/cli/index.ts +0 -74
  114. package/src/commands/built-in-commands.ts +0 -80
  115. package/src/commands/command-dispatcher.ts +0 -94
  116. package/src/commands/command-reply-adapters.ts +0 -27
  117. package/src/config/file-loader.ts +0 -618
  118. package/src/config/index.ts +0 -588
  119. package/src/config/network-allowlist.ts +0 -71
  120. package/src/connections/chat-instance-manager.ts +0 -1284
  121. package/src/connections/chat-response-bridge.ts +0 -618
  122. package/src/connections/index.ts +0 -7
  123. package/src/connections/interaction-bridge.ts +0 -831
  124. package/src/connections/message-handler-bridge.ts +0 -440
  125. package/src/connections/platform-auth-methods.ts +0 -15
  126. package/src/connections/types.ts +0 -84
  127. package/src/gateway/connection-manager.ts +0 -291
  128. package/src/gateway/index.ts +0 -698
  129. package/src/gateway/job-router.ts +0 -201
  130. package/src/gateway-main.ts +0 -200
  131. package/src/index.ts +0 -41
  132. package/src/infrastructure/queue/index.ts +0 -12
  133. package/src/infrastructure/queue/queue-producer.ts +0 -148
  134. package/src/infrastructure/queue/redis-queue.ts +0 -361
  135. package/src/infrastructure/queue/types.ts +0 -133
  136. package/src/infrastructure/redis/system-message-limiter.ts +0 -94
  137. package/src/interactions/config-request-store.ts +0 -198
  138. package/src/interactions.ts +0 -363
  139. package/src/lobu.ts +0 -311
  140. package/src/metrics/prometheus.ts +0 -159
  141. package/src/modules/module-system.ts +0 -179
  142. package/src/orchestration/base-deployment-manager.ts +0 -900
  143. package/src/orchestration/deployment-utils.ts +0 -98
  144. package/src/orchestration/impl/docker-deployment.ts +0 -620
  145. package/src/orchestration/impl/embedded-deployment.ts +0 -268
  146. package/src/orchestration/impl/index.ts +0 -8
  147. package/src/orchestration/impl/k8s/deployment.ts +0 -1061
  148. package/src/orchestration/impl/k8s/helpers.ts +0 -610
  149. package/src/orchestration/impl/k8s/index.ts +0 -1
  150. package/src/orchestration/index.ts +0 -333
  151. package/src/orchestration/message-consumer.ts +0 -584
  152. package/src/orchestration/scheduled-wakeup.ts +0 -704
  153. package/src/permissions/approval-policy.ts +0 -36
  154. package/src/permissions/grant-store.ts +0 -219
  155. package/src/platform/file-handler.ts +0 -66
  156. package/src/platform/link-buttons.ts +0 -57
  157. package/src/platform/renderer-utils.ts +0 -44
  158. package/src/platform/response-renderer.ts +0 -84
  159. package/src/platform/unified-thread-consumer.ts +0 -194
  160. package/src/platform.ts +0 -318
  161. package/src/proxy/http-proxy.ts +0 -752
  162. package/src/proxy/proxy-manager.ts +0 -81
  163. package/src/proxy/secret-proxy.ts +0 -402
  164. package/src/proxy/token-refresh-job.ts +0 -143
  165. package/src/routes/internal/audio.ts +0 -141
  166. package/src/routes/internal/device-auth.ts +0 -652
  167. package/src/routes/internal/files.ts +0 -226
  168. package/src/routes/internal/history.ts +0 -69
  169. package/src/routes/internal/images.ts +0 -127
  170. package/src/routes/internal/interactions.ts +0 -84
  171. package/src/routes/internal/middleware.ts +0 -23
  172. package/src/routes/internal/schedule.ts +0 -226
  173. package/src/routes/internal/types.ts +0 -22
  174. package/src/routes/openapi-auto.ts +0 -239
  175. package/src/routes/public/agent-access.ts +0 -23
  176. package/src/routes/public/agent-config.ts +0 -675
  177. package/src/routes/public/agent-history.ts +0 -422
  178. package/src/routes/public/agent-schedules.ts +0 -296
  179. package/src/routes/public/agent.ts +0 -1086
  180. package/src/routes/public/agents.ts +0 -373
  181. package/src/routes/public/channels.ts +0 -191
  182. package/src/routes/public/cli-auth.ts +0 -896
  183. package/src/routes/public/connections.ts +0 -574
  184. package/src/routes/public/landing.ts +0 -16
  185. package/src/routes/public/oauth.ts +0 -147
  186. package/src/routes/public/settings-auth.ts +0 -104
  187. package/src/routes/public/slack.ts +0 -173
  188. package/src/routes/shared/agent-ownership.ts +0 -101
  189. package/src/routes/shared/token-verifier.ts +0 -34
  190. package/src/services/bedrock-model-catalog.ts +0 -217
  191. package/src/services/bedrock-openai-service.ts +0 -658
  192. package/src/services/core-services.ts +0 -1072
  193. package/src/services/image-generation-service.ts +0 -257
  194. package/src/services/instruction-service.ts +0 -318
  195. package/src/services/mcp-registry.ts +0 -94
  196. package/src/services/platform-helpers.ts +0 -287
  197. package/src/services/session-manager.ts +0 -262
  198. package/src/services/settings-resolver.ts +0 -74
  199. package/src/services/system-config-resolver.ts +0 -89
  200. package/src/services/system-skills-service.ts +0 -229
  201. package/src/services/transcription-service.ts +0 -684
  202. package/src/session.ts +0 -110
  203. package/src/spaces/index.ts +0 -1
  204. package/src/spaces/space-resolver.ts +0 -17
  205. package/src/stores/in-memory-agent-store.ts +0 -403
  206. package/src/stores/redis-agent-store.ts +0 -279
  207. package/src/utils/public-url.ts +0 -44
  208. package/src/utils/rate-limiter.ts +0 -94
  209. package/tsconfig.json +0 -33
  210. package/tsconfig.tsbuildinfo +0 -1
@@ -1,17 +0,0 @@
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
- }
@@ -1,90 +0,0 @@
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
- }
@@ -1,267 +0,0 @@
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
- }
@@ -1,153 +0,0 @@
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
- }
@@ -1,7 +0,0 @@
1
- export interface OAuthCredentials {
2
- accessToken: string;
3
- refreshToken?: string;
4
- tokenType: string;
5
- expiresAt: number; // Unix timestamp in milliseconds
6
- scopes: string[];
7
- }
@@ -1,69 +0,0 @@
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
- };