@siteboon/claude-code-ui 1.11.0 → 1.12.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 (72) hide show
  1. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  2. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  3. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  4. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  5. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  6. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  7. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  8. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  9. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  10. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  11. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  12. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  13. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  14. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  15. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  16. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  17. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  18. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  19. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  20. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  21. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  22. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  23. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  24. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  25. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  26. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  27. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  28. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  29. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  30. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  31. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  32. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  33. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  34. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  35. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  36. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  37. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  38. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  39. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  40. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  41. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  42. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  43. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  44. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  45. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  46. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  47. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  48. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  49. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  50. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  51. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  52. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  53. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  54. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  55. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  56. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  57. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  58. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  59. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  60. package/dist/assets/index-DXtzL-q9.css +32 -0
  61. package/dist/assets/index-Do2w3FiK.js +1189 -0
  62. package/dist/assets/{vendor-codemirror-B7BYDWj-.js → vendor-codemirror-CnTQH7Pk.js} +1 -1
  63. package/dist/assets/{vendor-react-7V_UDHjJ.js → vendor-react-DVSKlM5e.js} +9 -9
  64. package/dist/index.html +4 -4
  65. package/package.json +4 -1
  66. package/server/database/auth.db +0 -0
  67. package/server/database/db.js +9 -0
  68. package/server/index.js +27 -11
  69. package/server/middleware/auth.js +34 -3
  70. package/server/routes/projects.js +378 -0
  71. package/dist/assets/index-B4_v-YUz.css +0 -32
  72. package/dist/assets/index-BZX1vtg9.js +0 -932
package/dist/index.html CHANGED
@@ -25,11 +25,11 @@
25
25
 
26
26
  <!-- Prevent zoom on iOS -->
27
27
  <meta name="format-detection" content="telephone=no" />
28
- <script type="module" crossorigin src="/assets/index-BZX1vtg9.js"></script>
29
- <link rel="modulepreload" crossorigin href="/assets/vendor-react-7V_UDHjJ.js">
30
- <link rel="modulepreload" crossorigin href="/assets/vendor-codemirror-B7BYDWj-.js">
28
+ <script type="module" crossorigin src="/assets/index-Do2w3FiK.js"></script>
29
+ <link rel="modulepreload" crossorigin href="/assets/vendor-react-DVSKlM5e.js">
30
+ <link rel="modulepreload" crossorigin href="/assets/vendor-codemirror-CnTQH7Pk.js">
31
31
  <link rel="modulepreload" crossorigin href="/assets/vendor-xterm-jI4BCHEb.js">
32
- <link rel="stylesheet" crossorigin href="/assets/index-B4_v-YUz.css">
32
+ <link rel="stylesheet" crossorigin href="/assets/index-DXtzL-q9.css">
33
33
  </head>
34
34
  <body>
35
35
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@siteboon/claude-code-ui",
3
- "version": "1.11.0",
3
+ "version": "1.12.0",
4
4
  "description": "A web-based UI for Claude Code CLI",
5
5
  "type": "module",
6
6
  "main": "server/index.js",
@@ -68,6 +68,7 @@
68
68
  "fuse.js": "^7.0.0",
69
69
  "gray-matter": "^4.0.3",
70
70
  "jsonwebtoken": "^9.0.2",
71
+ "katex": "^0.16.25",
71
72
  "lucide-react": "^0.515.0",
72
73
  "mime-types": "^3.0.1",
73
74
  "multer": "^2.0.1",
@@ -78,7 +79,9 @@
78
79
  "react-dropzone": "^14.2.3",
79
80
  "react-markdown": "^10.1.0",
80
81
  "react-router-dom": "^6.8.1",
82
+ "rehype-katex": "^7.0.1",
81
83
  "remark-gfm": "^4.0.0",
84
+ "remark-math": "^6.0.0",
82
85
  "sqlite": "^5.1.1",
83
86
  "sqlite3": "^5.1.7",
84
87
  "tailwind-merge": "^3.3.1",
Binary file
@@ -117,6 +117,15 @@ const userDb = {
117
117
  } catch (err) {
118
118
  throw err;
119
119
  }
120
+ },
121
+
122
+ getFirstUser: () => {
123
+ try {
124
+ const row = db.prepare('SELECT id, username, created_at, last_login FROM users WHERE is_active = 1 LIMIT 1').get();
125
+ return row;
126
+ } catch (err) {
127
+ throw err;
128
+ }
120
129
  }
121
130
  };
122
131
 
package/server/index.js CHANGED
@@ -69,6 +69,7 @@ import mcpUtilsRoutes from './routes/mcp-utils.js';
69
69
  import commandsRoutes from './routes/commands.js';
70
70
  import settingsRoutes from './routes/settings.js';
71
71
  import agentRoutes from './routes/agent.js';
72
+ import projectsRoutes from './routes/projects.js';
72
73
  import { initializeDatabase } from './database/db.js';
73
74
  import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
74
75
 
