@lobu/gateway 3.0.5 → 3.0.7

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,81 @@
1
+ import { existsSync } from "node:fs";
2
+ import type { Server } from "node:http";
3
+ import { createLogger } from "@lobu/core";
4
+ import { startHttpProxy, stopHttpProxy } from "./http-proxy";
5
+
6
+ const logger = createLogger("proxy-manager");
7
+
8
+ let proxyServer: Server | null = null;
9
+
10
+ /**
11
+ * Determine the bind host for the proxy.
12
+ * DEPLOYMENT_MODE=docker is expected to run inside a container. Fail fast if not,
13
+ * then bind to all interfaces so workers on lobu-internal can connect.
14
+ */
15
+ function getProxyBindHost(): string {
16
+ const deploymentMode = process.env.DEPLOYMENT_MODE;
17
+
18
+ if (deploymentMode === "docker") {
19
+ const runningInContainer =
20
+ existsSync("/.dockerenv") || existsSync("/run/.containerenv");
21
+ if (!runningInContainer) {
22
+ throw new Error(
23
+ "DEPLOYMENT_MODE=docker requires gateway to run inside a container"
24
+ );
25
+ }
26
+ }
27
+
28
+ // Docker Compose / K8s: bind to all interfaces
29
+ return "::";
30
+ }
31
+
32
+ /**
33
+ * Start filtering HTTP proxy for worker network isolation
34
+ * Workers can only access internet via this proxy, which enforces domain allowlist/blocklist
35
+ *
36
+ * Behavior based on environment configuration:
37
+ * - Empty/unset: Deny all (complete isolation)
38
+ * - WORKER_ALLOWED_DOMAINS=*: Allow all (unrestricted)
39
+ * - WORKER_ALLOWED_DOMAINS=domains: Allowlist mode
40
+ * - WORKER_DISALLOWED_DOMAINS=domains: Blocklist mode
41
+ * - Both set: Allowlist with exceptions
42
+ */
43
+ export async function startFilteringProxy(): Promise<void> {
44
+ try {
45
+ const parsedPort = Number.parseInt(
46
+ process.env.WORKER_PROXY_PORT || "8118",
47
+ 10
48
+ );
49
+ const port = Number.isFinite(parsedPort) ? parsedPort : 8118;
50
+ const host = getProxyBindHost();
51
+
52
+ proxyServer = await startHttpProxy(port, host);
53
+
54
+ logger.debug(`HTTP proxy started on ${host}:${port}`);
55
+ } catch (error) {
56
+ logger.error("Failed to start HTTP proxy:", error);
57
+ throw error;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Stop filtering proxy (cleanup on shutdown)
63
+ */
64
+ async function stopFilteringProxy(): Promise<void> {
65
+ if (proxyServer) {
66
+ logger.info("Stopping HTTP proxy...");
67
+ await stopHttpProxy(proxyServer);
68
+ proxyServer = null;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Handle graceful shutdown
74
+ */
75
+ process.on("SIGTERM", async () => {
76
+ await stopFilteringProxy();
77
+ });
78
+
79
+ process.on("SIGINT", async () => {
80
+ await stopFilteringProxy();
81
+ });
@@ -0,0 +1,402 @@
1
+ import { createLogger } from "@lobu/core";
2
+ import type { Context } from "hono";
3
+ import { Hono } from "hono";
4
+ import type Redis from "ioredis";
5
+ import type { AuthProfilesManager } from "../auth/settings/auth-profiles-manager";
6
+ import type { ProviderUpstreamConfig } from "../modules/module-system";
7
+
8
+ const logger = createLogger("secret-proxy");
9
+
10
+ const PLACEHOLDER_PREFIX = "lobu_secret_";
11
+ const REDIS_KEY_PREFIX = "lobu:secret:";
12
+
13
+ export interface SecretMapping {
14
+ agentId: string;
15
+ envVarName: string;
16
+ value: string;
17
+ deploymentName: string;
18
+ }
19
+
20
+ export interface SecretProxyConfig {
21
+ defaultUpstreamUrl: string;
22
+ providerUpstreams?: ProviderUpstreamConfig[];
23
+ }
24
+
25
+ /**
26
+ * Generic secret injection proxy.
27
+ *
28
+ * Workers receive random placeholder tokens instead of real secrets.
29
+ * This proxy intercepts requests, swaps placeholders back to real values
30
+ * in auth headers, and forwards to the upstream API.
31
+ *
32
+ * Zero provider-specific logic — works for any API that uses
33
+ * X-Api-Key or Authorization: Bearer headers.
34
+ */
35
+ export class SecretProxy {
36
+ private app: Hono;
37
+ private redis!: Redis;
38
+ private config: SecretProxyConfig;
39
+ private slugMap: Map<string, string>;
40
+ private slugToProviderId: Map<string, string> = new Map();
41
+ private authProfilesManager?: AuthProfilesManager;
42
+ private systemKeyResolver?: (providerId: string) => string | undefined;
43
+
44
+ constructor(config: SecretProxyConfig) {
45
+ this.config = config;
46
+ this.slugMap = new Map();
47
+ for (const upstream of config.providerUpstreams ?? []) {
48
+ this.slugMap.set(upstream.slug, upstream.upstreamBaseUrl);
49
+ logger.debug(
50
+ `Registered provider upstream: ${upstream.slug} -> ${upstream.upstreamBaseUrl}`
51
+ );
52
+ }
53
+ this.app = new Hono();
54
+ this.setupRoutes();
55
+ }
56
+
57
+ initialize(redis: Redis): void {
58
+ this.redis = redis;
59
+ }
60
+
61
+ setAuthProfilesManager(manager: AuthProfilesManager): void {
62
+ this.authProfilesManager = manager;
63
+ }
64
+
65
+ /**
66
+ * Set a callback that resolves system-level API keys for a provider.
67
+ * Used as fallback when no per-agent auth profile exists.
68
+ */
69
+ setSystemKeyResolver(
70
+ resolver: (providerId: string) => string | undefined
71
+ ): void {
72
+ this.systemKeyResolver = resolver;
73
+ }
74
+
75
+ /**
76
+ * Register a provider upstream for slug-based routing.
77
+ * Called after provider modules are initialized.
78
+ */
79
+ registerUpstream(
80
+ upstream: ProviderUpstreamConfig,
81
+ providerId?: string
82
+ ): void {
83
+ this.slugMap.set(upstream.slug, upstream.upstreamBaseUrl);
84
+ if (providerId) {
85
+ this.slugToProviderId.set(upstream.slug, providerId);
86
+ }
87
+ logger.debug(
88
+ `Registered provider upstream: ${upstream.slug} -> ${upstream.upstreamBaseUrl}${providerId ? ` (providerId: ${providerId})` : ""}`
89
+ );
90
+ }
91
+
92
+ getApp(): Hono {
93
+ return this.app;
94
+ }
95
+
96
+ private setupRoutes(): void {
97
+ this.app.get("/health", (c) =>
98
+ c.json({
99
+ service: "secret-proxy",
100
+ status: "enabled",
101
+ timestamp: new Date().toISOString(),
102
+ })
103
+ );
104
+
105
+ this.app.all("/*", (c) => this.handleRequest(c));
106
+ }
107
+
108
+ private async handleRequest(c: Context): Promise<Response> {
109
+ try {
110
+ return await this.forward(c);
111
+ } catch (error) {
112
+ logger.error("Secret proxy error:", error);
113
+ return c.json({ error: "Internal proxy error" }, 500);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Resolve a placeholder token to its real value via Redis.
119
+ * Handles both plain (`lobu_secret_<uuid>`) and prefixed
120
+ * (`sk-ant-oat01-lobu_secret_<uuid>`) placeholders.
121
+ */
122
+ private async resolveSecret(placeholder: string): Promise<string | null> {
123
+ const prefixIdx = placeholder.indexOf(PLACEHOLDER_PREFIX);
124
+ if (prefixIdx === -1) return null;
125
+ const uuid = placeholder.slice(prefixIdx + PLACEHOLDER_PREFIX.length);
126
+ const key = `${REDIS_KEY_PREFIX}${uuid}`;
127
+ const raw = await this.redis.get(key);
128
+ if (!raw) return null;
129
+ try {
130
+ const mapping: SecretMapping = JSON.parse(raw);
131
+ return mapping.value;
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * If the value contains a UUID placeholder prefix, resolve the real secret.
139
+ * Returns the value unchanged if it's not a recognized pattern.
140
+ */
141
+ private async swap(value: string): Promise<string> {
142
+ if (value.includes(PLACEHOLDER_PREFIX)) {
143
+ const resolved = await this.resolveSecret(value);
144
+ if (!resolved) {
145
+ logger.warn("Failed to resolve secret placeholder");
146
+ return value;
147
+ }
148
+ return resolved;
149
+ }
150
+
151
+ return value;
152
+ }
153
+
154
+ private async forward(c: Context): Promise<Response> {
155
+ // Build upstream URL — strip the proxy mount prefix and resolve provider slug
156
+ const url = new URL(c.req.url);
157
+ const rawPath = url.pathname.replace(/^\/api\/proxy/, "");
158
+
159
+ // Try slug-based routing: /api/proxy/{slug}/rest/of/path
160
+ let upstreamBaseUrl = this.config.defaultUpstreamUrl;
161
+ let forwardPath = rawPath;
162
+ let resolvedSlug: string | undefined;
163
+ let urlAgentId: string | undefined;
164
+ const slugMatch = rawPath.match(/^\/([^/]+)(\/.*)?$/);
165
+ if (slugMatch) {
166
+ const candidateSlug = slugMatch[1]!;
167
+ const resolved = this.slugMap.get(candidateSlug);
168
+ if (resolved) {
169
+ upstreamBaseUrl = resolved;
170
+ forwardPath = slugMatch[2] || "";
171
+ resolvedSlug = candidateSlug;
172
+
173
+ // Extract agentId from /a/{agentId} path segment if present.
174
+ // URL format: /api/proxy/{slug}/a/{agentId}/v1/chat/completions
175
+ const agentMatch = forwardPath.match(/^\/a\/([^/]+)(\/.*)?$/);
176
+ if (agentMatch) {
177
+ urlAgentId = agentMatch[1];
178
+ forwardPath = agentMatch[2] || "";
179
+ }
180
+ }
181
+ }
182
+
183
+ const upstream = `${upstreamBaseUrl}${forwardPath}${url.search}`;
184
+
185
+ // Copy request body for non-GET/HEAD
186
+ const method = c.req.method;
187
+ let body: string | undefined;
188
+ if (method !== "GET" && method !== "HEAD") {
189
+ body = await c.req.text();
190
+ }
191
+
192
+ // Build headers, swapping placeholder secrets in auth headers
193
+ const headers: Record<string, string> = {};
194
+
195
+ // Forward all original headers (except host/connection)
196
+ const skip = new Set(["host", "connection", "transfer-encoding"]);
197
+ for (const [key, val] of Object.entries(c.req.header())) {
198
+ if (val && !skip.has(key.toLowerCase())) {
199
+ headers[key] = val;
200
+ }
201
+ }
202
+
203
+ // Resolve credentials: prefer URL-based agentId (no header parsing needed),
204
+ // fall back to marker/placeholder swap for backward compatibility.
205
+ if (urlAgentId && resolvedSlug && this.authProfilesManager) {
206
+ const providerId = this.slugToProviderId.get(resolvedSlug);
207
+ if (providerId) {
208
+ const profile = await this.authProfilesManager.getBestProfile(
209
+ urlAgentId,
210
+ providerId
211
+ );
212
+ if (profile?.credential) {
213
+ headers.authorization = `Bearer ${profile.credential}`;
214
+ } else if (this.systemKeyResolver) {
215
+ const systemKey = this.systemKeyResolver(providerId);
216
+ if (systemKey) {
217
+ headers.authorization = `Bearer ${systemKey}`;
218
+ } else {
219
+ logger.warn(
220
+ `No auth profile or system key for agent ${urlAgentId}, provider ${providerId}`
221
+ );
222
+ return c.json(
223
+ {
224
+ error: {
225
+ message:
226
+ "No provider credentials configured. End-user provider setup is not available in chat yet. Ask an admin to connect a provider for the base agent.",
227
+ type: "authentication_error",
228
+ code: "no_credentials",
229
+ },
230
+ },
231
+ 401
232
+ );
233
+ }
234
+ } else {
235
+ logger.warn(
236
+ `No auth profile for agent ${urlAgentId}, provider ${providerId}`
237
+ );
238
+ return c.json(
239
+ {
240
+ error: {
241
+ message:
242
+ "No provider credentials configured. End-user provider setup is not available in chat yet. Ask an admin to connect a provider for the base agent.",
243
+ type: "authentication_error",
244
+ code: "no_credentials",
245
+ },
246
+ },
247
+ 401
248
+ );
249
+ }
250
+ } else {
251
+ logger.warn(`No providerId mapping for slug "${resolvedSlug}"`);
252
+ }
253
+ } else {
254
+ // Legacy path: swap UUID placeholders in auth headers (non-provider secrets)
255
+ const apiKey = headers["x-api-key"];
256
+ if (apiKey) {
257
+ headers["x-api-key"] = await this.swap(apiKey);
258
+ }
259
+
260
+ const auth = headers.authorization || headers.Authorization;
261
+ if (auth) {
262
+ const parts = auth.split(" ");
263
+ if (parts.length === 2 && parts[0]?.toLowerCase() === "bearer") {
264
+ const swapped = await this.swap(parts[1]!);
265
+ const headerName = headers.authorization
266
+ ? "authorization"
267
+ : "Authorization";
268
+ headers[headerName] = `Bearer ${swapped}`;
269
+ }
270
+ }
271
+ }
272
+
273
+ logger.info(`Forwarding to upstream: ${method} ${upstream}`);
274
+
275
+ const response = await fetch(upstream, { method, headers, body });
276
+
277
+ if (!response.ok) {
278
+ // Read body for error details (clone to avoid consuming the stream)
279
+ const errBody = await response
280
+ .clone()
281
+ .text()
282
+ .catch(() => "");
283
+ logger.warn(
284
+ `Upstream returned ${response.status} for ${method} ${upstream}: ${errBody.slice(0, 300)}`
285
+ );
286
+ }
287
+
288
+ // Build response headers (skip hop-by-hop)
289
+ const responseHeaders = new Headers();
290
+ response.headers.forEach((value, key) => {
291
+ if (
292
+ ![
293
+ "transfer-encoding",
294
+ "connection",
295
+ "upgrade",
296
+ "content-encoding",
297
+ ].includes(key.toLowerCase())
298
+ ) {
299
+ responseHeaders.set(key, value);
300
+ }
301
+ });
302
+
303
+ // Stream SSE / chunked responses directly
304
+ if (
305
+ response.headers.get("content-type")?.includes("text/event-stream") ||
306
+ response.headers.get("transfer-encoding") === "chunked"
307
+ ) {
308
+ responseHeaders.set("Cache-Control", "no-cache");
309
+ responseHeaders.set("Connection", "keep-alive");
310
+ if (response.body) {
311
+ return new Response(response.body as ReadableStream, {
312
+ status: response.status,
313
+ headers: responseHeaders,
314
+ });
315
+ }
316
+ return c.json({ error: "No response body from upstream" }, 502);
317
+ }
318
+
319
+ // Regular response pass-through
320
+ const text = await response.text();
321
+ return new Response(text, {
322
+ status: response.status,
323
+ headers: responseHeaders,
324
+ });
325
+ }
326
+ }
327
+
328
+ // ============================================================================
329
+ // Utility: store / delete placeholder mappings in Redis
330
+ // ============================================================================
331
+
332
+ /**
333
+ * Store a secret placeholder mapping in Redis.
334
+ * Called by the deployment manager when generating env vars.
335
+ */
336
+ export async function storeSecretMapping(
337
+ redis: Redis,
338
+ uuid: string,
339
+ mapping: SecretMapping,
340
+ ttlSeconds: number = 7 * 24 * 60 * 60 // 7 days default
341
+ ): Promise<void> {
342
+ const key = `${REDIS_KEY_PREFIX}${uuid}`;
343
+ await redis.set(key, JSON.stringify(mapping), "EX", ttlSeconds);
344
+ }
345
+
346
+ /**
347
+ * Delete all secret placeholder mappings for a given deployment.
348
+ * Called during deployment teardown.
349
+ */
350
+ export async function deleteSecretMappings(
351
+ redis: Redis,
352
+ deploymentName: string
353
+ ): Promise<void> {
354
+ const pattern = `${REDIS_KEY_PREFIX}*`;
355
+ let cursor = "0";
356
+ do {
357
+ const [next, keys] = await redis.scan(
358
+ cursor,
359
+ "MATCH",
360
+ pattern,
361
+ "COUNT",
362
+ 100
363
+ );
364
+ cursor = next;
365
+ for (const key of keys) {
366
+ try {
367
+ const raw = await redis.get(key);
368
+ if (raw) {
369
+ const mapping: SecretMapping = JSON.parse(raw);
370
+ if (mapping.deploymentName === deploymentName) {
371
+ await redis.del(key);
372
+ }
373
+ }
374
+ } catch {
375
+ // Skip malformed entries
376
+ }
377
+ }
378
+ } while (cursor !== "0");
379
+ }
380
+
381
+ /**
382
+ * Generate a UUID placeholder token and store its mapping in Redis.
383
+ * Returns the placeholder string to pass to the worker.
384
+ * Used for non-provider secrets (custom env vars with _KEY/_TOKEN/_SECRET patterns).
385
+ */
386
+ export async function generatePlaceholder(
387
+ redis: Redis,
388
+ agentId: string,
389
+ envVarName: string,
390
+ realValue: string,
391
+ deploymentName: string,
392
+ ttlSeconds?: number
393
+ ): Promise<string> {
394
+ const uuid = crypto.randomUUID();
395
+ await storeSecretMapping(
396
+ redis,
397
+ uuid,
398
+ { agentId, envVarName, value: realValue, deploymentName },
399
+ ttlSeconds
400
+ );
401
+ return `${PLACEHOLDER_PREFIX}${uuid}`;
402
+ }
@@ -0,0 +1,143 @@
1
+ import { createLogger } from "@lobu/core";
2
+ import type Redis from "ioredis";
3
+ import type { OAuthClient } from "../auth/oauth/client";
4
+ import type { AuthProfilesManager } from "../auth/settings/auth-profiles-manager";
5
+
6
+ const logger = createLogger("token-refresh-job");
7
+
8
+ const REFRESH_INTERVAL_MS = 2 * 60 * 1000; // 2 minutes
9
+ const EXPIRY_BUFFER_MS = 5 * 60 * 1000; // Refresh tokens expiring within 5 minutes
10
+
11
+ export interface RefreshableProvider {
12
+ providerId: string;
13
+ oauthClient: OAuthClient;
14
+ }
15
+
16
+ /**
17
+ * Background job that proactively refreshes OAuth tokens before they expire.
18
+ *
19
+ * On each tick:
20
+ * 1. Scans authProfiles for OAuth tokens expiring soon across all registered providers
21
+ * 2. Refreshes via the provider's OAuth client
22
+ * 3. Updates authProfiles with new credentials
23
+ */
24
+ export class TokenRefreshJob {
25
+ private timer: Timer | null = null;
26
+ private refreshLocks = new Map<string, Promise<void>>();
27
+
28
+ constructor(
29
+ private authProfilesManager: AuthProfilesManager,
30
+ private redis: Redis,
31
+ private refreshableProviders: RefreshableProvider[]
32
+ ) {}
33
+
34
+ start(): void {
35
+ if (this.timer) return;
36
+ this.timer = setInterval(() => {
37
+ this.tick().catch((err) =>
38
+ logger.error("Token refresh tick failed:", err)
39
+ );
40
+ }, REFRESH_INTERVAL_MS);
41
+ logger.debug("Token refresh job started");
42
+ }
43
+
44
+ stop(): void {
45
+ if (this.timer) {
46
+ clearInterval(this.timer);
47
+ this.timer = null;
48
+ }
49
+ logger.info("Token refresh job stopped");
50
+ }
51
+
52
+ private async tick(): Promise<void> {
53
+ const pattern = "agent:settings:*";
54
+ let cursor = "0";
55
+ do {
56
+ const [next, keys] = await this.redis.scan(
57
+ cursor,
58
+ "MATCH",
59
+ pattern,
60
+ "COUNT",
61
+ 100
62
+ );
63
+ cursor = next;
64
+ for (const key of keys) {
65
+ const agentId = key.replace("agent:settings:", "");
66
+ await this.maybeRefresh(agentId);
67
+ }
68
+ } while (cursor !== "0");
69
+ }
70
+
71
+ private async maybeRefresh(agentId: string): Promise<void> {
72
+ // Prevent concurrent refresh for the same agent
73
+ const existing = this.refreshLocks.get(agentId);
74
+ if (existing) {
75
+ await existing;
76
+ return;
77
+ }
78
+
79
+ const promise = this.doRefresh(agentId);
80
+ this.refreshLocks.set(agentId, promise);
81
+ try {
82
+ await promise;
83
+ } finally {
84
+ this.refreshLocks.delete(agentId);
85
+ }
86
+ }
87
+
88
+ private async doRefresh(agentId: string): Promise<void> {
89
+ for (const { providerId, oauthClient } of this.refreshableProviders) {
90
+ const profiles = await this.authProfilesManager.getProviderProfiles(
91
+ agentId,
92
+ providerId
93
+ );
94
+ const oauthProfile = profiles.find(
95
+ (profile) =>
96
+ profile.authType === "oauth" && !!profile.metadata?.refreshToken
97
+ );
98
+
99
+ if (!oauthProfile?.metadata?.refreshToken) continue;
100
+
101
+ const expiresAt = oauthProfile.metadata.expiresAt || 0;
102
+ const isExpiring = expiresAt <= Date.now() + EXPIRY_BUFFER_MS;
103
+ if (!isExpiring) continue;
104
+
105
+ logger.info(
106
+ `Refreshing ${providerId} token for agent ${agentId} profile ${oauthProfile.id}`,
107
+ { expiresAt: new Date(expiresAt).toISOString() }
108
+ );
109
+
110
+ try {
111
+ const newCredentials = await oauthClient.refreshToken(
112
+ oauthProfile.metadata.refreshToken
113
+ );
114
+
115
+ await this.authProfilesManager.upsertProfile({
116
+ agentId,
117
+ id: oauthProfile.id,
118
+ provider: oauthProfile.provider,
119
+ credential: newCredentials.accessToken,
120
+ authType: "oauth",
121
+ label: oauthProfile.label,
122
+ model: oauthProfile.model,
123
+ metadata: {
124
+ ...oauthProfile.metadata,
125
+ refreshToken: newCredentials.refreshToken,
126
+ expiresAt: newCredentials.expiresAt,
127
+ },
128
+ makePrimary: false,
129
+ });
130
+
131
+ logger.info(`Token refreshed for agent ${agentId} (${providerId})`);
132
+ } catch (error) {
133
+ logger.error(
134
+ `Failed to refresh ${providerId} token for agent ${agentId}`,
135
+ {
136
+ error,
137
+ profileId: oauthProfile.id,
138
+ }
139
+ );
140
+ }
141
+ }
142
+ }
143
+ }