claude-wec 1.0.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.
Files changed (137) hide show
  1. package/LICENSE +675 -0
  2. package/README.md +371 -0
  3. package/dist/api-docs.html +879 -0
  4. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  5. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  6. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  7. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  8. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  9. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  10. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  11. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  12. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  13. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  14. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  15. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  16. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  17. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  18. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  19. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  20. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  21. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  22. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  23. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  24. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  25. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  26. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  27. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  28. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  29. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  30. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  31. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  32. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  33. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  34. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  35. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  36. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  37. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  38. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  39. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  40. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  41. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  42. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  43. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  44. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  45. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  46. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  47. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  48. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  49. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  50. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  51. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  52. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  53. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  54. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  55. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  56. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  57. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  58. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  59. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  60. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  61. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  62. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  63. package/dist/assets/index-cIxJ4RXb.js +1226 -0
  64. package/dist/assets/index-oyEz69sP.css +32 -0
  65. package/dist/assets/vendor-codemirror-CJLzwpLB.js +39 -0
  66. package/dist/assets/vendor-react-DcyRfQm3.js +59 -0
  67. package/dist/assets/vendor-xterm-DfaPXD3y.js +66 -0
  68. package/dist/clear-cache.html +85 -0
  69. package/dist/convert-icons.md +53 -0
  70. package/dist/favicon.png +0 -0
  71. package/dist/favicon.svg +9 -0
  72. package/dist/generate-icons.js +49 -0
  73. package/dist/icons/claude-ai-icon.svg +1 -0
  74. package/dist/icons/codex-white.svg +3 -0
  75. package/dist/icons/codex.svg +3 -0
  76. package/dist/icons/cursor-white.svg +12 -0
  77. package/dist/icons/cursor.svg +1 -0
  78. package/dist/icons/generate-icons.md +19 -0
  79. package/dist/icons/icon-128x128.png +0 -0
  80. package/dist/icons/icon-128x128.svg +12 -0
  81. package/dist/icons/icon-144x144.png +0 -0
  82. package/dist/icons/icon-144x144.svg +12 -0
  83. package/dist/icons/icon-152x152.png +0 -0
  84. package/dist/icons/icon-152x152.svg +12 -0
  85. package/dist/icons/icon-192x192.png +0 -0
  86. package/dist/icons/icon-192x192.svg +12 -0
  87. package/dist/icons/icon-384x384.png +0 -0
  88. package/dist/icons/icon-384x384.svg +12 -0
  89. package/dist/icons/icon-512x512.png +0 -0
  90. package/dist/icons/icon-512x512.svg +12 -0
  91. package/dist/icons/icon-72x72.png +0 -0
  92. package/dist/icons/icon-72x72.svg +12 -0
  93. package/dist/icons/icon-96x96.png +0 -0
  94. package/dist/icons/icon-96x96.svg +12 -0
  95. package/dist/icons/icon-template.svg +12 -0
  96. package/dist/index.html +52 -0
  97. package/dist/logo-128.png +0 -0
  98. package/dist/logo-256.png +0 -0
  99. package/dist/logo-32.png +0 -0
  100. package/dist/logo-512.png +0 -0
  101. package/dist/logo-64.png +0 -0
  102. package/dist/logo.svg +17 -0
  103. package/dist/manifest.json +61 -0
  104. package/dist/screenshots/cli-selection.png +0 -0
  105. package/dist/screenshots/desktop-main.png +0 -0
  106. package/dist/screenshots/mobile-chat.png +0 -0
  107. package/dist/screenshots/tools-modal.png +0 -0
  108. package/dist/sw.js +49 -0
  109. package/package.json +109 -0
  110. package/server/claude-sdk.js +721 -0
  111. package/server/cli.js +327 -0
  112. package/server/cursor-cli.js +267 -0
  113. package/server/database/auth.db +0 -0
  114. package/server/database/db.js +361 -0
  115. package/server/database/init.sql +52 -0
  116. package/server/index.js +1747 -0
  117. package/server/middleware/auth.js +111 -0
  118. package/server/openai-codex.js +389 -0
  119. package/server/projects.js +1604 -0
  120. package/server/routes/agent.js +1230 -0
  121. package/server/routes/auth.js +135 -0
  122. package/server/routes/cli-auth.js +263 -0
  123. package/server/routes/codex.js +345 -0
  124. package/server/routes/commands.js +521 -0
  125. package/server/routes/cursor.js +795 -0
  126. package/server/routes/git.js +1128 -0
  127. package/server/routes/mcp-utils.js +48 -0
  128. package/server/routes/mcp.js +552 -0
  129. package/server/routes/projects.js +378 -0
  130. package/server/routes/settings.js +178 -0
  131. package/server/routes/taskmaster.js +1963 -0
  132. package/server/routes/user.js +106 -0
  133. package/server/utils/commandParser.js +303 -0
  134. package/server/utils/gitConfig.js +24 -0
  135. package/server/utils/mcp-detector.js +198 -0
  136. package/server/utils/taskmaster-websocket.js +129 -0
  137. package/shared/modelConstants.js +65 -0
