@lobu/gateway 2.8.0 → 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.
- package/package.json +2 -2
- package/src/__tests__/agent-config-routes.test.ts +254 -0
- package/src/__tests__/agent-history-routes.test.ts +72 -0
- package/src/__tests__/agent-routes.test.ts +68 -0
- package/src/__tests__/agent-schedules-routes.test.ts +59 -0
- package/src/__tests__/agent-settings-store.test.ts +323 -0
- package/src/__tests__/chat-instance-manager-slack.test.ts +204 -0
- package/src/__tests__/chat-response-bridge.test.ts +131 -0
- package/src/__tests__/config-memory-plugins.test.ts +92 -0
- package/src/__tests__/config-request-store.test.ts +127 -0
- package/src/__tests__/connection-routes.test.ts +144 -0
- package/src/__tests__/core-services-store-selection.test.ts +92 -0
- package/src/__tests__/docker-deployment.test.ts +1211 -0
- package/src/__tests__/embedded-deployment.test.ts +342 -0
- package/src/__tests__/grant-store.test.ts +148 -0
- package/src/__tests__/http-proxy.test.ts +281 -0
- package/src/__tests__/instruction-service.test.ts +37 -0
- package/src/__tests__/link-buttons.test.ts +112 -0
- package/src/__tests__/lobu.test.ts +32 -0
- package/src/__tests__/mcp-config-service.test.ts +347 -0
- package/src/__tests__/mcp-proxy.test.ts +696 -0
- package/src/__tests__/message-handler-bridge.test.ts +17 -0
- package/src/__tests__/model-selection.test.ts +172 -0
- package/src/__tests__/oauth-templates.test.ts +39 -0
- package/src/__tests__/platform-adapter-slack-send.test.ts +114 -0
- package/src/__tests__/platform-helpers-model-resolution.test.ts +253 -0
- package/src/__tests__/provider-inheritance.test.ts +212 -0
- package/src/__tests__/routes/cli-auth.test.ts +337 -0
- package/src/__tests__/routes/interactions.test.ts +121 -0
- package/src/__tests__/secret-proxy.test.ts +85 -0
- package/src/__tests__/session-manager.test.ts +572 -0
- package/src/__tests__/setup.ts +133 -0
- package/src/__tests__/skill-and-mcp-registry.test.ts +203 -0
- package/src/__tests__/slack-routes.test.ts +161 -0
- package/src/__tests__/system-config-resolver.test.ts +75 -0
- package/src/__tests__/system-message-limiter.test.ts +89 -0
- package/src/__tests__/system-skills-service.test.ts +362 -0
- package/src/__tests__/transcription-service.test.ts +222 -0
- package/src/__tests__/utils/rate-limiter.test.ts +102 -0
- package/src/__tests__/worker-connection-manager.test.ts +497 -0
- package/src/__tests__/worker-job-router.test.ts +722 -0
- package/src/api/index.ts +1 -0
- package/src/api/platform.ts +292 -0
- package/src/api/response-renderer.ts +157 -0
- package/src/auth/agent-metadata-store.ts +168 -0
- package/src/auth/api-auth-middleware.ts +69 -0
- package/src/auth/api-key-provider-module.ts +213 -0
- package/src/auth/base-provider-module.ts +201 -0
- package/src/auth/chatgpt/chatgpt-oauth-module.ts +185 -0
- package/src/auth/chatgpt/device-code-client.ts +218 -0
- package/src/auth/chatgpt/index.ts +1 -0
- package/src/auth/claude/oauth-module.ts +280 -0
- package/src/auth/cli/token-service.ts +249 -0
- package/src/auth/external/client.ts +560 -0
- package/src/auth/external/device-code-client.ts +225 -0
- package/src/auth/mcp/config-service.ts +392 -0
- package/src/auth/mcp/proxy.ts +1088 -0
- package/src/auth/mcp/string-substitution.ts +17 -0
- package/src/auth/mcp/tool-cache.ts +90 -0
- package/src/auth/oauth/base-client.ts +267 -0
- package/src/auth/oauth/client.ts +153 -0
- package/src/auth/oauth/credentials.ts +7 -0
- package/src/auth/oauth/providers.ts +69 -0
- package/src/auth/oauth/state-store.ts +150 -0
- package/src/auth/oauth-templates.ts +179 -0
- package/src/auth/provider-catalog.ts +220 -0
- package/src/auth/provider-model-options.ts +41 -0
- package/src/auth/settings/agent-settings-store.ts +565 -0
- package/src/auth/settings/auth-profiles-manager.ts +216 -0
- package/src/auth/settings/index.ts +12 -0
- package/src/auth/settings/model-preference-store.ts +52 -0
- package/src/auth/settings/model-selection.ts +135 -0
- package/src/auth/settings/resolved-settings-view.ts +298 -0
- package/src/auth/settings/template-utils.ts +44 -0
- package/src/auth/settings/token-service.ts +88 -0
- package/src/auth/system-env-store.ts +98 -0
- package/src/auth/user-agents-store.ts +68 -0
- package/src/channels/binding-service.ts +214 -0
- package/src/channels/index.ts +4 -0
- package/src/cli/gateway.ts +1304 -0
- package/src/cli/index.ts +74 -0
- package/src/commands/built-in-commands.ts +80 -0
- package/src/commands/command-dispatcher.ts +94 -0
- package/src/commands/command-reply-adapters.ts +27 -0
- package/src/config/file-loader.ts +618 -0
- package/src/config/index.ts +588 -0
- package/src/config/network-allowlist.ts +71 -0
- package/src/connections/chat-instance-manager.ts +1284 -0
- package/src/connections/chat-response-bridge.ts +618 -0
- package/src/connections/index.ts +7 -0
- package/src/connections/interaction-bridge.ts +831 -0
- package/src/connections/message-handler-bridge.ts +415 -0
- package/src/connections/platform-auth-methods.ts +15 -0
- package/src/connections/types.ts +84 -0
- package/src/gateway/connection-manager.ts +291 -0
- package/src/gateway/index.ts +700 -0
- package/src/gateway/job-router.ts +201 -0
- package/src/gateway-main.ts +200 -0
- package/src/index.ts +41 -0
- package/src/infrastructure/queue/index.ts +12 -0
- package/src/infrastructure/queue/queue-producer.ts +148 -0
- package/src/infrastructure/queue/redis-queue.ts +361 -0
- package/src/infrastructure/queue/types.ts +133 -0
- package/src/infrastructure/redis/system-message-limiter.ts +94 -0
- package/src/interactions/config-request-store.ts +198 -0
- package/src/interactions.ts +363 -0
- package/src/lobu.ts +311 -0
- package/src/metrics/prometheus.ts +159 -0
- package/src/modules/module-system.ts +179 -0
- package/src/orchestration/base-deployment-manager.ts +900 -0
- package/src/orchestration/deployment-utils.ts +98 -0
- package/src/orchestration/impl/docker-deployment.ts +620 -0
- package/src/orchestration/impl/embedded-deployment.ts +268 -0
- package/src/orchestration/impl/index.ts +8 -0
- package/src/orchestration/impl/k8s/deployment.ts +1061 -0
- package/src/orchestration/impl/k8s/helpers.ts +610 -0
- package/src/orchestration/impl/k8s/index.ts +1 -0
- package/src/orchestration/index.ts +333 -0
- package/src/orchestration/message-consumer.ts +584 -0
- package/src/orchestration/scheduled-wakeup.ts +704 -0
- package/src/permissions/approval-policy.ts +36 -0
- package/src/permissions/grant-store.ts +219 -0
- package/src/platform/file-handler.ts +66 -0
- package/src/platform/link-buttons.ts +57 -0
- package/src/platform/renderer-utils.ts +44 -0
- package/src/platform/response-renderer.ts +84 -0
- package/src/platform/unified-thread-consumer.ts +187 -0
- package/src/platform.ts +318 -0
- package/src/proxy/http-proxy.ts +752 -0
- package/src/proxy/proxy-manager.ts +81 -0
- package/src/proxy/secret-proxy.ts +402 -0
- package/src/proxy/token-refresh-job.ts +143 -0
- package/src/routes/internal/audio.ts +141 -0
- package/src/routes/internal/device-auth.ts +566 -0
- package/src/routes/internal/files.ts +226 -0
- package/src/routes/internal/history.ts +69 -0
- package/src/routes/internal/images.ts +127 -0
- package/src/routes/internal/interactions.ts +84 -0
- package/src/routes/internal/middleware.ts +23 -0
- package/src/routes/internal/schedule.ts +226 -0
- package/src/routes/internal/types.ts +22 -0
- package/src/routes/openapi-auto.ts +239 -0
- package/src/routes/public/agent-access.ts +23 -0
- package/src/routes/public/agent-config.ts +675 -0
- package/src/routes/public/agent-history.ts +422 -0
- package/src/routes/public/agent-schedules.ts +296 -0
- package/src/routes/public/agent.ts +1086 -0
- package/src/routes/public/agents.ts +373 -0
- package/src/routes/public/channels.ts +191 -0
- package/src/routes/public/cli-auth.ts +883 -0
- package/src/routes/public/connections.ts +574 -0
- package/src/routes/public/landing.ts +16 -0
- package/src/routes/public/oauth.ts +147 -0
- package/src/routes/public/settings-auth.ts +104 -0
- package/src/routes/public/slack.ts +173 -0
- package/src/routes/shared/agent-ownership.ts +101 -0
- package/src/routes/shared/token-verifier.ts +34 -0
- package/src/services/core-services.ts +1053 -0
- package/src/services/image-generation-service.ts +257 -0
- package/src/services/instruction-service.ts +318 -0
- package/src/services/mcp-registry.ts +94 -0
- package/src/services/platform-helpers.ts +287 -0
- package/src/services/session-manager.ts +262 -0
- package/src/services/settings-resolver.ts +74 -0
- package/src/services/system-config-resolver.ts +90 -0
- package/src/services/system-skills-service.ts +229 -0
- package/src/services/transcription-service.ts +684 -0
- package/src/session.ts +110 -0
- package/src/spaces/index.ts +1 -0
- package/src/spaces/space-resolver.ts +17 -0
- package/src/stores/in-memory-agent-store.ts +403 -0
- package/src/stores/redis-agent-store.ts +279 -0
- package/src/utils/public-url.ts +44 -0
- package/src/utils/rate-limiter.ts +94 -0
- package/tsconfig.json +33 -0
|
@@ -0,0 +1,565 @@
|
|
|
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
|
+
}
|