@cloudcli-ai/cloudcli 1.28.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 (163) hide show
  1. package/LICENSE +718 -0
  2. package/README.de.md +239 -0
  3. package/README.ja.md +231 -0
  4. package/README.ko.md +230 -0
  5. package/README.md +242 -0
  6. package/README.ru.md +239 -0
  7. package/README.zh-CN.md +230 -0
  8. package/dist/api-docs.html +879 -0
  9. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  10. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  11. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  12. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  13. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  14. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  15. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  16. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  17. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  18. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  19. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  20. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  21. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  22. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  23. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  24. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  25. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  26. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  27. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  28. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  29. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  30. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  31. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  32. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  33. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  34. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  35. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  36. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  37. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  38. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  39. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  40. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  41. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  42. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  43. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  44. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  45. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  46. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  47. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  48. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  49. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  50. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  51. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  52. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  53. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  54. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  55. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  56. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  57. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  58. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  59. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  60. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  61. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  62. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  63. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  64. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  65. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  66. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  67. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  68. package/dist/assets/index-B1XAhG_4.css +32 -0
  69. package/dist/assets/index-BWQPmiP5.js +1275 -0
  70. package/dist/assets/vendor-codemirror-C8f1vU1x.js +41 -0
  71. package/dist/assets/vendor-react-CdSTmIF1.js +59 -0
  72. package/dist/assets/vendor-xterm-CJZjLICi.js +66 -0
  73. package/dist/clear-cache.html +85 -0
  74. package/dist/convert-icons.md +53 -0
  75. package/dist/favicon.png +0 -0
  76. package/dist/favicon.svg +9 -0
  77. package/dist/generate-icons.js +49 -0
  78. package/dist/icons/claude-ai-icon.svg +1 -0
  79. package/dist/icons/codex-white.svg +3 -0
  80. package/dist/icons/codex.svg +3 -0
  81. package/dist/icons/cursor-white.svg +12 -0
  82. package/dist/icons/cursor.svg +1 -0
  83. package/dist/icons/gemini-ai-icon.svg +1 -0
  84. package/dist/icons/icon-128x128.png +0 -0
  85. package/dist/icons/icon-128x128.svg +12 -0
  86. package/dist/icons/icon-144x144.png +0 -0
  87. package/dist/icons/icon-144x144.svg +12 -0
  88. package/dist/icons/icon-152x152.png +0 -0
  89. package/dist/icons/icon-152x152.svg +12 -0
  90. package/dist/icons/icon-192x192.png +0 -0
  91. package/dist/icons/icon-192x192.svg +12 -0
  92. package/dist/icons/icon-384x384.png +0 -0
  93. package/dist/icons/icon-384x384.svg +12 -0
  94. package/dist/icons/icon-512x512.png +0 -0
  95. package/dist/icons/icon-512x512.svg +12 -0
  96. package/dist/icons/icon-72x72.png +0 -0
  97. package/dist/icons/icon-72x72.svg +12 -0
  98. package/dist/icons/icon-96x96.png +0 -0
  99. package/dist/icons/icon-96x96.svg +12 -0
  100. package/dist/icons/icon-template.svg +12 -0
  101. package/dist/index.html +52 -0
  102. package/dist/logo-128.png +0 -0
  103. package/dist/logo-256.png +0 -0
  104. package/dist/logo-32.png +0 -0
  105. package/dist/logo-512.png +0 -0
  106. package/dist/logo-64.png +0 -0
  107. package/dist/logo.svg +17 -0
  108. package/dist/manifest.json +61 -0
  109. package/dist/screenshots/cli-selection.png +0 -0
  110. package/dist/screenshots/desktop-main.png +0 -0
  111. package/dist/screenshots/mobile-chat.png +0 -0
  112. package/dist/screenshots/tools-modal.png +0 -0
  113. package/dist/sw.js +124 -0
  114. package/package.json +153 -0
  115. package/scripts/fix-node-pty.js +67 -0
  116. package/server/claude-sdk.js +817 -0
  117. package/server/cli.js +330 -0
  118. package/server/constants/config.js +5 -0
  119. package/server/cursor-cli.js +335 -0
  120. package/server/database/db.js +630 -0
  121. package/server/database/init.sql +99 -0
  122. package/server/gemini-cli.js +453 -0
  123. package/server/gemini-response-handler.js +79 -0
  124. package/server/index.js +2577 -0
  125. package/server/load-env.js +29 -0
  126. package/server/middleware/auth.js +132 -0
  127. package/server/openai-codex.js +418 -0
  128. package/server/projects.js +2561 -0
  129. package/server/providers/claude/adapter.js +278 -0
  130. package/server/providers/codex/adapter.js +248 -0
  131. package/server/providers/cursor/adapter.js +353 -0
  132. package/server/providers/gemini/adapter.js +186 -0
  133. package/server/providers/registry.js +44 -0
  134. package/server/providers/types.js +119 -0
  135. package/server/providers/utils.js +29 -0
  136. package/server/routes/agent.js +1245 -0
  137. package/server/routes/auth.js +135 -0
  138. package/server/routes/cli-auth.js +434 -0
  139. package/server/routes/codex.js +329 -0
  140. package/server/routes/commands.js +601 -0
  141. package/server/routes/cursor.js +798 -0
  142. package/server/routes/gemini.js +24 -0
  143. package/server/routes/git.js +1488 -0
  144. package/server/routes/mcp-utils.js +48 -0
  145. package/server/routes/mcp.js +552 -0
  146. package/server/routes/messages.js +61 -0
  147. package/server/routes/plugins.js +307 -0
  148. package/server/routes/projects.js +548 -0
  149. package/server/routes/settings.js +276 -0
  150. package/server/routes/taskmaster.js +1963 -0
  151. package/server/routes/user.js +123 -0
  152. package/server/services/notification-orchestrator.js +227 -0
  153. package/server/services/vapid-keys.js +35 -0
  154. package/server/sessionManager.js +226 -0
  155. package/server/utils/commandParser.js +303 -0
  156. package/server/utils/frontmatter.js +18 -0
  157. package/server/utils/gitConfig.js +34 -0
  158. package/server/utils/mcp-detector.js +198 -0
  159. package/server/utils/plugin-loader.js +457 -0
  160. package/server/utils/plugin-process-manager.js +184 -0
  161. package/server/utils/taskmaster-websocket.js +129 -0
  162. package/shared/modelConstants.js +92 -0
  163. package/shared/networkHosts.js +22 -0