@@ -169,6 +170,19 @@ const wss = new WebSocketServer({
169
170
  verifyClient: (info) => {
170
171
  console.log('WebSocket connection attempt to:', info.req.url);
171
172
 
173
+ // Platform mode: always allow connection
174
+ if (process.env.VITE_IS_PLATFORM === 'true') {
175
+ const user = authenticateWebSocket(null); // Will return first user
176
+ if (!user) {
177
+ console.log('[WARN] Platform mode: No user found in database');
178
+ return false;
179
+ }
180
+ info.req.user = user;
181
+ console.log('[OK] Platform mode WebSocket authenticated for user:', user.username);
182
+ return true;
183
+ }
184
+
185
+ // Normal mode: verify token
172
186
  // Extract token from query parameters or headers
173
187
  const url = new URL(info.req.url, 'http://localhost');
174
188
  const token = url.searchParams.get('token') ||
@@ -195,12 +209,23 @@ app.use(cors());
195
209
  app.use(express.json({ limit: '50mb' }));
196
210
  app.use(express.urlencoded({ limit: '50mb', extended: true }));
197
211
 
212
+ // Public health check endpoint (no authentication required)
213
+ app.get('/health', (req, res) => {
214
+ res.json({
215
+ status: 'ok',
216
+ timestamp: new Date().toISOString()
217
+ });
218
+ });
219
+
198
220
  // Optional API key validation (if configured)
199
221
  app.use('/api', validateApiKey);
200
222
 
201
223
  // Authentication routes (public)
202
224
  app.use('/api/auth', authRoutes);
203
225
 
226
+ // Projects API Routes (protected)
227
+ app.use('/api/projects', authenticateToken, projectsRoutes);
228
+
204
229
  // Git API Routes (protected)
205
230
  app.use('/api/git', authenticateToken, gitRoutes);
206
231
 
@@ -245,17 +270,8 @@ app.use(express.static(path.join(__dirname, '../dist'), {
245
270
  }));
246
271
 
247
272
  // API Routes (protected)
248
- app.get('/api/config', authenticateToken, (req, res) => {
249
- const host = req.headers.host || `${req.hostname}:${PORT}`;
250
- const protocol = req.protocol === 'https' || req.get('x-forwarded-proto') === 'https' ? 'wss' : 'ws';
251
-
252
- console.log('Config API called - Returning host:', host, 'Protocol:', protocol);
253
-
254
- res.json({
255
- serverPort: PORT,
256
- wsUrl: `${protocol}://${host}`
257
- });
258
- });
273
+ // /api/config endpoint removed - no longer needed
274
+ // Frontend now uses window.location for WebSocket URLs
259
275
 
260
276
  // System update endpoint
261
277
  app.post('/api/system/update', authenticateToken, async (req, res) => {
@@ -20,6 +20,22 @@ const validateApiKey = (req, res, next) => {
20
20
 
21
21
  // JWT authentication middleware
22
22
  const authenticateToken = async (req, res, next) => {
23
+ // Platform mode: use single database user
24
+ if (process.env.VITE_IS_PLATFORM === 'true') {
25
+ try {
26
+ const user = userDb.getFirstUser();
27
+ if (!user) {
28
+ return res.status(500).json({ error: 'Platform mode: No user found in database' });
29
+ }
30
+ req.user = user;
31
+ return next();
32
+ } catch (error) {
33
+ console.error('Platform mode error:', error);
34
+ return res.status(500).json({ error: 'Platform mode: Failed to fetch user' });
35
+ }
36
+ }
37
+
38
+ // Normal OSS JWT validation
23
39
  const authHeader = req.headers['authorization'];
24
40
  const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
25
41
 
@@ -29,13 +45,13 @@ const authenticateToken = async (req, res, next) => {
29
45
 
30
46
  try {
31
47
  const decoded = jwt.verify(token, JWT_SECRET);
32
-
48
+
33
49
  // Verify user still exists and is active
34
50
  const user = userDb.getUserById(decoded.userId);
35
51
  if (!user) {
36
52
  return res.status(401).json({ error: 'Invalid token. User not found.' });
37
53
  }
38
-
54
+
39
55
  req.user = user;
40
56
  next();
41
57
  } catch (error) {
@@ -58,10 +74,25 @@ const generateToken = (user) => {
58
74
 
59
75
  // WebSocket authentication function
60
76
  const authenticateWebSocket = (token) => {
77
+ // Platform mode: bypass token validation, return first user
78
+ if (process.env.VITE_IS_PLATFORM === 'true') {
79
+ try {
80
+ const user = userDb.getFirstUser();
81
+ if (user) {
82
+ return { userId: user.id, username: user.username };
83
+ }
84
+ return null;
85
+ } catch (error) {
86
+ console.error('Platform mode WebSocket error:', error);
87
+ return null;
88
+ }
89
+ }
90
+
91
+ // Normal OSS JWT validation
61
92
  if (!token) {
62
93
  return null;
63
94
  }
64
-
95
+
65
96
  try {
66
97
  const decoded = jwt.verify(token, JWT_SECRET);
67
98
  return decoded;
@@ -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;