@lobu/gateway 3.0.8 → 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 (219) hide show
  1. package/dist/api/platform.d.ts.map +1 -1
  2. package/dist/api/platform.js +8 -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/cli/index.js +2 -2
  12. package/dist/cli/index.js.map +1 -1
  13. package/dist/connections/chat-instance-manager.d.ts.map +1 -1
  14. package/dist/connections/chat-instance-manager.js +2 -1
  15. package/dist/connections/chat-instance-manager.js.map +1 -1
  16. package/dist/connections/interaction-bridge.d.ts +9 -2
  17. package/dist/connections/interaction-bridge.d.ts.map +1 -1
  18. package/dist/connections/interaction-bridge.js +132 -230
  19. package/dist/connections/interaction-bridge.js.map +1 -1
  20. package/dist/connections/message-handler-bridge.d.ts.map +1 -1
  21. package/dist/connections/message-handler-bridge.js +44 -26
  22. package/dist/connections/message-handler-bridge.js.map +1 -1
  23. package/dist/interactions.d.ts +9 -43
  24. package/dist/interactions.d.ts.map +1 -1
  25. package/dist/interactions.js +10 -52
  26. package/dist/interactions.js.map +1 -1
  27. package/dist/orchestration/base-deployment-manager.js +7 -7
  28. package/dist/orchestration/base-deployment-manager.js.map +1 -1
  29. package/dist/platform/unified-thread-consumer.d.ts.map +1 -1
  30. package/dist/platform/unified-thread-consumer.js +38 -34
  31. package/dist/platform/unified-thread-consumer.js.map +1 -1
  32. package/dist/routes/public/agent.d.ts +4 -0
  33. package/dist/routes/public/agent.d.ts.map +1 -1
  34. package/dist/routes/public/agent.js +21 -0
  35. package/dist/routes/public/agent.js.map +1 -1
  36. package/dist/services/core-services.d.ts.map +1 -1
  37. package/dist/services/core-services.js +4 -0
  38. package/dist/services/core-services.js.map +1 -1
  39. package/package.json +2 -2
  40. package/src/__tests__/agent-config-routes.test.ts +0 -254
  41. package/src/__tests__/agent-history-routes.test.ts +0 -72
  42. package/src/__tests__/agent-routes.test.ts +0 -68
  43. package/src/__tests__/agent-schedules-routes.test.ts +0 -59
  44. package/src/__tests__/agent-settings-store.test.ts +0 -323
  45. package/src/__tests__/bedrock-model-catalog.test.ts +0 -40
  46. package/src/__tests__/bedrock-openai-service.test.ts +0 -157
  47. package/src/__tests__/bedrock-provider-module.test.ts +0 -56
  48. package/src/__tests__/chat-instance-manager-slack.test.ts +0 -204
  49. package/src/__tests__/chat-response-bridge.test.ts +0 -131
  50. package/src/__tests__/config-memory-plugins.test.ts +0 -92
  51. package/src/__tests__/config-request-store.test.ts +0 -127
  52. package/src/__tests__/connection-routes.test.ts +0 -144
  53. package/src/__tests__/core-services-store-selection.test.ts +0 -92
  54. package/src/__tests__/docker-deployment.test.ts +0 -1211
  55. package/src/__tests__/embedded-deployment.test.ts +0 -342
  56. package/src/__tests__/grant-store.test.ts +0 -148
  57. package/src/__tests__/http-proxy.test.ts +0 -281
  58. package/src/__tests__/instruction-service.test.ts +0 -37
  59. package/src/__tests__/link-buttons.test.ts +0 -112
  60. package/src/__tests__/lobu.test.ts +0 -32
  61. package/src/__tests__/mcp-config-service.test.ts +0 -347
  62. package/src/__tests__/mcp-proxy.test.ts +0 -694
  63. package/src/__tests__/message-handler-bridge.test.ts +0 -17
  64. package/src/__tests__/model-selection.test.ts +0 -172
  65. package/src/__tests__/oauth-templates.test.ts +0 -39
  66. package/src/__tests__/platform-adapter-slack-send.test.ts +0 -114
  67. package/src/__tests__/platform-helpers-model-resolution.test.ts +0 -253
  68. package/src/__tests__/provider-inheritance.test.ts +0 -212
  69. package/src/__tests__/routes/cli-auth.test.ts +0 -337
  70. package/src/__tests__/routes/interactions.test.ts +0 -121
  71. package/src/__tests__/secret-proxy.test.ts +0 -85
  72. package/src/__tests__/session-manager.test.ts +0 -572
  73. package/src/__tests__/setup.ts +0 -133
  74. package/src/__tests__/skill-and-mcp-registry.test.ts +0 -203
  75. package/src/__tests__/slack-routes.test.ts +0 -161
  76. package/src/__tests__/system-config-resolver.test.ts +0 -75
  77. package/src/__tests__/system-message-limiter.test.ts +0 -89
  78. package/src/__tests__/system-skills-service.test.ts +0 -362
  79. package/src/__tests__/transcription-service.test.ts +0 -222
  80. package/src/__tests__/utils/rate-limiter.test.ts +0 -102
  81. package/src/__tests__/worker-connection-manager.test.ts +0 -497
  82. package/src/__tests__/worker-job-router.test.ts +0 -722
  83. package/src/api/index.ts +0 -1
  84. package/src/api/platform.ts +0 -292
  85. package/src/api/response-renderer.ts +0 -157
  86. package/src/auth/agent-metadata-store.ts +0 -168
  87. package/src/auth/api-auth-middleware.ts +0 -69
  88. package/src/auth/api-key-provider-module.ts +0 -213
  89. package/src/auth/base-provider-module.ts +0 -201
  90. package/src/auth/bedrock/provider-module.ts +0 -110
  91. package/src/auth/chatgpt/chatgpt-oauth-module.ts +0 -185
  92. package/src/auth/chatgpt/device-code-client.ts +0 -218
  93. package/src/auth/chatgpt/index.ts +0 -1
  94. package/src/auth/claude/oauth-module.ts +0 -280
  95. package/src/auth/cli/token-service.ts +0 -249
  96. package/src/auth/external/client.ts +0 -560
  97. package/src/auth/external/device-code-client.ts +0 -235
  98. package/src/auth/mcp/config-service.ts +0 -420
  99. package/src/auth/mcp/proxy.ts +0 -1086
  100. package/src/auth/mcp/string-substitution.ts +0 -17
  101. package/src/auth/mcp/tool-cache.ts +0 -90
  102. package/src/auth/oauth/base-client.ts +0 -267
  103. package/src/auth/oauth/client.ts +0 -153
  104. package/src/auth/oauth/credentials.ts +0 -7
  105. package/src/auth/oauth/providers.ts +0 -69
  106. package/src/auth/oauth/state-store.ts +0 -150
  107. package/src/auth/oauth-templates.ts +0 -179
  108. package/src/auth/provider-catalog.ts +0 -220
  109. package/src/auth/provider-model-options.ts +0 -41
  110. package/src/auth/settings/agent-settings-store.ts +0 -565
  111. package/src/auth/settings/auth-profiles-manager.ts +0 -216
  112. package/src/auth/settings/index.ts +0 -12
  113. package/src/auth/settings/model-preference-store.ts +0 -52
  114. package/src/auth/settings/model-selection.ts +0 -135
  115. package/src/auth/settings/resolved-settings-view.ts +0 -298
  116. package/src/auth/settings/template-utils.ts +0 -44
  117. package/src/auth/settings/token-service.ts +0 -88
  118. package/src/auth/system-env-store.ts +0 -98
  119. package/src/auth/user-agents-store.ts +0 -68
  120. package/src/channels/binding-service.ts +0 -214
  121. package/src/channels/index.ts +0 -4
  122. package/src/cli/gateway.ts +0 -1312
  123. package/src/cli/index.ts +0 -74
  124. package/src/commands/built-in-commands.ts +0 -80
  125. package/src/commands/command-dispatcher.ts +0 -94
  126. package/src/commands/command-reply-adapters.ts +0 -27
  127. package/src/config/file-loader.ts +0 -618
  128. package/src/config/index.ts +0 -588
  129. package/src/config/network-allowlist.ts +0 -71
  130. package/src/connections/chat-instance-manager.ts +0 -1284
  131. package/src/connections/chat-response-bridge.ts +0 -618
  132. package/src/connections/index.ts +0 -7
  133. package/src/connections/interaction-bridge.ts +0 -831
  134. package/src/connections/message-handler-bridge.ts +0 -415
  135. package/src/connections/platform-auth-methods.ts +0 -15
  136. package/src/connections/types.ts +0 -84
  137. package/src/gateway/connection-manager.ts +0 -291
  138. package/src/gateway/index.ts +0 -698
  139. package/src/gateway/job-router.ts +0 -201
  140. package/src/gateway-main.ts +0 -200
  141. package/src/index.ts +0 -41
  142. package/src/infrastructure/queue/index.ts +0 -12
  143. package/src/infrastructure/queue/queue-producer.ts +0 -148
  144. package/src/infrastructure/queue/redis-queue.ts +0 -361
  145. package/src/infrastructure/queue/types.ts +0 -133
  146. package/src/infrastructure/redis/system-message-limiter.ts +0 -94
  147. package/src/interactions/config-request-store.ts +0 -198
  148. package/src/interactions.ts +0 -363
  149. package/src/lobu.ts +0 -311
  150. package/src/metrics/prometheus.ts +0 -159
  151. package/src/modules/module-system.ts +0 -179
  152. package/src/orchestration/base-deployment-manager.ts +0 -900
  153. package/src/orchestration/deployment-utils.ts +0 -98
  154. package/src/orchestration/impl/docker-deployment.ts +0 -620
  155. package/src/orchestration/impl/embedded-deployment.ts +0 -268
  156. package/src/orchestration/impl/index.ts +0 -8
  157. package/src/orchestration/impl/k8s/deployment.ts +0 -1061
  158. package/src/orchestration/impl/k8s/helpers.ts +0 -610
  159. package/src/orchestration/impl/k8s/index.ts +0 -1
  160. package/src/orchestration/index.ts +0 -333
  161. package/src/orchestration/message-consumer.ts +0 -584
  162. package/src/orchestration/scheduled-wakeup.ts +0 -704
  163. package/src/permissions/approval-policy.ts +0 -36
  164. package/src/permissions/grant-store.ts +0 -219
  165. package/src/platform/file-handler.ts +0 -66
  166. package/src/platform/link-buttons.ts +0 -57
  167. package/src/platform/renderer-utils.ts +0 -44
  168. package/src/platform/response-renderer.ts +0 -84
  169. package/src/platform/unified-thread-consumer.ts +0 -187
  170. package/src/platform.ts +0 -318
  171. package/src/proxy/http-proxy.ts +0 -752
  172. package/src/proxy/proxy-manager.ts +0 -81
  173. package/src/proxy/secret-proxy.ts +0 -402
  174. package/src/proxy/token-refresh-job.ts +0 -143
  175. package/src/routes/internal/audio.ts +0 -141
  176. package/src/routes/internal/device-auth.ts +0 -652
  177. package/src/routes/internal/files.ts +0 -226
  178. package/src/routes/internal/history.ts +0 -69
  179. package/src/routes/internal/images.ts +0 -127
  180. package/src/routes/internal/interactions.ts +0 -84
  181. package/src/routes/internal/middleware.ts +0 -23
  182. package/src/routes/internal/schedule.ts +0 -226
  183. package/src/routes/internal/types.ts +0 -22
  184. package/src/routes/openapi-auto.ts +0 -239
  185. package/src/routes/public/agent-access.ts +0 -23
  186. package/src/routes/public/agent-config.ts +0 -675
  187. package/src/routes/public/agent-history.ts +0 -422
  188. package/src/routes/public/agent-schedules.ts +0 -296
  189. package/src/routes/public/agent.ts +0 -1086
  190. package/src/routes/public/agents.ts +0 -373
  191. package/src/routes/public/channels.ts +0 -191
  192. package/src/routes/public/cli-auth.ts +0 -896
  193. package/src/routes/public/connections.ts +0 -574
  194. package/src/routes/public/landing.ts +0 -16
  195. package/src/routes/public/oauth.ts +0 -147
  196. package/src/routes/public/settings-auth.ts +0 -104
  197. package/src/routes/public/slack.ts +0 -173
  198. package/src/routes/shared/agent-ownership.ts +0 -101
  199. package/src/routes/shared/token-verifier.ts +0 -34
  200. package/src/services/bedrock-model-catalog.ts +0 -217
  201. package/src/services/bedrock-openai-service.ts +0 -658
  202. package/src/services/core-services.ts +0 -1072
  203. package/src/services/image-generation-service.ts +0 -257
  204. package/src/services/instruction-service.ts +0 -318
  205. package/src/services/mcp-registry.ts +0 -94
  206. package/src/services/platform-helpers.ts +0 -287
  207. package/src/services/session-manager.ts +0 -262
  208. package/src/services/settings-resolver.ts +0 -74
  209. package/src/services/system-config-resolver.ts +0 -89
  210. package/src/services/system-skills-service.ts +0 -229
  211. package/src/services/transcription-service.ts +0 -684
  212. package/src/session.ts +0 -110
  213. package/src/spaces/index.ts +0 -1
  214. package/src/spaces/space-resolver.ts +0 -17
  215. package/src/stores/in-memory-agent-store.ts +0 -403
  216. package/src/stores/redis-agent-store.ts +0 -279
  217. package/src/utils/public-url.ts +0 -44
  218. package/src/utils/rate-limiter.ts +0 -94
  219. package/tsconfig.json +0 -33