@@ -0,0 +1,378 @@
1
+ import express from 'express';
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import { spawn } from 'child_process';
5
+ import os from 'os';
6
+ import { addProjectManually } from '../projects.js';
7
+
8
+ const router = express.Router();
9
+
10
+ // Configure allowed workspace root (defaults to user's home directory)
11
+ const WORKSPACES_ROOT = process.env.WORKSPACES_ROOT || os.homedir();
12
+
13
+ // System-critical paths that should never be used as workspace directories
14
+ const FORBIDDEN_PATHS = [
15
+ '/',
16
+ '/etc',
17
+ '/bin',
18
+ '/sbin',
19
+ '/usr',
20
+ '/dev',
21
+ '/proc',
22
+ '/sys',
23
+ '/var',
24
+ '/boot',
25
+ '/root',
26
+ '/lib',
27
+ '/lib64',
28
+ '/opt',
29
+ '/tmp',
30
+ '/run'
31
+ ];
32
+
33
+ /**
34
+ * Validates that a path is safe for workspace operations
35
+ * @param {string} requestedPath - The path to validate
36
+ * @returns {Promise<{valid: boolean, resolvedPath?: string, error?: string}>}
37
+ */
38
+ async function validateWorkspacePath(requestedPath) {
39
+ try {
40
+ // Resolve to absolute path
41
+ let absolutePath = path.resolve(requestedPath);
42
+
43
+ // Check if path is a forbidden system directory
44
+ const normalizedPath = path.normalize(absolutePath);
45
+ if (FORBIDDEN_PATHS.includes(normalizedPath) || normalizedPath === '/') {
46
+ return {
47
+ valid: false,
48
+ error: 'Cannot use system-critical directories as workspace locations'
49
+ };
50
+ }
51
+
52
+ // Additional check for paths starting with forbidden directories
53
+ for (const forbidden of FORBIDDEN_PATHS) {
54
+ if (normalizedPath === forbidden ||
55
+ normalizedPath.startsWith(forbidden + path.sep)) {
56
+ // Exception: /var/tmp and similar user-accessible paths might be allowed
57
+ // but /var itself and most /var subdirectories should be blocked
58
+ if (forbidden === '/var' &&
59
+ (normalizedPath.startsWith('/var/tmp') ||
60
+ normalizedPath.startsWith('/var/folders'))) {
61
+ continue; // Allow these specific cases
62
+ }
63
+
64
+ return {
65
+ valid: false,
66
+ error: `Cannot create workspace in system directory: ${forbidden}`
67
+ };
68
+ }
69
+ }
70
+
71
+ // Try to resolve the real path (following symlinks)
72
+ let realPath;
73
+ try {
74
+ // Check if path exists to resolve real path
75
+ await fs.access(absolutePath);
76
+ realPath = await fs.realpath(absolutePath);
77
+ } catch (error) {
78
+ if (error.code === 'ENOENT') {
79
+ // Path doesn't exist yet - check parent directory
80
+ let parentPath = path.dirname(absolutePath);
81
+ try {
82
+ const parentRealPath = await fs.realpath(parentPath);
83
+
84
+ // Reconstruct the full path with real parent
85
+ realPath = path.join(parentRealPath, path.basename(absolutePath));
86
+ } catch (parentError) {
87
+ if (parentError.code === 'ENOENT') {
88
+ // Parent doesn't exist either - use the absolute path as-is
89
+ // We'll validate it's within allowed root
90
+ realPath = absolutePath;
91
+ } else {
92
+ throw parentError;
93
+ }
94
+ }
95
+ } else {
96
+ throw error;
97
+ }
98
+ }
99
+
100
+ // Resolve the workspace root to its real path
101
+ const resolvedWorkspaceRoot = await fs.realpath(WORKSPACES_ROOT);
102
+
103
+ // Ensure the resolved path is contained within the allowed workspace root
104
+ if (!realPath.startsWith(resolvedWorkspaceRoot + path.sep) &&
105
+ realPath !== resolvedWorkspaceRoot) {
106
+ return {
107
+ valid: false,
108
+ error: `Workspace path must be within the allowed workspace root: ${WORKSPACES_ROOT}`
109
+ };
110
+ }
111
+
112
+ // Additional symlink check for existing paths
113
+ try {
114
+ await fs.access(absolutePath);
115
+ const stats = await fs.lstat(absolutePath);
116
+
117
+ if (stats.isSymbolicLink()) {
118
+ // Verify symlink target is also within allowed root
119
+ const linkTarget = await fs.readlink(absolutePath);
120
+ const resolvedTarget = path.resolve(path.dirname(absolutePath), linkTarget);
121
+ const realTarget = await fs.realpath(resolvedTarget);
122
+
123
+ if (!realTarget.startsWith(resolvedWorkspaceRoot + path.sep) &&
124
+ realTarget !== resolvedWorkspaceRoot) {
125
+ return {
126
+ valid: false,
127
+ error: 'Symlink target is outside the allowed workspace root'
128
+ };
129
+ }
130
+ }
131
+ } catch (error) {
132
+ if (error.code !== 'ENOENT') {
133
+ throw error;
134
+ }
135
+ // Path doesn't exist - that's fine for new workspace creation
136
+ }
137
+
138
+ return {
139
+ valid: true,
140
+ resolvedPath: realPath
141
+ };
142
+
143
+ } catch (error) {
144
+ return {
145
+ valid: false,
146
+ error: `Path validation failed: ${error.message}`
147
+ };
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Create a new workspace
153
+ * POST /api/projects/create-workspace
154
+ *
155
+ * Body:
156
+ * - workspaceType: 'existing' | 'new'
157
+ * - path: string (workspace path)
158
+ * - githubUrl?: string (optional, for new workspaces)
159
+ * - githubTokenId?: number (optional, ID of stored token)
160
+ * - newGithubToken?: string (optional, one-time token)
161
+ */
162
+ router.post('/create-workspace', async (req, res) => {
163
+ try {
164
+ const { workspaceType, path: workspacePath, githubUrl, githubTokenId, newGithubToken } = req.body;
165
+
166
+ // Validate required fields
167
+ if (!workspaceType || !workspacePath) {
168
+ return res.status(400).json({ error: 'workspaceType and path are required' });
169
+ }
170
+
171
+ if (!['existing', 'new'].includes(workspaceType)) {
172
+ return res.status(400).json({ error: 'workspaceType must be "existing" or "new"' });
173
+ }
174
+
175
+ // Validate path safety before any operations
176
+ const validation = await validateWorkspacePath(workspacePath);
177
+ if (!validation.valid) {
178
+ return res.status(400).json({
179
+ error: 'Invalid workspace path',
180
+ details: validation.error
181
+ });
182
+ }
183
+
184
+ const absolutePath = validation.resolvedPath;
185
+
186
+ // Handle existing workspace
187
+ if (workspaceType === 'existing') {
188
+ // Check if the path exists
189
+ try {
190
+ await fs.access(absolutePath);
191
+ const stats = await fs.stat(absolutePath);
192
+
193
+ if (!stats.isDirectory()) {
194
+ return res.status(400).json({ error: 'Path exists but is not a directory' });
195
+ }
196
+ } catch (error) {
197
+ if (error.code === 'ENOENT') {
198
+ return res.status(404).json({ error: 'Workspace path does not exist' });
199
+ }
200
+ throw error;
201
+ }
202
+
203
+ // Add the existing workspace to the project list
204
+ const project = await addProjectManually(absolutePath);
205
+
206
+ return res.json({
207
+ success: true,
208
+ project,
209
+ message: 'Existing workspace added successfully'
210
+ });
211
+ }
212
+
213
+ // Handle new workspace creation
214
+ if (workspaceType === 'new') {
215
+ // Check if path already exists
216
+ try {
217
+ await fs.access(absolutePath);
218
+ return res.status(400).json({
219
+ error: 'Path already exists. Please choose a different path or use "existing workspace" option.'
220
+ });
221
+ } catch (error) {
222
+ if (error.code !== 'ENOENT') {
223
+ throw error;
224
+ }
225
+ // Path doesn't exist - good, we can create it
226
+ }
227
+
228
+ // Create the directory
229
+ await fs.mkdir(absolutePath, { recursive: true });
230
+
231
+ // If GitHub URL is provided, clone the repository
232
+ if (githubUrl) {
233
+ let githubToken = null;
234
+
235
+ // Get GitHub token if needed
236
+ if (githubTokenId) {
237
+ // Fetch token from database
238
+ const token = await getGithubTokenById(githubTokenId, req.user.id);
239
+ if (!token) {
240
+ // Clean up created directory
241
+ await fs.rm(absolutePath, { recursive: true, force: true });
242
+ return res.status(404).json({ error: 'GitHub token not found' });
243
+ }
244
+ githubToken = token.github_token;
245
+ } else if (newGithubToken) {
246
+ githubToken = newGithubToken;
247
+ }
248
+
249
+ // Clone the repository
250
+ try {
251
+ await cloneGitHubRepository(githubUrl, absolutePath, githubToken);
252
+ } catch (error) {
253
+ // Clean up created directory on failure
254
+ try {
255
+ await fs.rm(absolutePath, { recursive: true, force: true });
256
+ } catch (cleanupError) {
257
+ console.error('Failed to clean up directory after clone failure:', cleanupError);
258
+ // Continue to throw original error
259
+ }
260
+ throw new Error(`Failed to clone repository: ${error.message}`);
261
+ }
262
+ }
263
+
264
+ // Add the new workspace to the project list
265
+ const project = await addProjectManually(absolutePath);
266
+
267
+ return res.json({
268
+ success: true,
269
+ project,
270
+ message: githubUrl
271
+ ? 'New workspace created and repository cloned successfully'
272
+ : 'New workspace created successfully'
273
+ });
274
+ }
275
+
276
+ } catch (error) {
277
+ console.error('Error creating workspace:', error);
278
+ res.status(500).json({
279
+ error: error.message || 'Failed to create workspace',
280
+ details: process.env.NODE_ENV === 'development' ? error.stack : undefined
281
+ });
282
+ }
283
+ });
284
+
285
+ /**
286
+ * Helper function to get GitHub token from database
287
+ */
288
+ async function getGithubTokenById(tokenId, userId) {
289
+ const { getDatabase } = await import('../database/db.js');
290
+ const db = await getDatabase();
291
+
292
+ const credential = await db.get(
293
+ 'SELECT * FROM user_credentials WHERE id = ? AND user_id = ? AND credential_type = ? AND is_active = 1',
294
+ [tokenId, userId, 'github_token']
295
+ );
296
+
297
+ // Return in the expected format (github_token field for compatibility)
298
+ if (credential) {
299
+ return {
300
+ ...credential,
301
+ github_token: credential.credential_value
302
+ };
303
+ }
304
+
305
+ return null;
306
+ }
307
+
308
+ /**
309
+ * Helper function to clone a GitHub repository
310
+ */
311
+ function cloneGitHubRepository(githubUrl, destinationPath, githubToken = null) {
312
+ return new Promise((resolve, reject) => {
313
+ // Parse GitHub URL and inject token if provided
314
+ let cloneUrl = githubUrl;
315
+
316
+ if (githubToken) {
317
+ try {
318
+ const url = new URL(githubUrl);
319
+ // Format: https://TOKEN@github.com/user/repo.git
320
+ url.username = githubToken;
321
+ url.password = '';
322
+ cloneUrl = url.toString();
323
+ } catch (error) {
324
+ return reject(new Error('Invalid GitHub URL format'));
325
+ }
326
+ }
327
+
328
+ const gitProcess = spawn('git', ['clone', cloneUrl, destinationPath], {
329
+ stdio: ['ignore', 'pipe', 'pipe'],
330
+ env: {
331
+ ...process.env,
332
+ GIT_TERMINAL_PROMPT: '0' // Disable git password prompts
333
+ }
334
+ });
335
+
336
+ let stdout = '';
337
+ let stderr = '';
338
+
339
+ gitProcess.stdout.on('data', (data) => {
340
+ stdout += data.toString();
341
+ });
342
+
343
+ gitProcess.stderr.on('data', (data) => {
344
+ stderr += data.toString();
345
+ });
346
+
347
+ gitProcess.on('close', (code) => {
348
+ if (code === 0) {
349
+ resolve({ stdout, stderr });
350
+ } else {
351
+ // Parse git error messages to provide helpful feedback
352
+ let errorMessage = 'Git clone failed';
353
+
354
+ if (stderr.includes('Authentication failed') || stderr.includes('could not read Username')) {
355
+ errorMessage = 'Authentication failed. Please check your GitHub token.';
356
+ } else if (stderr.includes('Repository not found')) {
357
+ errorMessage = 'Repository not found. Please check the URL and ensure you have access.';
358
+ } else if (stderr.includes('already exists')) {
359
+ errorMessage = 'Directory already exists';
360
+ } else if (stderr) {
361
+ errorMessage = stderr;
362
+ }
363
+
364
+ reject(new Error(errorMessage));
365
+ }
366
+ });
367
+
368
+ gitProcess.on('error', (error) => {
369
+ if (error.code === 'ENOENT') {
370
+ reject(new Error('Git is not installed or not in PATH'));
371
+ } else {
372
+ reject(error);
373
+ }
374
+ });
375
+ });
376
+ }
377
+
378
+ export default router;
@@ -0,0 +1,178 @@
1
+ import express from 'express';
2
+ import { apiKeysDb, credentialsDb } from '../database/db.js';
3
+
4
+ const router = express.Router();
5
+
6
+ // ===============================
7
+ // API Keys Management
8
+ // ===============================
9
+
10
+ // Get all API keys for the authenticated user
11
+ router.get('/api-keys', async (req, res) => {
12
+ try {
13
+ const apiKeys = apiKeysDb.getApiKeys(req.user.id);
14
+ // Don't send the full API key in the list for security
15
+ const sanitizedKeys = apiKeys.map(key => ({
16
+ ...key,
17
+ api_key: key.api_key.substring(0, 10) + '...'
18
+ }));
19
+ res.json({ apiKeys: sanitizedKeys });
20
+ } catch (error) {
21
+ console.error('Error fetching API keys:', error);
22
+ res.status(500).json({ error: 'Failed to fetch API keys' });
23
+ }
24
+ });
25
+
26
+ // Create a new API key
27
+ router.post('/api-keys', async (req, res) => {
28
+ try {
29
+ const { keyName } = req.body;
30
+
31
+ if (!keyName || !keyName.trim()) {
32
+ return res.status(400).json({ error: 'Key name is required' });
33
+ }
34
+
35
+ const result = apiKeysDb.createApiKey(req.user.id, keyName.trim());
36
+ res.json({
37
+ success: true,
38
+ apiKey: result
39
+ });
40
+ } catch (error) {
41
+ console.error('Error creating API key:', error);
42
+ res.status(500).json({ error: 'Failed to create API key' });
43
+ }
44
+ });
45
+
46
+ // Delete an API key
47
+ router.delete('/api-keys/:keyId', async (req, res) => {
48
+ try {
49
+ const { keyId } = req.params;
50
+ const success = apiKeysDb.deleteApiKey(req.user.id, parseInt(keyId));
51
+
52
+ if (success) {
53
+ res.json({ success: true });
54
+ } else {
55
+ res.status(404).json({ error: 'API key not found' });
56
+ }
57
+ } catch (error) {
58
+ console.error('Error deleting API key:', error);
59
+ res.status(500).json({ error: 'Failed to delete API key' });
60
+ }
61
+ });
62
+
63
+ // Toggle API key active status
64
+ router.patch('/api-keys/:keyId/toggle', async (req, res) => {
65
+ try {
66
+ const { keyId } = req.params;
67
+ const { isActive } = req.body;
68
+
69
+ if (typeof isActive !== 'boolean') {
70
+ return res.status(400).json({ error: 'isActive must be a boolean' });
71
+ }
72
+
73
+ const success = apiKeysDb.toggleApiKey(req.user.id, parseInt(keyId), isActive);
74
+
75
+ if (success) {
76
+ res.json({ success: true });
77
+ } else {
78
+ res.status(404).json({ error: 'API key not found' });
79
+ }
80
+ } catch (error) {
81
+ console.error('Error toggling API key:', error);
82
+ res.status(500).json({ error: 'Failed to toggle API key' });
83
+ }
84
+ });
85
+
86
+ // ===============================
87
+ // Generic Credentials Management
88
+ // ===============================
89
+
90
+ // Get all credentials for the authenticated user (optionally filtered by type)
91
+ router.get('/credentials', async (req, res) => {
92
+ try {
93
+ const { type } = req.query;
94
+ const credentials = credentialsDb.getCredentials(req.user.id, type || null);
95
+ // Don't send the actual credential values for security
96
+ res.json({ credentials });
97
+ } catch (error) {
98
+ console.error('Error fetching credentials:', error);
99
+ res.status(500).json({ error: 'Failed to fetch credentials' });
100
+ }
101
+ });
102
+
103
+ // Create a new credential
104
+ router.post('/credentials', async (req, res) => {
105
+ try {
106
+ const { credentialName, credentialType, credentialValue, description } = req.body;
107
+
108
+ if (!credentialName || !credentialName.trim()) {
109
+ return res.status(400).json({ error: 'Credential name is required' });
110
+ }
111
+
112
+ if (!credentialType || !credentialType.trim()) {
113
+ return res.status(400).json({ error: 'Credential type is required' });
114
+ }
115
+
116
+ if (!credentialValue || !credentialValue.trim()) {
117
+ return res.status(400).json({ error: 'Credential value is required' });
118
+ }
119
+
120
+ const result = credentialsDb.createCredential(
121
+ req.user.id,
122
+ credentialName.trim(),
123
+ credentialType.trim(),
124
+ credentialValue.trim(),
125
+ description?.trim() || null
126
+ );
127
+
128
+ res.json({
129
+ success: true,
130
+ credential: result
131
+ });
132
+ } catch (error) {
133
+ console.error('Error creating credential:', error);
134
+ res.status(500).json({ error: 'Failed to create credential' });
135
+ }
136
+ });
137
+
138
+ // Delete a credential
139
+ router.delete('/credentials/:credentialId', async (req, res) => {
140
+ try {
141
+ const { credentialId } = req.params;
142
+ const success = credentialsDb.deleteCredential(req.user.id, parseInt(credentialId));
143
+
144
+ if (success) {
145
+ res.json({ success: true });
146
+ } else {
147
+ res.status(404).json({ error: 'Credential not found' });
148
+ }
149
+ } catch (error) {
150
+ console.error('Error deleting credential:', error);
151
+ res.status(500).json({ error: 'Failed to delete credential' });
152
+ }
153
+ });
154
+
155
+ // Toggle credential active status
156
+ router.patch('/credentials/:credentialId/toggle', async (req, res) => {
157
+ try {
158
+ const { credentialId } = req.params;
159
+ const { isActive } = req.body;
160
+
161
+ if (typeof isActive !== 'boolean') {
162
+ return res.status(400).json({ error: 'isActive must be a boolean' });
163
+ }
164
+
165
+ const success = credentialsDb.toggleCredential(req.user.id, parseInt(credentialId), isActive);
166
+
167
+ if (success) {
168
+ res.json({ success: true });
169
+ } else {
170
+ res.status(404).json({ error: 'Credential not found' });
171
+ }
172
+ } catch (error) {
173
+ console.error('Error toggling credential:', error);
174
+ res.status(500).json({ error: 'Failed to toggle credential' });
175
+ }
176
+ });
177
+
178
+ export default router;