upfynai-code 2.9.0 → 2.9.2

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 (229) hide show
  1. package/README.md +91 -66
  2. package/client/dist/api-docs.html +838 -0
  3. package/client/dist/assets/AppContent-BXZDeSIC.js +545 -0
  4. package/client/dist/assets/CanvasFullScreen-mnpCnLZ9.js +1 -0
  5. package/client/dist/assets/CanvasWorkspace-4CqmjAVQ.js +163 -0
  6. package/client/dist/assets/DashboardPanel-zFIFlw56.js +1 -0
  7. package/client/dist/assets/FileTree-B0c_GaB3.js +1 -0
  8. package/client/dist/assets/GitPanel-DUP4zVU4.js +2 -0
  9. package/client/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  10. package/client/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  11. package/client/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  12. package/client/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  13. package/client/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  14. package/client/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  15. package/client/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  16. package/client/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  17. package/client/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  18. package/client/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  19. package/client/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  20. package/client/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  21. package/client/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  22. package/client/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  23. package/client/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  24. package/client/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  25. package/client/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  26. package/client/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  27. package/client/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  28. package/client/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  29. package/client/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  30. package/client/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  31. package/client/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  32. package/client/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  33. package/client/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  34. package/client/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  35. package/client/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  36. package/client/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  37. package/client/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  38. package/client/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  39. package/client/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  40. package/client/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  41. package/client/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  42. package/client/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  43. package/client/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  44. package/client/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  45. package/client/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  46. package/client/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  47. package/client/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  48. package/client/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  49. package/client/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  50. package/client/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  51. package/client/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  52. package/client/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  53. package/client/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  54. package/client/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  55. package/client/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  56. package/client/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  57. package/client/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  58. package/client/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  59. package/client/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  60. package/client/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  61. package/client/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  62. package/client/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  63. package/client/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  64. package/client/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  65. package/client/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  66. package/client/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  67. package/client/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  68. package/client/dist/assets/LoginModal-BRycfsyD.js +13 -0
  69. package/client/dist/assets/MarkdownPreview-DHmk3qzu.js +1 -0
  70. package/client/dist/assets/MermaidBlock-BuBc_G-F.js +2 -0
  71. package/client/dist/assets/Onboarding-BcnaZZ0o.js +1 -0
  72. package/client/dist/assets/PreviewPanel-CqCa92Tf.js +32 -0
  73. package/client/dist/assets/SetupForm-S0g6u5yT.js +1 -0
  74. package/client/dist/assets/WorkflowsPanel-CouH9JDO.js +1 -0
  75. package/client/dist/assets/index-BFuqS0tY.css +1 -0
  76. package/client/dist/assets/index-CNDcVl2g.js +68 -0
  77. package/client/dist/assets/pdf-CE_K4jFx.js +12 -0
  78. package/client/dist/assets/vendor-canvas-BZV40eAE.css +1 -0
  79. package/client/dist/assets/vendor-canvas-D39yWul6.js +49 -0
  80. package/client/dist/assets/vendor-codemirror-CbtmxxaB.js +35 -0
  81. package/client/dist/assets/vendor-diff-DNQpbhrT.js +69 -0
  82. package/client/dist/assets/vendor-i18n-DCFGyhQR.js +1 -0
  83. package/client/dist/assets/vendor-icons-BaD0x9SL.js +711 -0
  84. package/client/dist/assets/vendor-markdown-CimbIo6Y.js +296 -0
  85. package/client/dist/assets/vendor-mermaid-CH7SGc99.js +2556 -0
  86. package/client/dist/assets/vendor-react-96lCPsRK.js +67 -0
  87. package/client/dist/assets/vendor-syntax-DuHI9Ok6.js +16 -0
  88. package/client/dist/assets/vendor-xterm-CZq1hqo1.js +66 -0
  89. package/client/dist/assets/vendor-xterm-qxJ8_QYu.css +32 -0
  90. package/client/dist/clear-cache.html +85 -0
  91. package/client/dist/convert-icons.md +53 -0
  92. package/client/dist/favicon.png +0 -0
  93. package/client/dist/favicon.svg +5 -0
  94. package/client/dist/generate-icons.js +49 -0
  95. package/client/dist/icons/claude-ai-icon.svg +1 -0
  96. package/client/dist/icons/codex-white.svg +3 -0
  97. package/client/dist/icons/codex.svg +3 -0
  98. package/client/dist/icons/cursor-white.svg +12 -0
  99. package/client/dist/icons/cursor.svg +1 -0
  100. package/client/dist/icons/icon-128x128.png +0 -0
  101. package/client/dist/icons/icon-128x128.svg +5 -0
  102. package/client/dist/icons/icon-144x144.png +0 -0
  103. package/client/dist/icons/icon-144x144.svg +5 -0
  104. package/client/dist/icons/icon-152x152.png +0 -0
  105. package/client/dist/icons/icon-152x152.svg +5 -0
  106. package/client/dist/icons/icon-192x192.png +0 -0
  107. package/client/dist/icons/icon-192x192.svg +5 -0
  108. package/client/dist/icons/icon-384x384.png +0 -0
  109. package/client/dist/icons/icon-384x384.svg +5 -0
  110. package/client/dist/icons/icon-512x512.png +0 -0
  111. package/client/dist/icons/icon-512x512.svg +5 -0
  112. package/client/dist/icons/icon-72x72.png +0 -0
  113. package/client/dist/icons/icon-72x72.svg +5 -0
  114. package/client/dist/icons/icon-96x96.png +0 -0
  115. package/client/dist/icons/icon-96x96.svg +5 -0
  116. package/client/dist/icons/icon-template.svg +5 -0
  117. package/client/dist/index.html +119 -0
  118. package/client/dist/logo-128.png +0 -0
  119. package/client/dist/logo-256.png +0 -0
  120. package/client/dist/logo-32.png +0 -0
  121. package/client/dist/logo-512.png +0 -0
  122. package/client/dist/logo-64.png +0 -0
  123. package/client/dist/logo.svg +14 -0
  124. package/client/dist/manifest.json +61 -0
  125. package/client/dist/mcp-docs.html +108 -0
  126. package/client/dist/offline.html +84 -0
  127. package/client/dist/screenshots/cli-selection.png +0 -0
  128. package/client/dist/screenshots/desktop-main.png +0 -0
  129. package/client/dist/screenshots/mobile-chat.png +0 -0
  130. package/client/dist/screenshots/tools-modal.png +0 -0
  131. package/client/dist/sw.js +82 -0
  132. package/commands/upfynai-connect.md +59 -0
  133. package/commands/upfynai-disconnect.md +31 -0
  134. package/commands/upfynai-doctor.md +99 -0
  135. package/commands/upfynai-export.md +49 -0
  136. package/commands/upfynai-local.md +82 -0
  137. package/commands/upfynai-status.md +75 -0
  138. package/commands/upfynai-stop.md +49 -0
  139. package/commands/upfynai-uninstall.md +58 -0
  140. package/commands/upfynai.md +69 -0
  141. package/package.json +143 -82
  142. package/scripts/build-client.js +17 -0
  143. package/scripts/fix-node-pty.js +67 -0
  144. package/scripts/install-commands.js +78 -0
  145. package/server/agent-loop.js +242 -0
  146. package/server/auto-compact.js +99 -0
  147. package/server/claude-sdk.js +797 -0
  148. package/server/cli-ui.js +785 -0
  149. package/server/cli.js +596 -0
  150. package/server/constants/config.js +31 -0
  151. package/server/cursor-cli.js +270 -0
  152. package/server/database/auth.db +0 -0
  153. package/server/database/db.js +1391 -0
  154. package/server/database/init.sql +70 -0
  155. package/server/index.js +3799 -0
  156. package/server/load-env.js +26 -0
  157. package/server/mcp-server.js +621 -0
  158. package/server/middleware/auth.js +176 -0
  159. package/server/middleware/relayHelpers.js +44 -0
  160. package/server/middleware/sandboxRouter.js +174 -0
  161. package/server/openai-codex.js +403 -0
  162. package/server/openrouter.js +137 -0
  163. package/server/projects.js +1807 -0
  164. package/server/provider-factory.js +174 -0
  165. package/server/relay-client.js +379 -0
  166. package/server/routes/agent.js +1226 -0
  167. package/server/routes/auth.js +554 -0
  168. package/server/routes/canvas.js +53 -0
  169. package/server/routes/cli-auth.js +263 -0
  170. package/server/routes/codex.js +396 -0
  171. package/server/routes/commands.js +707 -0
  172. package/server/routes/composio.js +176 -0
  173. package/server/routes/cursor.js +770 -0
  174. package/server/routes/dashboard.js +295 -0
  175. package/server/routes/git.js +1208 -0
  176. package/server/routes/keys.js +34 -0
  177. package/server/routes/mcp-utils.js +48 -0
  178. package/server/routes/mcp.js +661 -0
  179. package/server/routes/payments.js +227 -0
  180. package/server/routes/projects.js +655 -0
  181. package/server/routes/sessions.js +146 -0
  182. package/server/routes/settings.js +261 -0
  183. package/server/routes/taskmaster.js +1928 -0
  184. package/server/routes/user.js +106 -0
  185. package/server/routes/vapi-chat.js +624 -0
  186. package/server/routes/voice.js +235 -0
  187. package/server/routes/webhooks.js +166 -0
  188. package/server/routes/workflows.js +312 -0
  189. package/server/sandbox.js +120 -0
  190. package/server/services/composio.js +204 -0
  191. package/server/services/sessionRegistry.js +139 -0
  192. package/server/services/whisperService.js +84 -0
  193. package/server/services/workflowScheduler.js +206 -0
  194. package/server/tests/relay-flow.test.js +570 -0
  195. package/server/tests/sessions.test.js +259 -0
  196. package/server/utils/commandParser.js +303 -0
  197. package/server/utils/email.js +61 -0
  198. package/server/utils/gitConfig.js +24 -0
  199. package/server/utils/mcp-detector.js +198 -0
  200. package/server/utils/taskmaster-websocket.js +129 -0
  201. package/shared/integrationCatalog.d.ts +12 -0
  202. package/shared/integrationCatalog.js +172 -0
  203. package/shared/modelConstants.js +96 -0
  204. package/bin/cli.js +0 -97
  205. package/dist/agents/claude.js +0 -229
  206. package/dist/agents/codex.js +0 -48
  207. package/dist/agents/cursor.js +0 -48
  208. package/dist/agents/detect.js +0 -51
  209. package/dist/agents/exec.js +0 -31
  210. package/dist/agents/files.js +0 -105
  211. package/dist/agents/git.js +0 -18
  212. package/dist/agents/gitagent.js +0 -67
  213. package/dist/agents/index.js +0 -88
  214. package/dist/agents/shell.js +0 -38
  215. package/dist/agents/utils.js +0 -136
  216. package/scripts/postinstall.js +0 -9
  217. package/scripts/prepublish.js +0 -58
  218. package/src/animation.js +0 -228
  219. package/src/auth.js +0 -122
  220. package/src/config.js +0 -40
  221. package/src/connect.js +0 -416
  222. package/src/launch.js +0 -78
  223. package/src/mcp.js +0 -57
  224. package/src/permissions.js +0 -140
  225. package/src/persistent-shell.js +0 -261
  226. package/src/server.js +0 -54
  227. /package/{dist → shared}/gitagent/index.js +0 -0
  228. /package/{dist → shared}/gitagent/parser.js +0 -0
  229. /package/{dist → shared}/gitagent/prompt-builder.js +0 -0