@@ -1,565 +0,0 @@
1
- import {
2
- type AuthProfile,
3
- BaseRedisStore,
4
- decrypt,
5
- encrypt,
6
- type InstalledProvider,
7
- type McpServerConfig,
8
- type NetworkConfig,
9
- type NixConfig,
10
- type PluginsConfig,
11
- type SkillsConfig,
12
- safeJsonParse,
13
- safeJsonStringify,
14
- type ToolsConfig,
15
- } from "@lobu/core";
16
- import type Redis from "ioredis";
17
- import type {
18
- ModelSelectionState,
19
- ProviderModelPreferences,
20
- } from "./model-selection";
21
-
22
- const ENCRYPTED_VALUE_PREFIX = "enc:v1:";
23
-
24
- interface SensitiveValueDecodeResult {
25
- value: string;
26
- needsMigration: boolean;
27
- }
28
-
29
- /**
30
- * Agent settings - configurable per agentId via web UI
31
- * Stored in Redis at agent:settings:{agentId}
32
- */
33
- export interface AgentSettings {
34
- /** Claude model to use (e.g., claude-sonnet-4, claude-opus-4) */
35
- model?: string;
36
- /** Model selection mode (auto provider/default model vs pinned provider/model). */
37
- modelSelection?: ModelSelectionState;
38
- /** Per-provider preferred model for auto mode. */
39
- providerModelPreferences?: ProviderModelPreferences;
40
- /** Network access configuration */
41
- networkConfig?: NetworkConfig;
42
- /** Nix environment configuration */
43
- nixConfig?: NixConfig;
44
- /** Additional MCP servers */
45
- mcpServers?: Record<string, McpServerConfig>;
46
- /** Internal marker: MCP IDs already acknowledged to the user in chat */
47
- mcpInstallNotified?: Record<string, number>;
48
- /** Workspace identity/instruction files (markdown content) */
49
- soulMd?: string;
50
- /** Workspace user-specific context (markdown content) */
51
- userMd?: string;
52
- /** Workspace agent identity description (markdown content) */
53
- identityMd?: string;
54
- /** Skills configuration - enabled skills from skills.sh */
55
- skillsConfig?: SkillsConfig;
56
- /** Tool permission configuration - allowed/denied tools */
57
- toolsConfig?: ToolsConfig;
58
- /** OpenClaw plugin configuration */
59
- pluginsConfig?: PluginsConfig;
60
- /** Ordered auth profiles (index 0 = primary). Used for multi-provider credential management. */
61
- authProfiles?: AuthProfile[];
62
- /** Installed providers for this agent (index 0 = primary). */
63
- installedProviders?: InstalledProvider[];
64
- /** Enable verbose logging (show tool calls, reasoning, etc.) */
65
- verboseLogging?: boolean;
66
- /** Template agent this sandbox was cloned from (for credential fallback) */
67
- templateAgentId?: string;
68
- /** Last updated timestamp */
69
- updatedAt: number;
70
- }
71
-
72
- export interface AgentSettingsContext {
73
- localSettings: AgentSettings | null;
74
- effectiveSettings: AgentSettings | null;
75
- templateAgentId?: string;
76
- }
77
-
78
- /**
79
- * Store and retrieve agent settings from Redis
80
- * Pattern: agent:settings:{agentId}
81
- *
82
- * Settings are stored per agentId (e.g., "telegram-6570514069", "slack-g-C12345")
83
- */
84
- export class AgentSettingsStore extends BaseRedisStore<AgentSettings> {
85
- private readonly encryptionAvailable: boolean;
86
-
87
- constructor(redis: Redis) {
88
- super({
89
- redis,
90
- keyPrefix: "agent:settings",
91
- loggerName: "agent-settings-store",
92
- });
93
-
94
- this.encryptionAvailable = this.canEncryptSensitiveValues();
95
- }
96
-
97
- /**
98
- * Get settings for an agent
99
- * Returns null if no settings configured
100
- */
101
- async getSettings(agentId: string): Promise<AgentSettings | null> {
102
- const key = this.buildKey(agentId);
103
- try {
104
- const data = await this.redis.get(key);
105
- if (!data) {
106
- return null;
107
- }
108
-
109
- const parsed = safeJsonParse<AgentSettings>(data);
110
- if (!parsed) {
111
- this.logger.warn("Failed to parse agent settings from Redis", { key });
112
- return null;
113
- }
114
-
115
- const { settings, needsMigration } =
116
- this.decryptSettingsForRuntime(parsed);
117
-
118
- if (needsMigration) {
119
- await this.migrateSettingsInPlace(key, settings, data);
120
- }
121
-
122
- return settings;
123
- } catch (error) {
124
- this.logger.error("Failed to get settings from Redis", {
125
- error: error instanceof Error ? error.message : String(error),
126
- key,
127
- });
128
- return null;
129
- }
130
- }
131
-
132
- /**
133
- * Get effective settings for an agent, with template agent fallback.
134
- * For sandbox agents, inherits from the template agent when own settings
135
- * are missing or have no providers configured.
136
- */
137
- async getEffectiveSettings(agentId: string): Promise<AgentSettings | null> {
138
- const context = await this.getSettingsContext(agentId);
139
- return context.effectiveSettings;
140
- }
141
-
142
- async getSettingsContext(agentId: string): Promise<AgentSettingsContext> {
143
- const localSettings = await this.getSettings(agentId);
144
-
145
- // Resolve template agent ID
146
- const templateAgentId = await this.resolveTemplateAgentId(
147
- agentId,
148
- localSettings
149
- );
150
- if (!templateAgentId) {
151
- return { localSettings, effectiveSettings: localSettings };
152
- }
153
-
154
- const templateSettings = await this.getSettings(templateAgentId);
155
- if (!templateSettings) {
156
- return {
157
- localSettings,
158
- effectiveSettings: localSettings,
159
- templateAgentId,
160
- };
161
- }
162
-
163
- // Merge: own settings override template, but inherit missing fields
164
- if (!localSettings) {
165
- return {
166
- localSettings,
167
- effectiveSettings: { ...templateSettings, templateAgentId },
168
- templateAgentId,
169
- };
170
- }
171
-
172
- return {
173
- localSettings,
174
- effectiveSettings: {
175
- ...templateSettings,
176
- ...Object.fromEntries(
177
- Object.entries(localSettings).filter(([, v]) => v !== undefined)
178
- ),
179
- templateAgentId,
180
- } as AgentSettings,
181
- templateAgentId,
182
- };
183
- }
184
-
185
- /**
186
- * Resolve the template agent ID for a sandbox agent.
187
- * Chain: settings.templateAgentId → metadata.parentConnectionId → connection.templateAgentId
188
- */
189
- private async resolveTemplateAgentId(
190
- agentId: string,
191
- settings: AgentSettings | null
192
- ): Promise<string | undefined> {
193
- if (settings?.templateAgentId) return settings.templateAgentId;
194
-
195
- try {
196
- // Check metadata for parentConnectionId
197
- const metaRaw = await this.redis.get(`agent_metadata:${agentId}`);
198
- if (!metaRaw) return undefined;
199
- const meta = safeJsonParse<{ parentConnectionId?: string }>(metaRaw);
200
- if (!meta?.parentConnectionId) return undefined;
201
-
202
- // Check connection for templateAgentId
203
- const connRaw = await this.redis.get(
204
- `connection:${meta.parentConnectionId}`
205
- );
206
- if (!connRaw) return undefined;
207
- const conn = safeJsonParse<{ templateAgentId?: string }>(connRaw);
208
- return conn?.templateAgentId;
209
- } catch {
210
- return undefined;
211
- }
212
- }
213
-
214
- /**
215
- * Save settings for an agent
216
- * Overwrites existing settings
217
- */
218
- async saveSettings(
219
- agentId: string,
220
- settings: Omit<AgentSettings, "updatedAt">
221
- ): Promise<void> {
222
- const key = this.buildKey(agentId);
223
- const fullSettings: AgentSettings = {
224
- ...settings,
225
- updatedAt: Date.now(),
226
- };
227
- await this.set(key, fullSettings);
228
- this.logger.info(`Saved settings for agent ${agentId}`);
229
- }
230
-
231
- /**
232
- * Update specific settings fields (partial update)
233
- */
234
- async updateSettings(
235
- agentId: string,
236
- updates: Partial<Omit<AgentSettings, "updatedAt">>
237
- ): Promise<void> {
238
- const existing = await this.getSettings(agentId);
239
- const merged: AgentSettings = {
240
- ...existing,
241
- ...updates,
242
- updatedAt: Date.now(),
243
- };
244
- const key = this.buildKey(agentId);
245
- await this.set(key, merged);
246
- this.logger.info(`Updated settings for agent ${agentId}`);
247
- }
248
-
249
- /**
250
- * Delete settings for an agent
251
- */
252
- async deleteSettings(agentId: string): Promise<void> {
253
- const key = this.buildKey(agentId);
254
- await this.delete(key);
255
- this.logger.info(`Deleted settings for agent ${agentId}`);
256
- }
257
-
258
- /**
259
- * Find all sandbox agent IDs that reference a given template agent.
260
- */
261
- async findSandboxAgentIds(templateAgentId: string): Promise<string[]> {
262
- const prefix = `${this.keyPrefix}:`;
263
- const keys = await this.scanByPrefix(prefix);
264
- const sandboxIds: string[] = [];
265
-
266
- for (const key of keys) {
267
- try {
268
- const raw = await this.redis.get(key);
269
- if (!raw) continue;
270
- const parsed = safeJsonParse<AgentSettings>(raw);
271
- if (parsed?.templateAgentId === templateAgentId) {
272
- sandboxIds.push(key.slice(prefix.length));
273
- }
274
- } catch {
275
- // Skip unparseable entries
276
- }
277
- }
278
-
279
- return sandboxIds;
280
- }
281
-
282
- /**
283
- * Check if agent has any settings configured
284
- */
285
- async hasSettings(agentId: string): Promise<boolean> {
286
- const key = this.buildKey(agentId);
287
- return this.exists(key);
288
- }
289
-
290
- /**
291
- * Find the first agent that has installed providers configured.
292
- * Used to find a template for ephemeral agents.
293
- */
294
- async findTemplateAgentId(): Promise<string | null> {
295
- const prefix = `${this.keyPrefix}:`;
296
- const keys = await this.scanByPrefix(prefix);
297
- for (const key of keys) {
298
- try {
299
- const data = await this.redis.get(key);
300
- if (!data) continue;
301
- const parsed = safeJsonParse<AgentSettings>(data);
302
- if (
303
- parsed?.installedProviders &&
304
- parsed.installedProviders.length > 0
305
- ) {
306
- // Extract agentId from key: "agent:settings:{agentId}"
307
- return key.slice(prefix.length);
308
- }
309
- } catch {
310
- /* skip unparseable key */
311
- }
312
- }
313
- return null;
314
- }
315
-
316
- protected override serialize(value: AgentSettings): string {
317
- const encrypted = this.encryptSettingsForStorage(value);
318
- const json = safeJsonStringify(encrypted);
319
- if (json === null) {
320
- throw new Error("Failed to serialize value to JSON");
321
- }
322
- return json;
323
- }
324
-
325
- private canEncryptSensitiveValues(): boolean {
326
- try {
327
- const probe = "agent-settings-store-encryption-probe";
328
- return decrypt(encrypt(probe)) === probe;
329
- } catch {
330
- this.logger.warn(
331
- "ENCRYPTION_KEY not configured or invalid - auth profile credentials will be stored unencrypted"
332
- );
333
- return false;
334
- }
335
- }
336
-
337
- private async migrateSettingsInPlace(
338
- key: string,
339
- settings: AgentSettings,
340
- originalRaw: string
341
- ): Promise<void> {
342
- if (!this.encryptionAvailable) {
343
- return;
344
- }
345
-
346
- try {
347
- await this.redis.watch(key);
348
- const currentRaw = await this.redis.get(key);
349
- if (currentRaw !== originalRaw) {
350
- await this.redis.unwatch();
351
- this.logger.info(
352
- "Skipped credentials migration due to concurrent settings update",
353
- { key }
354
- );
355
- return;
356
- }
357
-
358
- const serialized = this.serialize(settings);
359
- const result = await this.redis.multi().set(key, serialized).exec();
360
- if (!result) {
361
- this.logger.info(
362
- "Skipped credentials migration due to concurrent settings update",
363
- { key }
364
- );
365
- return;
366
- }
367
-
368
- this.logger.info(
369
- "Migrated agent settings credentials to encrypted format",
370
- {
371
- key,
372
- }
373
- );
374
- } catch (error) {
375
- try {
376
- await this.redis.unwatch();
377
- } catch {
378
- // Ignore cleanup failures.
379
- }
380
- this.logger.warn(
381
- "Failed migrating plaintext agent settings credentials",
382
- {
383
- error: error instanceof Error ? error.message : String(error),
384
- key,
385
- }
386
- );
387
- }
388
- }
389
-
390
- private encryptSettingsForStorage(settings: AgentSettings): AgentSettings {
391
- let result = settings;
392
-
393
- // Encrypt auth profile credentials
394
- if (
395
- Array.isArray(settings.authProfiles) &&
396
- settings.authProfiles.length > 0
397
- ) {
398
- let profilesChanged = false;
399
- const authProfiles = settings.authProfiles.map((profile) => {
400
- const encryptedCredential = this.encryptSensitiveValue(
401
- profile.credential
402
- );
403
- const credentialChanged = encryptedCredential !== profile.credential;
404
- let metadataChanged = false;
405
- let metadata = profile.metadata;
406
-
407
- if (profile.metadata?.refreshToken) {
408
- const encryptedRefreshToken = this.encryptSensitiveValue(
409
- profile.metadata.refreshToken
410
- );
411
- if (encryptedRefreshToken !== profile.metadata.refreshToken) {
412
- metadataChanged = true;
413
- metadata = {
414
- ...profile.metadata,
415
- refreshToken: encryptedRefreshToken,
416
- };
417
- }
418
- }
419
-
420
- if (!credentialChanged && !metadataChanged) {
421
- return profile;
422
- }
423
-
424
- profilesChanged = true;
425
- return {
426
- ...profile,
427
- credential: encryptedCredential,
428
- metadata,
429
- };
430
- });
431
-
432
- if (profilesChanged) {
433
- result = { ...result, authProfiles };
434
- }
435
- }
436
-
437
- return result;
438
- }
439
-
440
- private decryptSettingsForRuntime(settings: AgentSettings): {
441
- settings: AgentSettings;
442
- needsMigration: boolean;
443
- } {
444
- let result = settings;
445
- let changed = false;
446
- let needsMigration = false;
447
-
448
- // Decrypt auth profile credentials
449
- if (
450
- Array.isArray(settings.authProfiles) &&
451
- settings.authProfiles.length > 0
452
- ) {
453
- let profilesChanged = false;
454
-
455
- const authProfiles = settings.authProfiles.map((profile) => {
456
- const credential = this.decryptSensitiveValue(profile.credential);
457
- let metadata = profile.metadata;
458
- let metadataChanged = false;
459
-
460
- if (profile.metadata?.refreshToken) {
461
- const refreshToken = this.decryptSensitiveValue(
462
- profile.metadata.refreshToken
463
- );
464
- if (refreshToken.value !== profile.metadata.refreshToken) {
465
- metadataChanged = true;
466
- metadata = {
467
- ...profile.metadata,
468
- refreshToken: refreshToken.value,
469
- };
470
- }
471
- needsMigration ||= refreshToken.needsMigration;
472
- }
473
-
474
- if (credential.value !== profile.credential || metadataChanged) {
475
- profilesChanged = true;
476
- }
477
-
478
- needsMigration ||= credential.needsMigration;
479
-
480
- if (!metadataChanged && credential.value === profile.credential) {
481
- return profile;
482
- }
483
-
484
- return {
485
- ...profile,
486
- credential: credential.value,
487
- metadata,
488
- };
489
- });
490
-
491
- if (profilesChanged) {
492
- changed = true;
493
- result = { ...result, authProfiles };
494
- }
495
- }
496
-
497
- if (!changed) {
498
- return { settings, needsMigration };
499
- }
500
-
501
- return { settings: result, needsMigration };
502
- }
503
-
504
- private encryptSensitiveValue(value: string): string {
505
- if (!this.encryptionAvailable) {
506
- return value;
507
- }
508
- if (value.startsWith(ENCRYPTED_VALUE_PREFIX)) {
509
- return value;
510
- }
511
- return `${ENCRYPTED_VALUE_PREFIX}${encrypt(value)}`;
512
- }
513
-
514
- private decryptSensitiveValue(value: string): SensitiveValueDecodeResult {
515
- if (value.startsWith(ENCRYPTED_VALUE_PREFIX)) {
516
- if (!this.encryptionAvailable) {
517
- return { value, needsMigration: false };
518
- }
519
-
520
- try {
521
- const decrypted = decrypt(value.slice(ENCRYPTED_VALUE_PREFIX.length));
522
- return { value: decrypted, needsMigration: false };
523
- } catch (error) {
524
- this.logger.warn(
525
- "Dropping undecryptable credential (ENCRYPTION_KEY changed?)",
526
- { error: error instanceof Error ? error.message : String(error) }
527
- );
528
- return { value: "", needsMigration: false };
529
- }
530
- }
531
-
532
- if (this.encryptionAvailable && this.looksLikeLegacyEncryptedValue(value)) {
533
- try {
534
- const decrypted = decrypt(value);
535
- return { value: decrypted, needsMigration: true };
536
- } catch (error) {
537
- this.logger.warn(
538
- "Failed to decrypt legacy auth profile credential value",
539
- {
540
- error: error instanceof Error ? error.message : String(error),
541
- }
542
- );
543
- return { value, needsMigration: false };
544
- }
545
- }
546
-
547
- return {
548
- value,
549
- needsMigration: this.encryptionAvailable,
550
- };
551
- }
552
-
553
- private looksLikeLegacyEncryptedValue(value: string): boolean {
554
- const [iv, tag, encrypted, ...rest] = value.split(":");
555
- if (rest.length > 0) return false;
556
- if (!iv || !tag || !encrypted) return false;
557
- return (
558
- iv.length === 24 &&
559
- tag.length === 32 &&
560
- /^[0-9a-f]+$/i.test(iv) &&
561
- /^[0-9a-f]+$/i.test(tag) &&
562
- /^[0-9a-f]+$/i.test(encrypted)
563
- );
564
- }
565
- }