apteva 0.4.57 → 0.7.0
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/README.md +216 -54
- package/cli.js +35 -0
- package/install.js +92 -0
- package/package.json +12 -79
- package/LICENSE +0 -63
- package/bin/apteva.js +0 -196
- package/dist/ActivityPage.kxzzb4yc.js +0 -3
- package/dist/ApiDocsPage.zq998hbm.js +0 -4
- package/dist/App.55rea8mn.js +0 -61
- package/dist/App.5ywb23z4.js +0 -53
- package/dist/App.6thds120.js +0 -4
- package/dist/App.9tctxzqm.js +0 -8
- package/dist/App.a8r8ttaz.js +0 -4
- package/dist/App.agsv5bje.js +0 -4
- package/dist/App.cepapqmx.js +0 -4
- package/dist/App.dp041gb3.js +0 -221
- package/dist/App.fds72zb5.js +0 -4
- package/dist/App.fg9qj2dq.js +0 -4
- package/dist/App.ndfejbm9.js +0 -4
- package/dist/App.nxmfmq1h.js +0 -13
- package/dist/App.qdfyt8ba.js +0 -4
- package/dist/App.x2d0ygt6.js +0 -4
- package/dist/App.yt9p4nr3.js +0 -20
- package/dist/App.zn4mw16t.js +0 -1
- package/dist/ConnectionsPage.8r96ryw7.js +0 -3
- package/dist/McpPage.3cwh0gnd.js +0 -3
- package/dist/SettingsPage.ykgdh5ev.js +0 -3
- package/dist/SkillsPage.4np1s65b.js +0 -3
- package/dist/TasksPage.4g08t7p6.js +0 -3
- package/dist/TelemetryPage.72w9pwcp.js +0 -3
- package/dist/TestsPage.z4fk3r7r.js +0 -3
- package/dist/ThreadsPage.63tcajeh.js +0 -3
- package/dist/apteva-kit.css +0 -1
- package/dist/icon.png +0 -0
- package/dist/index.html +0 -16
- package/dist/styles.css +0 -1
- package/scripts/postinstall.mjs +0 -102
- package/src/auth/index.ts +0 -394
- package/src/auth/middleware.ts +0 -213
- package/src/binary.ts +0 -536
- package/src/channels/index.ts +0 -40
- package/src/channels/telegram.ts +0 -311
- package/src/crypto.ts +0 -301
- package/src/db-tests.ts +0 -174
- package/src/db.ts +0 -3133
- package/src/integrations/agentdojo.ts +0 -559
- package/src/integrations/composio.ts +0 -437
- package/src/integrations/index.ts +0 -87
- package/src/integrations/skillsmp.ts +0 -318
- package/src/mcp-client.ts +0 -605
- package/src/mcp-handler.ts +0 -394
- package/src/mcp-platform.ts +0 -2403
- package/src/openapi.ts +0 -2410
- package/src/providers.ts +0 -597
- package/src/routes/api/agent-utils.ts +0 -890
- package/src/routes/api/agents.ts +0 -916
- package/src/routes/api/api-keys.ts +0 -95
- package/src/routes/api/channels.ts +0 -182
- package/src/routes/api/helpers.ts +0 -12
- package/src/routes/api/integrations.ts +0 -639
- package/src/routes/api/mcp.ts +0 -574
- package/src/routes/api/meta-agent.ts +0 -195
- package/src/routes/api/projects.ts +0 -112
- package/src/routes/api/providers.ts +0 -424
- package/src/routes/api/skills.ts +0 -537
- package/src/routes/api/system.ts +0 -333
- package/src/routes/api/telemetry.ts +0 -203
- package/src/routes/api/tests.ts +0 -148
- package/src/routes/api/triggers.ts +0 -518
- package/src/routes/api/users.ts +0 -148
- package/src/routes/api/webhooks.ts +0 -171
- package/src/routes/api.ts +0 -53
- package/src/routes/auth.ts +0 -251
- package/src/routes/share.ts +0 -86
- package/src/routes/static.ts +0 -131
- package/src/server.ts +0 -642
- package/src/test-runner.ts +0 -598
- package/src/triggers/agentdojo.ts +0 -253
- package/src/triggers/composio.ts +0 -264
- package/src/triggers/index.ts +0 -71
- package/src/tui/AgentList.tsx +0 -145
- package/src/tui/App.tsx +0 -102
- package/src/tui/Login.tsx +0 -104
- package/src/tui/api.ts +0 -72
- package/src/tui/index.tsx +0 -7
- package/src/web/App.tsx +0 -455
- package/src/web/components/activity/ActivityPage.tsx +0 -314
- package/src/web/components/activity/index.ts +0 -1
- package/src/web/components/agents/AgentCard.tsx +0 -189
- package/src/web/components/agents/AgentPanel.tsx +0 -2244
- package/src/web/components/agents/AgentsView.tsx +0 -180
- package/src/web/components/agents/CreateAgentModal.tsx +0 -475
- package/src/web/components/agents/index.ts +0 -4
- package/src/web/components/api/ApiDocsPage.tsx +0 -842
- package/src/web/components/auth/CreateAccountStep.tsx +0 -176
- package/src/web/components/auth/LoginPage.tsx +0 -91
- package/src/web/components/auth/index.ts +0 -2
- package/src/web/components/common/Icons.tsx +0 -250
- package/src/web/components/common/LoadingSpinner.tsx +0 -44
- package/src/web/components/common/Modal.tsx +0 -199
- package/src/web/components/common/Select.tsx +0 -97
- package/src/web/components/common/index.ts +0 -20
- package/src/web/components/connections/ConnectionsPage.tsx +0 -54
- package/src/web/components/connections/IntegrationsTab.tsx +0 -170
- package/src/web/components/connections/OverviewTab.tsx +0 -137
- package/src/web/components/connections/TriggersTab.tsx +0 -1346
- package/src/web/components/dashboard/Dashboard.tsx +0 -572
- package/src/web/components/dashboard/index.ts +0 -1
- package/src/web/components/index.ts +0 -21
- package/src/web/components/layout/ErrorBanner.tsx +0 -18
- package/src/web/components/layout/Header.tsx +0 -332
- package/src/web/components/layout/Sidebar.tsx +0 -231
- package/src/web/components/layout/index.ts +0 -3
- package/src/web/components/mcp/IntegrationsPanel.tsx +0 -857
- package/src/web/components/mcp/McpPage.tsx +0 -2515
- package/src/web/components/mcp/index.ts +0 -1
- package/src/web/components/meta-agent/MetaAgent.tsx +0 -245
- package/src/web/components/onboarding/OnboardingWizard.tsx +0 -404
- package/src/web/components/onboarding/index.ts +0 -1
- package/src/web/components/settings/SettingsPage.tsx +0 -2776
- package/src/web/components/settings/index.ts +0 -1
- package/src/web/components/skills/SkillsPage.tsx +0 -1200
- package/src/web/components/tasks/TasksPage.tsx +0 -1116
- package/src/web/components/tasks/index.ts +0 -1
- package/src/web/components/telemetry/TelemetryPage.tsx +0 -1129
- package/src/web/components/tests/TestsPage.tsx +0 -594
- package/src/web/components/threads/ThreadsPage.tsx +0 -315
- package/src/web/context/AuthContext.tsx +0 -242
- package/src/web/context/ProjectContext.tsx +0 -214
- package/src/web/context/TelemetryContext.tsx +0 -299
- package/src/web/context/ThemeContext.tsx +0 -90
- package/src/web/context/UIModeContext.tsx +0 -49
- package/src/web/context/index.ts +0 -12
- package/src/web/hooks/index.ts +0 -3
- package/src/web/hooks/useAgents.ts +0 -115
- package/src/web/hooks/useOnboarding.ts +0 -20
- package/src/web/hooks/useProviders.ts +0 -75
- package/src/web/icon.png +0 -0
- package/src/web/index.html +0 -16
- package/src/web/styles.css +0 -118
- package/src/web/themes.ts +0 -162
- package/src/web/types.ts +0 -298
package/src/channels/telegram.ts
DELETED
|
@@ -1,311 +0,0 @@
|
|
|
1
|
-
import { Bot } from "grammy";
|
|
2
|
-
import { AgentDB, ChannelDB } from "../db";
|
|
3
|
-
import { decryptObject } from "../crypto";
|
|
4
|
-
import { agentFetch } from "../routes/api/agent-utils";
|
|
5
|
-
|
|
6
|
-
interface TelegramConfig {
|
|
7
|
-
botToken: string;
|
|
8
|
-
allowList?: string[]; // Telegram user IDs allowed to chat
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
// In-memory map of running bot instances
|
|
12
|
-
const activeBots = new Map<string, Bot>();
|
|
13
|
-
|
|
14
|
-
export function isChannelActive(channelId: string): boolean {
|
|
15
|
-
return activeBots.has(channelId);
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export async function startTelegramChannel(channelId: string): Promise<{ success: boolean; error?: string }> {
|
|
19
|
-
// Stop existing if running
|
|
20
|
-
if (activeBots.has(channelId)) {
|
|
21
|
-
await stopTelegramChannel(channelId);
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
const channel = ChannelDB.findById(channelId);
|
|
25
|
-
if (!channel) return { success: false, error: "Channel not found" };
|
|
26
|
-
|
|
27
|
-
let config: TelegramConfig;
|
|
28
|
-
try {
|
|
29
|
-
config = decryptObject(channel.config) as unknown as TelegramConfig;
|
|
30
|
-
} catch {
|
|
31
|
-
ChannelDB.setStatus(channelId, "error", "Failed to decrypt config");
|
|
32
|
-
return { success: false, error: "Failed to decrypt config" };
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
if (!config.botToken) {
|
|
36
|
-
ChannelDB.setStatus(channelId, "error", "Missing bot token");
|
|
37
|
-
return { success: false, error: "Missing bot token" };
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
const agent = AgentDB.findById(channel.agent_id);
|
|
41
|
-
if (!agent) {
|
|
42
|
-
ChannelDB.setStatus(channelId, "error", "Agent not found");
|
|
43
|
-
return { success: false, error: "Agent not found" };
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
try {
|
|
47
|
-
const bot = new Bot(config.botToken);
|
|
48
|
-
|
|
49
|
-
// /start command
|
|
50
|
-
bot.command("start", async (ctx) => {
|
|
51
|
-
await ctx.reply(`Connected to agent: ${agent.name}`);
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
// Handle text messages
|
|
55
|
-
bot.on("message:text", async (ctx) => {
|
|
56
|
-
// Access control
|
|
57
|
-
if (config.allowList?.length) {
|
|
58
|
-
const senderId = String(ctx.from.id);
|
|
59
|
-
if (!config.allowList.includes(senderId)) return;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// Check agent is running
|
|
63
|
-
const currentAgent = AgentDB.findById(channel.agent_id);
|
|
64
|
-
if (!currentAgent || currentAgent.status !== "running" || !currentAgent.port) {
|
|
65
|
-
await ctx.reply("Agent is not running.");
|
|
66
|
-
return;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// Send typing indicator
|
|
70
|
-
await ctx.replyWithChatAction("typing");
|
|
71
|
-
|
|
72
|
-
try {
|
|
73
|
-
// Map telegram chat → agent thread
|
|
74
|
-
const threadId = `telegram-${ctx.chat.id}`;
|
|
75
|
-
|
|
76
|
-
// Proxy to agent via agentFetch (same path as web UI chat)
|
|
77
|
-
const res = await agentFetch(currentAgent.id, currentAgent.port, "/chat", {
|
|
78
|
-
method: "POST",
|
|
79
|
-
headers: { "Content-Type": "application/json" },
|
|
80
|
-
body: JSON.stringify({
|
|
81
|
-
message: ctx.message.text,
|
|
82
|
-
thread_id: threadId,
|
|
83
|
-
}),
|
|
84
|
-
});
|
|
85
|
-
|
|
86
|
-
if (!res.ok) {
|
|
87
|
-
await ctx.reply("Error: agent returned an error.");
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// Stream response and send messages progressively as segments complete
|
|
92
|
-
await streamAndSend(res, ctx);
|
|
93
|
-
} catch (err) {
|
|
94
|
-
console.error(`[telegram:${channelId}] Message handling error:`, err);
|
|
95
|
-
await ctx.reply("Error processing your message.");
|
|
96
|
-
}
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
// Error handler
|
|
100
|
-
bot.catch((err) => {
|
|
101
|
-
console.error(`[telegram:${channelId}] Bot error:`, err);
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
// Start long-polling (non-blocking)
|
|
105
|
-
bot.start({
|
|
106
|
-
onStart: () => {
|
|
107
|
-
console.log(`[telegram:${channelId}] Bot started for agent ${agent.name}`);
|
|
108
|
-
},
|
|
109
|
-
});
|
|
110
|
-
|
|
111
|
-
activeBots.set(channelId, bot);
|
|
112
|
-
ChannelDB.setStatus(channelId, "running");
|
|
113
|
-
return { success: true };
|
|
114
|
-
} catch (err: any) {
|
|
115
|
-
const errorMsg = err.message || String(err);
|
|
116
|
-
console.error(`[telegram:${channelId}] Failed to start:`, errorMsg);
|
|
117
|
-
ChannelDB.setStatus(channelId, "error", errorMsg);
|
|
118
|
-
return { success: false, error: errorMsg };
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
export async function stopTelegramChannel(channelId: string): Promise<void> {
|
|
123
|
-
const bot = activeBots.get(channelId);
|
|
124
|
-
if (bot) {
|
|
125
|
-
try {
|
|
126
|
-
await bot.stop();
|
|
127
|
-
} catch {
|
|
128
|
-
// Ignore stop errors
|
|
129
|
-
}
|
|
130
|
-
activeBots.delete(channelId);
|
|
131
|
-
}
|
|
132
|
-
ChannelDB.setStatus(channelId, "stopped");
|
|
133
|
-
console.log(`[telegram:${channelId}] Bot stopped`);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Stream SSE response from agent and send Telegram messages progressively.
|
|
138
|
-
* Mirrors the chunk types from apteva-kit's chat component:
|
|
139
|
-
* content/token → accumulate text, send when a boundary is hit
|
|
140
|
-
* tool_call → flush pending text, send tool indicator immediately
|
|
141
|
-
* tool_use, tool_input_delta, tool_result, tool_stream → skipped
|
|
142
|
-
*
|
|
143
|
-
* Messages are sent as soon as each segment completes (tool boundary or end of stream),
|
|
144
|
-
* so the user sees them appear progressively in real-time.
|
|
145
|
-
*/
|
|
146
|
-
async function streamAndSend(
|
|
147
|
-
res: Response,
|
|
148
|
-
ctx: { reply: (text: string, opts?: any) => Promise<any>; replyWithChatAction: (action: string) => Promise<any> },
|
|
149
|
-
onActivity?: () => void,
|
|
150
|
-
): Promise<void> {
|
|
151
|
-
if (!res.body) {
|
|
152
|
-
await ctx.reply("(No response from agent)");
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
const reader = res.body.getReader();
|
|
157
|
-
const decoder = new TextDecoder();
|
|
158
|
-
let textBuffer = "";
|
|
159
|
-
let buffer = "";
|
|
160
|
-
let messagesSent = 0;
|
|
161
|
-
|
|
162
|
-
async function flushText() {
|
|
163
|
-
const trimmed = textBuffer.trim();
|
|
164
|
-
if (trimmed) {
|
|
165
|
-
const chunks = splitMessage(trimmed, 4096);
|
|
166
|
-
for (const chunk of chunks) {
|
|
167
|
-
try {
|
|
168
|
-
await ctx.reply(chunk, { parse_mode: "Markdown" });
|
|
169
|
-
} catch {
|
|
170
|
-
await ctx.reply(chunk);
|
|
171
|
-
}
|
|
172
|
-
messagesSent++;
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
textBuffer = "";
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// Periodically send typing indicator while streaming
|
|
179
|
-
const typingInterval = setInterval(() => {
|
|
180
|
-
ctx.replyWithChatAction("typing").catch(() => {});
|
|
181
|
-
}, 4000);
|
|
182
|
-
|
|
183
|
-
try {
|
|
184
|
-
while (true) {
|
|
185
|
-
const { done, value } = await reader.read();
|
|
186
|
-
if (done) break;
|
|
187
|
-
|
|
188
|
-
buffer += decoder.decode(value, { stream: true });
|
|
189
|
-
|
|
190
|
-
const lines = buffer.split("\n");
|
|
191
|
-
buffer = lines.pop() || "";
|
|
192
|
-
|
|
193
|
-
for (const line of lines) {
|
|
194
|
-
if (!line.startsWith("data: ")) continue;
|
|
195
|
-
const data = line.slice(6).trim();
|
|
196
|
-
if (data === "[DONE]") continue;
|
|
197
|
-
|
|
198
|
-
try {
|
|
199
|
-
const chunk = JSON.parse(data);
|
|
200
|
-
|
|
201
|
-
switch (chunk.type) {
|
|
202
|
-
// Text content — accumulate
|
|
203
|
-
case "content":
|
|
204
|
-
case "token":
|
|
205
|
-
if (chunk.content) textBuffer += chunk.content;
|
|
206
|
-
else if (chunk.text) textBuffer += chunk.text;
|
|
207
|
-
break;
|
|
208
|
-
|
|
209
|
-
// Tool starting — flush text immediately, then send tool indicator
|
|
210
|
-
case "tool_call": {
|
|
211
|
-
await flushText();
|
|
212
|
-
const name = chunk.tool_display_name || chunk.tool_name || "tool";
|
|
213
|
-
try {
|
|
214
|
-
await ctx.reply(`🔧 _${escapeMarkdown(name)}_`, { parse_mode: "Markdown" });
|
|
215
|
-
} catch {
|
|
216
|
-
await ctx.reply(`🔧 ${name}`);
|
|
217
|
-
}
|
|
218
|
-
messagesSent++;
|
|
219
|
-
break;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
// Thinking — strip, never send to channel
|
|
223
|
-
case "thinking":
|
|
224
|
-
case "thinking_delta":
|
|
225
|
-
break;
|
|
226
|
-
|
|
227
|
-
// Intermediate tool events — skip, but signal activity
|
|
228
|
-
case "tool_input_delta":
|
|
229
|
-
case "tool_use":
|
|
230
|
-
case "tool_stream":
|
|
231
|
-
case "tool_result":
|
|
232
|
-
onActivity?.();
|
|
233
|
-
break;
|
|
234
|
-
|
|
235
|
-
// Fallback: older SSE formats
|
|
236
|
-
case "message_delta":
|
|
237
|
-
if (chunk.delta?.text) textBuffer += chunk.delta.text;
|
|
238
|
-
break;
|
|
239
|
-
case "content_block_delta":
|
|
240
|
-
if (chunk.delta?.text) textBuffer += chunk.delta.text;
|
|
241
|
-
break;
|
|
242
|
-
|
|
243
|
-
default:
|
|
244
|
-
if (chunk.content && typeof chunk.content === "string") {
|
|
245
|
-
textBuffer += chunk.content;
|
|
246
|
-
} else if (typeof chunk.text === "string") {
|
|
247
|
-
textBuffer += chunk.text;
|
|
248
|
-
}
|
|
249
|
-
break;
|
|
250
|
-
}
|
|
251
|
-
} catch {
|
|
252
|
-
if (data && data !== "[DONE]") {
|
|
253
|
-
textBuffer += data;
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
} catch {
|
|
259
|
-
// Stream read error — flush what we have
|
|
260
|
-
} finally {
|
|
261
|
-
clearInterval(typingInterval);
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
// Flush remaining text
|
|
265
|
-
await flushText();
|
|
266
|
-
|
|
267
|
-
if (messagesSent === 0) {
|
|
268
|
-
await ctx.reply("(No response from agent)");
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/**
|
|
273
|
-
* Escape special Markdown characters for Telegram Markdown parse mode.
|
|
274
|
-
*/
|
|
275
|
-
function escapeMarkdown(text: string): string {
|
|
276
|
-
return text.replace(/([_*\[\]()~`>#+\-=|{}.!\\])/g, "\\$1");
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/**
|
|
280
|
-
* Split a message into chunks respecting the max length.
|
|
281
|
-
* Tries to split at newlines when possible.
|
|
282
|
-
*/
|
|
283
|
-
function splitMessage(text: string, maxLength: number): string[] {
|
|
284
|
-
if (text.length <= maxLength) return [text];
|
|
285
|
-
|
|
286
|
-
const chunks: string[] = [];
|
|
287
|
-
let remaining = text;
|
|
288
|
-
|
|
289
|
-
while (remaining.length > 0) {
|
|
290
|
-
if (remaining.length <= maxLength) {
|
|
291
|
-
chunks.push(remaining);
|
|
292
|
-
break;
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
// Try to find a newline near the limit
|
|
296
|
-
let splitAt = remaining.lastIndexOf("\n", maxLength);
|
|
297
|
-
if (splitAt < maxLength * 0.5) {
|
|
298
|
-
// No good newline found — split at space
|
|
299
|
-
splitAt = remaining.lastIndexOf(" ", maxLength);
|
|
300
|
-
}
|
|
301
|
-
if (splitAt < maxLength * 0.3) {
|
|
302
|
-
// No good split point — hard split
|
|
303
|
-
splitAt = maxLength;
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
chunks.push(remaining.slice(0, splitAt));
|
|
307
|
-
remaining = remaining.slice(splitAt).trimStart();
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
return chunks;
|
|
311
|
-
}
|
package/src/crypto.ts
DELETED
|
@@ -1,301 +0,0 @@
|
|
|
1
|
-
import { createCipheriv, createDecipheriv, randomBytes, scryptSync, createHash } from "crypto";
|
|
2
|
-
import { hostname, userInfo } from "os";
|
|
3
|
-
import { join } from "path";
|
|
4
|
-
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
|
|
5
|
-
import { homedir } from "os";
|
|
6
|
-
|
|
7
|
-
const ALGORITHM = "aes-256-gcm";
|
|
8
|
-
const IV_LENGTH = 16;
|
|
9
|
-
const SALT_LENGTH = 32;
|
|
10
|
-
const TAG_LENGTH = 16;
|
|
11
|
-
const KEY_LENGTH = 32;
|
|
12
|
-
|
|
13
|
-
// Cache the encryption secret to avoid repeated file reads
|
|
14
|
-
let cachedSecret: string | null = null;
|
|
15
|
-
|
|
16
|
-
// Get the path for storing the encryption secret
|
|
17
|
-
function getSecretPath(): string {
|
|
18
|
-
const dataDir = process.env.DATA_DIR || join(homedir(), ".apteva");
|
|
19
|
-
return join(dataDir, ".encryption-key");
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
// Get or create a persistent encryption secret
|
|
23
|
-
// This ensures keys can be decrypted after container/app restarts
|
|
24
|
-
function getOrCreateSecret(): string {
|
|
25
|
-
if (cachedSecret) return cachedSecret;
|
|
26
|
-
|
|
27
|
-
const secretPath = getSecretPath();
|
|
28
|
-
|
|
29
|
-
// Try to read existing secret
|
|
30
|
-
if (existsSync(secretPath)) {
|
|
31
|
-
try {
|
|
32
|
-
cachedSecret = readFileSync(secretPath, "utf8").trim();
|
|
33
|
-
if (cachedSecret && cachedSecret.length >= 32) {
|
|
34
|
-
return cachedSecret;
|
|
35
|
-
}
|
|
36
|
-
} catch {
|
|
37
|
-
// Fall through to create new
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// Create new secret and persist it
|
|
42
|
-
cachedSecret = randomBytes(32).toString("hex");
|
|
43
|
-
try {
|
|
44
|
-
const dir = process.env.DATA_DIR || join(homedir(), ".apteva");
|
|
45
|
-
if (!existsSync(dir)) {
|
|
46
|
-
mkdirSync(dir, { recursive: true });
|
|
47
|
-
}
|
|
48
|
-
writeFileSync(secretPath, cachedSecret, { mode: 0o600 });
|
|
49
|
-
} catch (err) {
|
|
50
|
-
console.error("[crypto] Warning: Could not persist encryption key:", err);
|
|
51
|
-
// Continue with in-memory key - will work for this session but not across restarts
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
return cachedSecret;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
// Get a machine-specific identifier for key derivation
|
|
58
|
-
// Now uses a persistent secret instead of volatile machine factors
|
|
59
|
-
function getMachineId(): string {
|
|
60
|
-
return getOrCreateSecret();
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// Derive encryption key from machine ID and salt
|
|
64
|
-
function deriveKey(salt: Buffer): Buffer {
|
|
65
|
-
const machineId = getMachineId();
|
|
66
|
-
return scryptSync(machineId, salt, KEY_LENGTH);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
// Create a hash hint of the last 4 characters of a key
|
|
70
|
-
export function createKeyHint(key: string): string {
|
|
71
|
-
if (key.length < 4) return "****";
|
|
72
|
-
return "..." + key.slice(-4);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Encrypt a string value
|
|
77
|
-
* Returns: base64 encoded string containing salt + iv + encrypted + authTag
|
|
78
|
-
*/
|
|
79
|
-
export function encrypt(plaintext: string): string {
|
|
80
|
-
const salt = randomBytes(SALT_LENGTH);
|
|
81
|
-
const key = deriveKey(salt);
|
|
82
|
-
const iv = randomBytes(IV_LENGTH);
|
|
83
|
-
|
|
84
|
-
const cipher = createCipheriv(ALGORITHM, key, iv);
|
|
85
|
-
const encrypted = Buffer.concat([
|
|
86
|
-
cipher.update(plaintext, "utf8"),
|
|
87
|
-
cipher.final(),
|
|
88
|
-
]);
|
|
89
|
-
const authTag = cipher.getAuthTag();
|
|
90
|
-
|
|
91
|
-
// Combine: salt (32) + iv (16) + authTag (16) + encrypted (variable)
|
|
92
|
-
const combined = Buffer.concat([salt, iv, authTag, encrypted]);
|
|
93
|
-
return combined.toString("base64");
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Decrypt a previously encrypted value
|
|
98
|
-
* Input: base64 encoded string from encrypt()
|
|
99
|
-
*/
|
|
100
|
-
export function decrypt(encryptedBase64: string): string {
|
|
101
|
-
const combined = Buffer.from(encryptedBase64, "base64");
|
|
102
|
-
|
|
103
|
-
// Extract components
|
|
104
|
-
const salt = combined.subarray(0, SALT_LENGTH);
|
|
105
|
-
const iv = combined.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
|
|
106
|
-
const authTag = combined.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
|
|
107
|
-
const encrypted = combined.subarray(SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
|
|
108
|
-
|
|
109
|
-
const key = deriveKey(salt);
|
|
110
|
-
|
|
111
|
-
const decipher = createDecipheriv(ALGORITHM, key, iv);
|
|
112
|
-
decipher.setAuthTag(authTag);
|
|
113
|
-
|
|
114
|
-
const decrypted = Buffer.concat([
|
|
115
|
-
decipher.update(encrypted),
|
|
116
|
-
decipher.final(),
|
|
117
|
-
]);
|
|
118
|
-
|
|
119
|
-
return decrypted.toString("utf8");
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/**
|
|
123
|
-
* Hash a value (one-way, for checking if key changed)
|
|
124
|
-
*/
|
|
125
|
-
export function hash(value: string): string {
|
|
126
|
-
return createHash("sha256").update(value).digest("hex");
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/**
|
|
130
|
-
* Validate that a string looks like an API key for a given provider
|
|
131
|
-
*/
|
|
132
|
-
export function validateKeyFormat(provider: string, key: string): { valid: boolean; error?: string } {
|
|
133
|
-
const trimmed = key.trim();
|
|
134
|
-
|
|
135
|
-
if (!trimmed) {
|
|
136
|
-
return { valid: false, error: "API key cannot be empty" };
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
// Local providers use URLs instead of API keys
|
|
140
|
-
const urlProviders: Record<string, string> = {
|
|
141
|
-
ollama: "http://localhost:11434",
|
|
142
|
-
cdp: "ws://localhost:9222",
|
|
143
|
-
speaches: "http://localhost:8000",
|
|
144
|
-
whisper_cpp: "http://localhost:8080",
|
|
145
|
-
kokoro: "http://localhost:8880",
|
|
146
|
-
piper: "http://localhost:5000",
|
|
147
|
-
fish_speech: "http://localhost:8180",
|
|
148
|
-
};
|
|
149
|
-
if (provider in urlProviders) {
|
|
150
|
-
if (trimmed.startsWith("http://") || trimmed.startsWith("https://") || trimmed.startsWith("ws://") || trimmed.startsWith("wss://")) {
|
|
151
|
-
return { valid: true };
|
|
152
|
-
}
|
|
153
|
-
return { valid: false, error: `${provider} requires a valid URL (e.g., ${urlProviders[provider]})` };
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
// Multi-field providers store JSON objects — validate the inner api_key
|
|
157
|
-
if (provider === "browserbase") {
|
|
158
|
-
try {
|
|
159
|
-
const parsed = JSON.parse(trimmed);
|
|
160
|
-
if (parsed.api_key && typeof parsed.api_key === "string") {
|
|
161
|
-
return { valid: true };
|
|
162
|
-
}
|
|
163
|
-
} catch {
|
|
164
|
-
// Not JSON — treat as plain API key (backwards compat)
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
// Provider-specific format validation
|
|
169
|
-
const patterns: Record<string, { pattern: RegExp; example: string }> = {
|
|
170
|
-
anthropic: {
|
|
171
|
-
pattern: /^sk-ant-[a-zA-Z0-9_-]+$/,
|
|
172
|
-
example: "sk-ant-...",
|
|
173
|
-
},
|
|
174
|
-
openai: {
|
|
175
|
-
pattern: /^sk-[a-zA-Z0-9_-]+$/,
|
|
176
|
-
example: "sk-...",
|
|
177
|
-
},
|
|
178
|
-
groq: {
|
|
179
|
-
pattern: /^gsk_[a-zA-Z0-9_-]+$/,
|
|
180
|
-
example: "gsk_...",
|
|
181
|
-
},
|
|
182
|
-
gemini: {
|
|
183
|
-
pattern: /^[a-zA-Z0-9_-]+$/,
|
|
184
|
-
example: "AIza...",
|
|
185
|
-
},
|
|
186
|
-
fireworks: {
|
|
187
|
-
pattern: /^fw_[a-zA-Z0-9_-]+$|^[a-zA-Z0-9_-]+$/,
|
|
188
|
-
example: "fw_...",
|
|
189
|
-
},
|
|
190
|
-
xai: {
|
|
191
|
-
pattern: /^xai-[a-zA-Z0-9_-]+$|^[a-zA-Z0-9_-]+$/,
|
|
192
|
-
example: "xai-...",
|
|
193
|
-
},
|
|
194
|
-
moonshot: {
|
|
195
|
-
pattern: /^sk-[a-zA-Z0-9_-]+$|^[a-zA-Z0-9_-]+$/,
|
|
196
|
-
example: "sk-...",
|
|
197
|
-
},
|
|
198
|
-
together: {
|
|
199
|
-
pattern: /^[a-zA-Z0-9_-]+$/,
|
|
200
|
-
example: "...",
|
|
201
|
-
},
|
|
202
|
-
venice: {
|
|
203
|
-
pattern: /^[a-zA-Z0-9_-]+$/,
|
|
204
|
-
example: "...",
|
|
205
|
-
},
|
|
206
|
-
cerebras: {
|
|
207
|
-
pattern: /^csk-[a-zA-Z0-9_-]+$|^[a-zA-Z0-9_-]+$/,
|
|
208
|
-
example: "csk-...",
|
|
209
|
-
},
|
|
210
|
-
// MCP Integrations
|
|
211
|
-
composio: {
|
|
212
|
-
pattern: /^[a-zA-Z0-9_-]+$/,
|
|
213
|
-
example: "...",
|
|
214
|
-
},
|
|
215
|
-
smithery: {
|
|
216
|
-
pattern: /^[a-zA-Z0-9_-]+$/,
|
|
217
|
-
example: "...",
|
|
218
|
-
},
|
|
219
|
-
agentdojo: {
|
|
220
|
-
pattern: /^(key_)?[a-zA-Z0-9_-]+$/,
|
|
221
|
-
example: "key_...",
|
|
222
|
-
},
|
|
223
|
-
// Voice providers
|
|
224
|
-
elevenlabs: {
|
|
225
|
-
pattern: /^[a-zA-Z0-9_-]+$/,
|
|
226
|
-
example: "sk_...",
|
|
227
|
-
},
|
|
228
|
-
deepgram: {
|
|
229
|
-
pattern: /^[a-zA-Z0-9_-]+$/,
|
|
230
|
-
example: "...",
|
|
231
|
-
},
|
|
232
|
-
// Browser providers
|
|
233
|
-
browserbase: {
|
|
234
|
-
pattern: /^bb_[a-zA-Z0-9_-]+$|^[a-zA-Z0-9_-]+$/,
|
|
235
|
-
example: "bb_live_...",
|
|
236
|
-
},
|
|
237
|
-
steel: {
|
|
238
|
-
pattern: /^steel_[a-zA-Z0-9_-]+$|^[a-zA-Z0-9_-]+$/,
|
|
239
|
-
example: "steel_...",
|
|
240
|
-
},
|
|
241
|
-
};
|
|
242
|
-
|
|
243
|
-
const providerPattern = patterns[provider];
|
|
244
|
-
if (providerPattern && !providerPattern.pattern.test(trimmed)) {
|
|
245
|
-
return {
|
|
246
|
-
valid: false,
|
|
247
|
-
error: `Invalid key format for ${provider}. Expected format: ${providerPattern.example}`,
|
|
248
|
-
};
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// Minimum length check
|
|
252
|
-
if (trimmed.length < 10) {
|
|
253
|
-
return { valid: false, error: "API key seems too short" };
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
return { valid: true };
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/**
|
|
260
|
-
* Encrypt an object (for env vars / credentials)
|
|
261
|
-
* Returns encrypted JSON string
|
|
262
|
-
*/
|
|
263
|
-
export function encryptObject(obj: Record<string, string>): string {
|
|
264
|
-
if (!obj || Object.keys(obj).length === 0) {
|
|
265
|
-
return "";
|
|
266
|
-
}
|
|
267
|
-
return encrypt(JSON.stringify(obj));
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/**
|
|
271
|
-
* Decrypt an object (for env vars / credentials)
|
|
272
|
-
* Handles both encrypted and legacy unencrypted JSON
|
|
273
|
-
*/
|
|
274
|
-
export function decryptObject(data: string): Record<string, string> {
|
|
275
|
-
if (!data || data === "{}") {
|
|
276
|
-
return {};
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
// Check if it looks like encrypted data (base64) or plain JSON
|
|
280
|
-
if (data.startsWith("{")) {
|
|
281
|
-
// Plain JSON (legacy unencrypted)
|
|
282
|
-
try {
|
|
283
|
-
return JSON.parse(data);
|
|
284
|
-
} catch {
|
|
285
|
-
return {};
|
|
286
|
-
}
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
// Try to decrypt
|
|
290
|
-
try {
|
|
291
|
-
const decrypted = decrypt(data);
|
|
292
|
-
return JSON.parse(decrypted);
|
|
293
|
-
} catch {
|
|
294
|
-
// Decryption failed, try parsing as JSON (migration case)
|
|
295
|
-
try {
|
|
296
|
-
return JSON.parse(data);
|
|
297
|
-
} catch {
|
|
298
|
-
return {};
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
}
|