@@ -0,0 +1,135 @@
1
+ import express from 'express';
2
+ import bcrypt from 'bcrypt';
3
+ import { userDb, db } from '../database/db.js';
4
+ import { generateToken, authenticateToken } from '../middleware/auth.js';
5
+
6
+ const router = express.Router();
7
+
8
+ // Check auth status and setup requirements
9
+ router.get('/status', async (req, res) => {
10
+ try {
11
+ const hasUsers = await userDb.hasUsers();
12
+ res.json({
13
+ needsSetup: !hasUsers,
14
+ isAuthenticated: false // Will be overridden by frontend if token exists
15
+ });
16
+ } catch (error) {
17
+ console.error('Auth status error:', error);
18
+ res.status(500).json({ error: 'Internal server error' });
19
+ }
20
+ });
21
+
22
+ // User registration (setup) - only allowed if no users exist
23
+ router.post('/register', async (req, res) => {
24
+ try {
25
+ const { username, password } = req.body;
26
+
27
+ // Validate input
28
+ if (!username || !password) {
29
+ return res.status(400).json({ error: 'Username and password are required' });
30
+ }
31
+
32
+ if (username.length < 3 || password.length < 6) {
33
+ return res.status(400).json({ error: 'Username must be at least 3 characters, password at least 6 characters' });
34
+ }
35
+
36
+ // Use a transaction to prevent race conditions
37
+ db.prepare('BEGIN').run();
38
+ try {
39
+ // Check if users already exist (only allow one user)
40
+ const hasUsers = userDb.hasUsers();
41
+ if (hasUsers) {
42
+ db.prepare('ROLLBACK').run();
43
+ return res.status(403).json({ error: 'User already exists. This is a single-user system.' });
44
+ }
45
+
46
+ // Hash password
47
+ const saltRounds = 12;
48
+ const passwordHash = await bcrypt.hash(password, saltRounds);
49
+
50
+ // Create user
51
+ const user = userDb.createUser(username, passwordHash);
52
+
53
+ // Generate token
54
+ const token = generateToken(user);
55
+
56
+ db.prepare('COMMIT').run();
57
+
58
+ // Update last login (non-fatal, outside transaction)
59
+ userDb.updateLastLogin(user.id);
60
+
61
+ res.json({
62
+ success: true,
63
+ user: { id: user.id, username: user.username },
64
+ token
65
+ });
66
+ } catch (error) {
67
+ db.prepare('ROLLBACK').run();
68
+ throw error;
69
+ }
70
+
71
+ } catch (error) {
72
+ console.error('Registration error:', error);
73
+ if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
74
+ res.status(409).json({ error: 'Username already exists' });
75
+ } else {
76
+ res.status(500).json({ error: 'Internal server error' });
77
+ }
78
+ }
79
+ });
80
+
81
+ // User login
82
+ router.post('/login', async (req, res) => {
83
+ try {
84
+ const { username, password } = req.body;
85
+
86
+ // Validate input
87
+ if (!username || !password) {
88
+ return res.status(400).json({ error: 'Username and password are required' });
89
+ }
90
+
91
+ // Get user from database
92
+ const user = userDb.getUserByUsername(username);
93
+ if (!user) {
94
+ return res.status(401).json({ error: 'Invalid username or password' });
95
+ }
96
+
97
+ // Verify password
98
+ const isValidPassword = await bcrypt.compare(password, user.password_hash);
99
+ if (!isValidPassword) {
100
+ return res.status(401).json({ error: 'Invalid username or password' });
101
+ }
102
+
103
+ // Generate token
104
+ const token = generateToken(user);
105
+
106
+ // Update last login
107
+ userDb.updateLastLogin(user.id);
108
+
109
+ res.json({
110
+ success: true,
111
+ user: { id: user.id, username: user.username },
112
+ token
113
+ });
114
+
115
+ } catch (error) {
116
+ console.error('Login error:', error);
117
+ res.status(500).json({ error: 'Internal server error' });
118
+ }
119
+ });
120
+
121
+ // Get current user (protected route)
122
+ router.get('/user', authenticateToken, (req, res) => {
123
+ res.json({
124
+ user: req.user
125
+ });
126
+ });
127
+
128
+ // Logout (client-side token removal, but this endpoint can be used for logging)
129
+ router.post('/logout', authenticateToken, (req, res) => {
130
+ // In a simple JWT system, logout is mainly client-side
131
+ // This endpoint exists for consistency and potential future logging
132
+ res.json({ success: true, message: 'Logged out successfully' });
133
+ });
134
+
135
+ export default router;
@@ -0,0 +1,434 @@
1
+ import express from 'express';
2
+ import { spawn } from 'child_process';
3
+ import fs from 'fs/promises';
4
+ import path from 'path';
5
+ import os from 'os';
6
+
7
+ const router = express.Router();
8
+
9
+ router.get('/claude/status', async (req, res) => {
10
+ try {
11
+ const credentialsResult = await checkClaudeCredentials();
12
+
13
+ if (credentialsResult.authenticated) {
14
+ return res.json({
15
+ authenticated: true,
16
+ email: credentialsResult.email || 'Authenticated',
17
+ method: credentialsResult.method // 'api_key' or 'credentials_file'
18
+ });
19
+ }
20
+
21
+ return res.json({
22
+ authenticated: false,
23
+ email: null,
24
+ method: null,
25
+ error: credentialsResult.error || 'Not authenticated'
26
+ });
27
+
28
+ } catch (error) {
29
+ console.error('Error checking Claude auth status:', error);
30
+ res.status(500).json({
31
+ authenticated: false,
32
+ email: null,
33
+ method: null,
34
+ error: error.message
35
+ });
36
+ }
37
+ });
38
+
39
+ router.get('/cursor/status', async (req, res) => {
40
+ try {
41
+ const result = await checkCursorStatus();
42
+
43
+ res.json({
44
+ authenticated: result.authenticated,
45
+ email: result.email,
46
+ error: result.error
47
+ });
48
+
49
+ } catch (error) {
50
+ console.error('Error checking Cursor auth status:', error);
51
+ res.status(500).json({
52
+ authenticated: false,
53
+ email: null,
54
+ error: error.message
55
+ });
56
+ }
57
+ });
58
+
59
+ router.get('/codex/status', async (req, res) => {
60
+ try {
61
+ const result = await checkCodexCredentials();
62
+
63
+ res.json({
64
+ authenticated: result.authenticated,
65
+ email: result.email,
66
+ error: result.error
67
+ });
68
+
69
+ } catch (error) {
70
+ console.error('Error checking Codex auth status:', error);
71
+ res.status(500).json({
72
+ authenticated: false,
73
+ email: null,
74
+ error: error.message
75
+ });
76
+ }
77
+ });
78
+
79
+ router.get('/gemini/status', async (req, res) => {
80
+ try {
81
+ const result = await checkGeminiCredentials();
82
+
83
+ res.json({
84
+ authenticated: result.authenticated,
85
+ email: result.email,
86
+ error: result.error
87
+ });
88
+
89
+ } catch (error) {
90
+ console.error('Error checking Gemini auth status:', error);
91
+ res.status(500).json({
92
+ authenticated: false,
93
+ email: null,
94
+ error: error.message
95
+ });
96
+ }
97
+ });
98
+
99
+ async function loadClaudeSettingsEnv() {
100
+ try {
101
+ const settingsPath = path.join(os.homedir(), '.claude', 'settings.json');
102
+ const content = await fs.readFile(settingsPath, 'utf8');
103
+ const settings = JSON.parse(content);
104
+
105
+ if (settings?.env && typeof settings.env === 'object') {
106
+ return settings.env;
107
+ }
108
+ } catch (error) {
109
+ // Ignore missing or malformed settings and fall back to other auth sources.
110
+ }
111
+
112
+ return {};
113
+ }
114
+
115
+ /**
116
+ * Checks Claude authentication credentials using two methods with priority order:
117
+ *
118
+ * Priority 1: ANTHROPIC_API_KEY environment variable
119
+ * Priority 1b: ~/.claude/settings.json env values
120
+ * Priority 2: ~/.claude/.credentials.json OAuth tokens
121
+ *
122
+ * The Claude Agent SDK prioritizes environment variables over authenticated subscriptions.
123
+ * This matching behavior ensures consistency with how the SDK authenticates.
124
+ *
125
+ * References:
126
+ * - https://support.claude.com/en/articles/12304248-managing-api-key-environment-variables-in-claude-code
127
+ * "Claude Code prioritizes environment variable API keys over authenticated subscriptions"
128
+ * - https://platform.claude.com/docs/en/agent-sdk/overview
129
+ * SDK authentication documentation
130
+ *
131
+ * @returns {Promise<Object>} Authentication status with { authenticated, email, method }
132
+ * - authenticated: boolean indicating if valid credentials exist
133
+ * - email: user email or auth method identifier
134
+ * - method: 'api_key' for env var, 'credentials_file' for OAuth tokens
135
+ */
136
+ async function checkClaudeCredentials() {
137
+ // Priority 1: Check for ANTHROPIC_API_KEY environment variable
138
+ // The SDK checks this first and uses it if present, even if OAuth tokens exist.
139
+ // When set, API calls are charged via pay-as-you-go rates instead of subscription.
140
+ if (process.env.ANTHROPIC_API_KEY && process.env.ANTHROPIC_API_KEY.trim()) {
141
+ return {
142
+ authenticated: true,
143
+ email: 'API Key Auth',
144
+ method: 'api_key'
145
+ };
146
+ }
147
+
148
+ // Priority 1b: Check ~/.claude/settings.json env values.
149
+ // Claude Code can read proxy/auth values from settings.json even when the
150
+ // CloudCLI server process itself was not started with those env vars exported.
151
+ const settingsEnv = await loadClaudeSettingsEnv();
152
+
153
+ if (typeof settingsEnv.ANTHROPIC_API_KEY === 'string' && settingsEnv.ANTHROPIC_API_KEY.trim()) {
154
+ return {
155
+ authenticated: true,
156
+ email: 'API Key Auth',
157
+ method: 'api_key'
158
+ };
159
+ }
160
+
161
+ if (typeof settingsEnv.ANTHROPIC_AUTH_TOKEN === 'string' && settingsEnv.ANTHROPIC_AUTH_TOKEN.trim()) {
162
+ return {
163
+ authenticated: true,
164
+ email: 'Configured via settings.json',
165
+ method: 'api_key'
166
+ };
167
+ }
168
+
169
+ // Priority 2: Check ~/.claude/.credentials.json for OAuth tokens
170
+ // This is the standard authentication method used by Claude CLI after running
171
+ // 'claude /login' or 'claude setup-token' commands.
172
+ try {
173
+ const credPath = path.join(os.homedir(), '.claude', '.credentials.json');
174
+ const content = await fs.readFile(credPath, 'utf8');
175
+ const creds = JSON.parse(content);
176
+
177
+ const oauth = creds.claudeAiOauth;
178
+ if (oauth && oauth.accessToken) {
179
+ const isExpired = oauth.expiresAt && Date.now() >= oauth.expiresAt;
180
+
181
+ if (!isExpired) {
182
+ return {
183
+ authenticated: true,
184
+ email: creds.email || creds.user || null,
185
+ method: 'credentials_file'
186
+ };
187
+ }
188
+ }
189
+
190
+ return {
191
+ authenticated: false,
192
+ email: null,
193
+ method: null
194
+ };
195
+ } catch (error) {
196
+ return {
197
+ authenticated: false,
198
+ email: null,
199
+ method: null
200
+ };
201
+ }
202
+ }
203
+
204
+ function checkCursorStatus() {
205
+ return new Promise((resolve) => {
206
+ let processCompleted = false;
207
+
208
+ const timeout = setTimeout(() => {
209
+ if (!processCompleted) {
210
+ processCompleted = true;
211
+ if (childProcess) {
212
+ childProcess.kill();
213
+ }
214
+ resolve({
215
+ authenticated: false,
216
+ email: null,
217
+ error: 'Command timeout'
218
+ });
219
+ }
220
+ }, 5000);
221
+
222
+ let childProcess;
223
+ try {
224
+ childProcess = spawn('cursor-agent', ['status']);
225
+ } catch (err) {
226
+ clearTimeout(timeout);
227
+ processCompleted = true;
228
+ resolve({
229
+ authenticated: false,
230
+ email: null,
231
+ error: 'Cursor CLI not found or not installed'
232
+ });
233
+ return;
234
+ }
235
+
236
+ let stdout = '';
237
+ let stderr = '';
238
+
239
+ childProcess.stdout.on('data', (data) => {
240
+ stdout += data.toString();
241
+ });
242
+
243
+ childProcess.stderr.on('data', (data) => {
244
+ stderr += data.toString();
245
+ });
246
+
247
+ childProcess.on('close', (code) => {
248
+ if (processCompleted) return;
249
+ processCompleted = true;
250
+ clearTimeout(timeout);
251
+
252
+ if (code === 0) {
253
+ const emailMatch = stdout.match(/Logged in as ([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/i);
254
+
255
+ if (emailMatch) {
256
+ resolve({
257
+ authenticated: true,
258
+ email: emailMatch[1],
259
+ output: stdout
260
+ });
261
+ } else if (stdout.includes('Logged in')) {
262
+ resolve({
263
+ authenticated: true,
264
+ email: 'Logged in',
265
+ output: stdout
266
+ });
267
+ } else {
268
+ resolve({
269
+ authenticated: false,
270
+ email: null,
271
+ error: 'Not logged in'
272
+ });
273
+ }
274
+ } else {
275
+ resolve({
276
+ authenticated: false,
277
+ email: null,
278
+ error: stderr || 'Not logged in'
279
+ });
280
+ }
281
+ });
282
+
283
+ childProcess.on('error', (err) => {
284
+ if (processCompleted) return;
285
+ processCompleted = true;
286
+ clearTimeout(timeout);
287
+
288
+ resolve({
289
+ authenticated: false,
290
+ email: null,
291
+ error: 'Cursor CLI not found or not installed'
292
+ });
293
+ });
294
+ });
295
+ }
296
+
297
+ async function checkCodexCredentials() {
298
+ try {
299
+ const authPath = path.join(os.homedir(), '.codex', 'auth.json');
300
+ const content = await fs.readFile(authPath, 'utf8');
301
+ const auth = JSON.parse(content);
302
+
303
+ // Tokens are nested under 'tokens' key
304
+ const tokens = auth.tokens || {};
305
+
306
+ // Check for valid tokens (id_token or access_token)
307
+ if (tokens.id_token || tokens.access_token) {
308
+ // Try to extract email from id_token JWT payload
309
+ let email = 'Authenticated';
310
+ if (tokens.id_token) {
311
+ try {
312
+ // JWT is base64url encoded: header.payload.signature
313
+ const parts = tokens.id_token.split('.');
314
+ if (parts.length >= 2) {
315
+ // Decode the payload (second part)
316
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
317
+ email = payload.email || payload.user || 'Authenticated';
318
+ }
319
+ } catch {
320
+ // If JWT decoding fails, use fallback
321
+ email = 'Authenticated';
322
+ }
323
+ }
324
+
325
+ return {
326
+ authenticated: true,
327
+ email
328
+ };
329
+ }
330
+
331
+ // Also check for OPENAI_API_KEY as fallback auth method
332
+ if (auth.OPENAI_API_KEY) {
333
+ return {
334
+ authenticated: true,
335
+ email: 'API Key Auth'
336
+ };
337
+ }
338
+
339
+ return {
340
+ authenticated: false,
341
+ email: null,
342
+ error: 'No valid tokens found'
343
+ };
344
+ } catch (error) {
345
+ if (error.code === 'ENOENT') {
346
+ return {
347
+ authenticated: false,
348
+ email: null,
349
+ error: 'Codex not configured'
350
+ };
351
+ }
352
+ return {
353
+ authenticated: false,
354
+ email: null,
355
+ error: error.message
356
+ };
357
+ }
358
+ }
359
+
360
+ async function checkGeminiCredentials() {
361
+ if (process.env.GEMINI_API_KEY && process.env.GEMINI_API_KEY.trim()) {
362
+ return {
363
+ authenticated: true,
364
+ email: 'API Key Auth'
365
+ };
366
+ }
367
+
368
+ try {
369
+ const credsPath = path.join(os.homedir(), '.gemini', 'oauth_creds.json');
370
+ const content = await fs.readFile(credsPath, 'utf8');
371
+ const creds = JSON.parse(content);
372
+
373
+ if (creds.access_token) {
374
+ let email = 'OAuth Session';
375
+
376
+ try {
377
+ // Validate token against Google API
378
+ const tokenRes = await fetch(`https://oauth2.googleapis.com/tokeninfo?access_token=${creds.access_token}`);
379
+ if (tokenRes.ok) {
380
+ const tokenInfo = await tokenRes.json();
381
+ if (tokenInfo.email) {
382
+ email = tokenInfo.email;
383
+ }
384
+ } else if (!creds.refresh_token) {
385
+ // Token invalid and no refresh token available
386
+ return {
387
+ authenticated: false,
388
+ email: null,
389
+ error: 'Access token invalid and no refresh token found'
390
+ };
391
+ } else {
392
+ // Token might be expired but we have a refresh token, so CLI will refresh it
393
+ try {
394
+ const accPath = path.join(os.homedir(), '.gemini', 'google_accounts.json');
395
+ const accContent = await fs.readFile(accPath, 'utf8');
396
+ const accounts = JSON.parse(accContent);
397
+ if (accounts.active) {
398
+ email = accounts.active;
399
+ }
400
+ } catch (e) { }
401
+ }
402
+ } catch (e) {
403
+ // Network error, fallback to checking local accounts file
404
+ try {
405
+ const accPath = path.join(os.homedir(), '.gemini', 'google_accounts.json');
406
+ const accContent = await fs.readFile(accPath, 'utf8');
407
+ const accounts = JSON.parse(accContent);
408
+ if (accounts.active) {
409
+ email = accounts.active;
410
+ }
411
+ } catch (err) { }
412
+ }
413
+
414
+ return {
415
+ authenticated: true,
416
+ email: email
417
+ };
418
+ }
419
+
420
+ return {
421
+ authenticated: false,
422
+ email: null,
423
+ error: 'No valid tokens found in oauth_creds'
424
+ };
425
+ } catch (error) {
426
+ return {
427
+ authenticated: false,
428
+ email: null,
429
+ error: 'Gemini CLI not configured'
430
+ };
431
+ }
432
+ }
433
+
434
+ export default router;