@@ -0,0 +1,655 @@
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
+ function sanitizeGitError(message, token) {
11
+ if (!message || !token) return message;
12
+ return message.replace(new RegExp(token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), '***');
13
+ }
14
+
15
+ // Configure allowed workspace root.
16
+ // In platform mode (Railway), file operations are proxied to user's local machine via relay,
17
+ // so no server-side path restriction is needed. Only restrict in self-hosted mode if explicitly set.
18
+ const IS_LOCAL = !process.env.RAILWAY_ENVIRONMENT && !process.env.VERCEL && !process.env.RENDER;
19
+ const IS_PLATFORM = !!process.env.RAILWAY_ENVIRONMENT || !!process.env.VERCEL;
20
+ export const WORKSPACES_ROOT = process.env.WORKSPACES_ROOT || (IS_LOCAL || IS_PLATFORM ? null : os.homedir());
21
+
22
+ // System-critical paths that should never be used as workspace directories
23
+ export const FORBIDDEN_PATHS = [
24
+ // Unix
25
+ '/',
26
+ '/etc',
27
+ '/bin',
28
+ '/sbin',
29
+ '/usr',
30
+ '/dev',
31
+ '/proc',
32
+ '/sys',
33
+ '/var',
34
+ '/boot',
35
+ '/root',
36
+ '/lib',
37
+ '/lib64',
38
+ '/opt',
39
+ '/tmp',
40
+ '/run',
41
+ // Windows
42
+ 'C:\\Windows',
43
+ 'C:\\Program Files',
44
+ 'C:\\Program Files (x86)',
45
+ 'C:\\ProgramData',
46
+ 'C:\\System Volume Information',
47
+ 'C:\\$Recycle.Bin'
48
+ ];
49
+
50
+ /**
51
+ * Validates that a path is safe for workspace operations
52
+ * @param {string} requestedPath - The path to validate
53
+ * @returns {Promise<{valid: boolean, resolvedPath?: string, error?: string}>}
54
+ */
55
+ export async function validateWorkspacePath(requestedPath) {
56
+ try {
57
+ // Resolve to absolute path
58
+ let absolutePath = path.resolve(requestedPath);
59
+
60
+ // Check if path is a forbidden system directory
61
+ const normalizedPath = path.normalize(absolutePath);
62
+ if (FORBIDDEN_PATHS.includes(normalizedPath) || normalizedPath === '/') {
63
+ return {
64
+ valid: false,
65
+ error: 'Cannot use system-critical directories as workspace locations'
66
+ };
67
+ }
68
+
69
+ // Additional check for paths starting with forbidden directories
70
+ for (const forbidden of FORBIDDEN_PATHS) {
71
+ if (normalizedPath === forbidden ||
72
+ normalizedPath.startsWith(forbidden + path.sep)) {
73
+ // Exception: /var/tmp and similar user-accessible paths might be allowed
74
+ // but /var itself and most /var subdirectories should be blocked
75
+ if (forbidden === '/var' &&
76
+ (normalizedPath.startsWith('/var/tmp') ||
77
+ normalizedPath.startsWith('/var/folders'))) {
78
+ continue; // Allow these specific cases
79
+ }
80
+
81
+ return {
82
+ valid: false,
83
+ error: `Cannot create workspace in system directory: ${forbidden}`
84
+ };
85
+ }
86
+ }
87
+
88
+ // Try to resolve the real path (following symlinks)
89
+ let realPath;
90
+ try {
91
+ // Check if path exists to resolve real path
92
+ await fs.access(absolutePath);
93
+ realPath = await fs.realpath(absolutePath);
94
+ } catch (error) {
95
+ if (error.code === 'ENOENT') {
96
+ // Path doesn't exist yet - check parent directory
97
+ let parentPath = path.dirname(absolutePath);
98
+ try {
99
+ const parentRealPath = await fs.realpath(parentPath);
100
+
101
+ // Reconstruct the full path with real parent
102
+ realPath = path.join(parentRealPath, path.basename(absolutePath));
103
+ } catch (parentError) {
104
+ if (parentError.code === 'ENOENT') {
105
+ // Parent doesn't exist either - use the absolute path as-is
106
+ // We'll validate it's within allowed root
107
+ realPath = absolutePath;
108
+ } else {
109
+ throw parentError;
110
+ }
111
+ }
112
+ } else {
113
+ throw error;
114
+ }
115
+ }
116
+
117
+ // If a workspace root is configured, enforce containment
118
+ if (WORKSPACES_ROOT) {
119
+ const resolvedWorkspaceRoot = await fs.realpath(WORKSPACES_ROOT);
120
+
121
+ if (!realPath.startsWith(resolvedWorkspaceRoot + path.sep) &&
122
+ realPath !== resolvedWorkspaceRoot) {
123
+ return {
124
+ valid: false,
125
+ error: `Workspace path must be within the allowed workspace root: ${WORKSPACES_ROOT}`
126
+ };
127
+ }
128
+
129
+ // Additional symlink check for existing paths
130
+ try {
131
+ await fs.access(absolutePath);
132
+ const stats = await fs.lstat(absolutePath);
133
+
134
+ if (stats.isSymbolicLink()) {
135
+ const linkTarget = await fs.readlink(absolutePath);
136
+ const resolvedTarget = path.resolve(path.dirname(absolutePath), linkTarget);
137
+ const realTarget = await fs.realpath(resolvedTarget);
138
+
139
+ if (!realTarget.startsWith(resolvedWorkspaceRoot + path.sep) &&
140
+ realTarget !== resolvedWorkspaceRoot) {
141
+ return {
142
+ valid: false,
143
+ error: 'Symlink target is outside the allowed workspace root'
144
+ };
145
+ }
146
+ }
147
+ } catch (error) {
148
+ if (error.code !== 'ENOENT') {
149
+ throw error;
150
+ }
151
+ }
152
+ }
153
+
154
+ return {
155
+ valid: true,
156
+ resolvedPath: realPath
157
+ };
158
+
159
+ } catch (error) {
160
+ return {
161
+ valid: false,
162
+ error: 'Path validation failed'
163
+ };
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Create a new workspace
169
+ * POST /api/projects/create-workspace
170
+ *
171
+ * Body:
172
+ * - workspaceType: 'existing' | 'new'
173
+ * - path: string (workspace path)
174
+ * - githubUrl?: string (optional, for new workspaces)
175
+ * - githubTokenId?: number (optional, ID of stored token)
176
+ * - newGithubToken?: string (optional, one-time token)
177
+ */
178
+ router.post('/create-workspace', async (req, res) => {
179
+ try {
180
+ const { workspaceType, path: workspacePath, githubUrl, githubTokenId, newGithubToken } = req.body;
181
+
182
+ // Validate required fields
183
+ if (!workspaceType || !workspacePath) {
184
+ return res.status(400).json({ error: 'workspaceType and path are required' });
185
+ }
186
+
187
+ if (!['existing', 'new'].includes(workspaceType)) {
188
+ return res.status(400).json({ error: 'workspaceType must be "existing" or "new"' });
189
+ }
190
+
191
+ // Handle existing workspace
192
+ if (workspaceType === 'existing') {
193
+ // In cloud mode (Railway/Vercel/Render), the path is on the user's local machine.
194
+ // We cannot validate it server-side. Just trust the user's input and add it.
195
+ const IS_CLOUD_ENV = !!(process.env.RAILWAY_ENVIRONMENT || process.env.VERCEL || process.env.RENDER);
196
+ if (IS_CLOUD_ENV) {
197
+ const project = await addProjectManually(workspacePath);
198
+ return res.json({ success: true, project, message: 'Workspace added successfully' });
199
+ }
200
+
201
+ // Local/self-hosted mode: validate on server filesystem
202
+ const validation = await validateWorkspacePath(workspacePath);
203
+ if (!validation.valid) {
204
+ return res.status(400).json({ error: 'Invalid workspace path', details: validation.error });
205
+ }
206
+ const absolutePath = validation.resolvedPath;
207
+
208
+ try {
209
+ await fs.access(absolutePath);
210
+ const stats = await fs.stat(absolutePath);
211
+
212
+ if (!stats.isDirectory()) {
213
+ return res.status(400).json({ error: 'Path exists but is not a directory' });
214
+ }
215
+ } catch (error) {
216
+ if (error.code === 'ENOENT') {
217
+ return res.status(404).json({ error: 'Workspace path does not exist' });
218
+ }
219
+ throw error;
220
+ }
221
+
222
+ const project = await addProjectManually(absolutePath);
223
+
224
+ return res.json({
225
+ success: true,
226
+ project,
227
+ message: 'Existing workspace added successfully'
228
+ });
229
+ }
230
+
231
+ // Handle new workspace creation
232
+ if (workspaceType === 'new') {
233
+ const IS_CLOUD_ENV = !!(process.env.RAILWAY_ENVIRONMENT || process.env.VERCEL || process.env.RENDER);
234
+
235
+ // In cloud mode, create directory and clone via relay
236
+ if (IS_CLOUD_ENV) {
237
+ if (!req.hasRelay || !req.hasRelay()) {
238
+ return res.status(503).json({
239
+ error: 'Machine not connected',
240
+ message: 'Run "uc connect" on your local machine to create new workspaces.',
241
+ code: 'RELAY_NOT_CONNECTED'
242
+ });
243
+ }
244
+
245
+ // Create directory via relay
246
+ await req.sendRelay('create-folder', { folderPath: workspacePath }, 15000);
247
+
248
+ if (githubUrl) {
249
+ let githubToken = null;
250
+ if (githubTokenId) {
251
+ const token = await getGithubTokenById(githubTokenId, req.user.id);
252
+ if (!token) {
253
+ return res.status(404).json({ error: 'GitHub token not found' });
254
+ }
255
+ githubToken = token.github_token;
256
+ } else if (newGithubToken) {
257
+ githubToken = newGithubToken;
258
+ }
259
+
260
+ const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
261
+ const repoName = normalizedUrl.split('/').pop() || 'repository';
262
+ // Build clone URL with token if needed
263
+ let cloneUrl = githubUrl;
264
+ if (githubToken) {
265
+ const urlObj = new URL(githubUrl.endsWith('.git') ? githubUrl : `${githubUrl}.git`);
266
+ urlObj.username = githubToken;
267
+ urlObj.password = 'x-oauth-basic';
268
+ cloneUrl = urlObj.toString();
269
+ }
270
+ const clonePath = `${workspacePath}/${repoName}`;
271
+
272
+ try {
273
+ await req.sendRelay('shell-command', {
274
+ command: `git clone "${cloneUrl}" "${clonePath}"`,
275
+ cwd: workspacePath
276
+ }, 120000);
277
+ } catch (error) {
278
+ const sanitized = sanitizeGitError(error.message, githubToken);
279
+ throw new Error(`Failed to clone repository: ${sanitized}`);
280
+ }
281
+
282
+ const project = await addProjectManually(clonePath);
283
+ return res.json({ success: true, project, message: 'New workspace created and repository cloned successfully' });
284
+ }
285
+
286
+ const project = await addProjectManually(workspacePath);
287
+ return res.json({ success: true, project, message: 'New workspace created successfully' });
288
+ }
289
+
290
+ // Local mode
291
+ const validation = await validateWorkspacePath(workspacePath);
292
+ const absolutePath = validation.valid ? validation.resolvedPath : path.resolve(workspacePath);
293
+ await fs.mkdir(absolutePath, { recursive: true });
294
+
295
+ if (githubUrl) {
296
+ let githubToken = null;
297
+
298
+ if (githubTokenId) {
299
+ const token = await getGithubTokenById(githubTokenId, req.user.id);
300
+ if (!token) {
301
+ await fs.rm(absolutePath, { recursive: true, force: true });
302
+ return res.status(404).json({ error: 'GitHub token not found' });
303
+ }
304
+ githubToken = token.github_token;
305
+ } else if (newGithubToken) {
306
+ githubToken = newGithubToken;
307
+ }
308
+
309
+ const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
310
+ const repoName = normalizedUrl.split('/').pop() || 'repository';
311
+ const clonePath = path.join(absolutePath, repoName);
312
+
313
+ try {
314
+ await fs.access(clonePath);
315
+ return res.status(409).json({
316
+ error: 'Directory already exists',
317
+ details: `The destination path "${clonePath}" already exists. Please choose a different location or remove the existing directory.`
318
+ });
319
+ } catch (err) {
320
+ // Directory doesn't exist, which is what we want
321
+ }
322
+
323
+ try {
324
+ await cloneGitHubRepository(githubUrl, clonePath, githubToken);
325
+ } catch (error) {
326
+ try {
327
+ const stats = await fs.stat(clonePath);
328
+ if (stats.isDirectory()) {
329
+ await fs.rm(clonePath, { recursive: true, force: true });
330
+ }
331
+ } catch (cleanupError) {
332
+ // ignore
333
+ }
334
+ throw new Error(`Failed to clone repository: ${error.message}`);
335
+ }
336
+
337
+ const project = await addProjectManually(clonePath);
338
+ return res.json({ success: true, project, message: 'New workspace created and repository cloned successfully' });
339
+ }
340
+
341
+ const project = await addProjectManually(absolutePath);
342
+ return res.json({ success: true, project, message: 'New workspace created successfully' });
343
+ }
344
+
345
+ } catch (error) {
346
+ // workspace creation error
347
+ res.status(500).json({
348
+ error: 'Failed to create workspace',
349
+ details: error.message
350
+ });
351
+ }
352
+ });
353
+
354
+ /**
355
+ * Helper function to get GitHub token from database
356
+ */
357
+ async function getGithubTokenById(tokenId, userId) {
358
+ const { getDatabase } = await import('../database/db.js');
359
+ const db = await getDatabase();
360
+
361
+ const credential = await db.get(
362
+ 'SELECT * FROM user_credentials WHERE id = ? AND user_id = ? AND credential_type = ? AND is_active = 1',
363
+ [tokenId, userId, 'github_token']
364
+ );
365
+
366
+ // Return in the expected format (github_token field for compatibility)
367
+ if (credential) {
368
+ return {
369
+ ...credential,
370
+ github_token: credential.credential_value
371
+ };
372
+ }
373
+
374
+ return null;
375
+ }
376
+
377
+ /**
378
+ * Clone repository with progress streaming (SSE)
379
+ * GET /api/projects/clone-progress
380
+ */
381
+ router.get('/clone-progress', async (req, res) => {
382
+ const { path: workspacePath, githubUrl, githubTokenId, newGithubToken } = req.query;
383
+
384
+ res.setHeader('Content-Type', 'text/event-stream');
385
+ res.setHeader('Cache-Control', 'no-cache');
386
+ res.setHeader('Connection', 'keep-alive');
387
+ res.flushHeaders();
388
+
389
+ const sendEvent = (type, data) => {
390
+ res.write(`data: ${JSON.stringify({ type, ...data })}\n\n`);
391
+ };
392
+
393
+ try {
394
+ if (!workspacePath || !githubUrl) {
395
+ sendEvent('error', { message: 'workspacePath and githubUrl are required' });
396
+ res.end();
397
+ return;
398
+ }
399
+
400
+ const IS_CLOUD_ENV = !!(process.env.RAILWAY_ENVIRONMENT || process.env.VERCEL || process.env.RENDER);
401
+
402
+ // Cloud mode: clone via relay on user's machine
403
+ if (IS_CLOUD_ENV) {
404
+ if (!req.hasRelay || !req.hasRelay()) {
405
+ sendEvent('error', { message: 'Machine not connected. Run "uc connect" on your local machine.' });
406
+ res.end();
407
+ return;
408
+ }
409
+
410
+ let githubToken = null;
411
+ if (githubTokenId) {
412
+ const token = await getGithubTokenById(parseInt(githubTokenId), req.user.id);
413
+ if (!token) {
414
+ sendEvent('error', { message: 'GitHub token not found' });
415
+ res.end();
416
+ return;
417
+ }
418
+ githubToken = token.github_token;
419
+ } else if (newGithubToken) {
420
+ githubToken = newGithubToken;
421
+ }
422
+
423
+ sendEvent('progress', { message: 'Creating directory...' });
424
+ await req.sendRelay('create-folder', { folderPath: workspacePath }, 15000);
425
+
426
+ const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
427
+ const repoName = normalizedUrl.split('/').pop() || 'repository';
428
+ const clonePath = `${workspacePath}/${repoName}`;
429
+
430
+ let cloneUrl = githubUrl;
431
+ if (githubToken) {
432
+ try {
433
+ const url = new URL(githubUrl.endsWith('.git') ? githubUrl : `${githubUrl}.git`);
434
+ url.username = githubToken;
435
+ url.password = 'x-oauth-basic';
436
+ cloneUrl = url.toString();
437
+ } catch (error) {
438
+ // SSH URL or invalid - use as-is
439
+ }
440
+ }
441
+
442
+ sendEvent('progress', { message: `Cloning into '${repoName}'...` });
443
+
444
+ try {
445
+ await req.sendRelay('shell-command', {
446
+ command: `git clone "${cloneUrl}" "${clonePath}"`,
447
+ cwd: workspacePath
448
+ }, 120000);
449
+
450
+ const project = await addProjectManually(clonePath);
451
+ sendEvent('complete', { project, message: 'Repository cloned successfully' });
452
+ } catch (error) {
453
+ const sanitized = sanitizeGitError(error.message, githubToken);
454
+ sendEvent('error', { message: sanitized || 'Git clone failed' });
455
+ }
456
+
457
+ res.end();
458
+ return;
459
+ }
460
+
461
+ // Local mode
462
+ const validation = await validateWorkspacePath(workspacePath);
463
+ if (!validation.valid) {
464
+ sendEvent('error', { message: validation.error });
465
+ res.end();
466
+ return;
467
+ }
468
+
469
+ const absolutePath = validation.resolvedPath;
470
+
471
+ await fs.mkdir(absolutePath, { recursive: true });
472
+
473
+ let githubToken = null;
474
+ if (githubTokenId) {
475
+ const token = await getGithubTokenById(parseInt(githubTokenId), req.user.id);
476
+ if (!token) {
477
+ await fs.rm(absolutePath, { recursive: true, force: true });
478
+ sendEvent('error', { message: 'GitHub token not found' });
479
+ res.end();
480
+ return;
481
+ }
482
+ githubToken = token.github_token;
483
+ } else if (newGithubToken) {
484
+ githubToken = newGithubToken;
485
+ }
486
+
487
+ const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
488
+ const repoName = normalizedUrl.split('/').pop() || 'repository';
489
+ const clonePath = path.join(absolutePath, repoName);
490
+
491
+ try {
492
+ await fs.access(clonePath);
493
+ sendEvent('error', { message: `Directory "${repoName}" already exists. Please choose a different location or remove the existing directory.` });
494
+ res.end();
495
+ return;
496
+ } catch (err) {
497
+ // Directory doesn't exist, which is what we want
498
+ }
499
+
500
+ let cloneUrl = githubUrl;
501
+ if (githubToken) {
502
+ try {
503
+ const url = new URL(githubUrl);
504
+ url.username = githubToken;
505
+ url.password = '';
506
+ cloneUrl = url.toString();
507
+ } catch (error) {
508
+ // SSH URL or invalid - use as-is
509
+ }
510
+ }
511
+
512
+ sendEvent('progress', { message: `Cloning into '${repoName}'...` });
513
+
514
+ const gitProcess = spawn('git', ['clone', '--progress', cloneUrl, clonePath], {
515
+ stdio: ['ignore', 'pipe', 'pipe'],
516
+ env: {
517
+ ...process.env,
518
+ GIT_TERMINAL_PROMPT: '0'
519
+ }
520
+ });
521
+
522
+ let lastError = '';
523
+
524
+ gitProcess.stdout.on('data', (data) => {
525
+ const message = data.toString().trim();
526
+ if (message) {
527
+ sendEvent('progress', { message });
528
+ }
529
+ });
530
+
531
+ gitProcess.stderr.on('data', (data) => {
532
+ const message = data.toString().trim();
533
+ lastError = message;
534
+ if (message) {
535
+ sendEvent('progress', { message });
536
+ }
537
+ });
538
+
539
+ gitProcess.on('close', async (code) => {
540
+ if (code === 0) {
541
+ try {
542
+ const project = await addProjectManually(clonePath);
543
+ sendEvent('complete', { project, message: 'Repository cloned successfully' });
544
+ } catch (error) {
545
+ sendEvent('error', { message: `Clone succeeded but failed to add project: ${error.message}` });
546
+ }
547
+ } else {
548
+ const sanitizedError = sanitizeGitError(lastError, githubToken);
549
+ let errorMessage = 'Git clone failed';
550
+ if (lastError.includes('Authentication failed') || lastError.includes('could not read Username')) {
551
+ errorMessage = 'Authentication failed. Please check your credentials.';
552
+ } else if (lastError.includes('Repository not found')) {
553
+ errorMessage = 'Repository not found. Please check the URL and ensure you have access.';
554
+ } else if (lastError.includes('already exists')) {
555
+ errorMessage = 'Directory already exists';
556
+ } else if (sanitizedError) {
557
+ errorMessage = sanitizedError;
558
+ }
559
+ try {
560
+ await fs.rm(clonePath, { recursive: true, force: true });
561
+ } catch (cleanupError) {
562
+ // cleanup failure ignored
563
+ }
564
+ sendEvent('error', { message: errorMessage });
565
+ }
566
+ res.end();
567
+ });
568
+
569
+ gitProcess.on('error', (error) => {
570
+ if (error.code === 'ENOENT') {
571
+ sendEvent('error', { message: 'Git is not installed or not in PATH' });
572
+ } else {
573
+ sendEvent('error', { message: error.message });
574
+ }
575
+ res.end();
576
+ });
577
+
578
+ req.on('close', () => {
579
+ gitProcess.kill();
580
+ });
581
+
582
+ } catch (error) {
583
+ sendEvent('error', { message: error.message });
584
+ res.end();
585
+ }
586
+ });
587
+
588
+ /**
589
+ * Helper function to clone a GitHub repository
590
+ */
591
+ function cloneGitHubRepository(githubUrl, destinationPath, githubToken = null) {
592
+ return new Promise((resolve, reject) => {
593
+ let cloneUrl = githubUrl;
594
+
595
+ if (githubToken) {
596
+ try {
597
+ const url = new URL(githubUrl);
598
+ url.username = githubToken;
599
+ url.password = '';
600
+ cloneUrl = url.toString();
601
+ } catch (error) {
602
+ // SSH URL - use as-is
603
+ }
604
+ }
605
+
606
+ const gitProcess = spawn('git', ['clone', '--progress', cloneUrl, destinationPath], {
607
+ stdio: ['ignore', 'pipe', 'pipe'],
608
+ env: {
609
+ ...process.env,
610
+ GIT_TERMINAL_PROMPT: '0'
611
+ }
612
+ });
613
+
614
+ let stdout = '';
615
+ let stderr = '';
616
+
617
+ gitProcess.stdout.on('data', (data) => {
618
+ stdout += data.toString();
619
+ });
620
+
621
+ gitProcess.stderr.on('data', (data) => {
622
+ stderr += data.toString();
623
+ });
624
+
625
+ gitProcess.on('close', (code) => {
626
+ if (code === 0) {
627
+ resolve({ stdout, stderr });
628
+ } else {
629
+ let errorMessage = 'Git clone failed';
630
+
631
+ if (stderr.includes('Authentication failed') || stderr.includes('could not read Username')) {
632
+ errorMessage = 'Authentication failed. Please check your GitHub token.';
633
+ } else if (stderr.includes('Repository not found')) {
634
+ errorMessage = 'Repository not found. Please check the URL and ensure you have access.';
635
+ } else if (stderr.includes('already exists')) {
636
+ errorMessage = 'Directory already exists';
637
+ } else if (stderr) {
638
+ errorMessage = stderr;
639
+ }
640
+
641
+ reject(new Error(errorMessage));
642
+ }
643
+ });
644
+
645
+ gitProcess.on('error', (error) => {
646
+ if (error.code === 'ENOENT') {
647
+ reject(new Error('Git is not installed or not in PATH'));
648
+ } else {
649
+ reject(error);
650
+ }
651
+ });
652
+ });
653
+ }
654
+
655
+ export default router;