@siteboon/claude-code-ui 1.24.0 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/index.js CHANGED
@@ -64,6 +64,8 @@ import cliAuthRoutes from './routes/cli-auth.js';
64
64
  import userRoutes from './routes/user.js';
65
65
  import codexRoutes from './routes/codex.js';
66
66
  import geminiRoutes from './routes/gemini.js';
67
+ import pluginsRoutes from './routes/plugins.js';
68
+ import { startEnabledPluginServers, stopAllPlugins } from './utils/plugin-process-manager.js';
67
69
  import { initializeDatabase, sessionNamesDb, applyCustomSessionNames } from './database/db.js';
68
70
  import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
69
71
  import { IS_PLATFORM } from './constants/config.js';
@@ -324,7 +326,7 @@ const wss = new WebSocketServer({
324
326
  // Make WebSocket server available to routes
325
327
  app.locals.wss = wss;
326
328
 
327
- app.use(cors());
329
+ app.use(cors({ exposedHeaders: ['X-Refreshed-Token'] }));
328
330
  app.use(express.json({
329
331
  limit: '50mb',
330
332
  type: (req) => {
@@ -389,6 +391,9 @@ app.use('/api/codex', authenticateToken, codexRoutes);
389
391
  // Gemini API Routes (protected)
390
392
  app.use('/api/gemini', authenticateToken, geminiRoutes);
391
393
 
394
+ // Plugins API Routes (protected)
395
+ app.use('/api/plugins', authenticateToken, pluginsRoutes);
396
+
392
397
  // Agent API Routes (uses API key authentication)
393
398
  app.use('/api/agent', agentRoutes);
394
399
 
@@ -1694,50 +1699,43 @@ function handleShellConnection(ws) {
1694
1699
  }));
1695
1700
 
1696
1701
  try {
1697
- // Prepare the shell command adapted to the platform and provider
1702
+ // Validate projectPath resolve to absolute and verify it exists
1703
+ const resolvedProjectPath = path.resolve(projectPath);
1704
+ try {
1705
+ const stats = fs.statSync(resolvedProjectPath);
1706
+ if (!stats.isDirectory()) {
1707
+ throw new Error('Not a directory');
1708
+ }
1709
+ } catch (pathErr) {
1710
+ ws.send(JSON.stringify({ type: 'error', message: 'Invalid project path' }));
1711
+ return;
1712
+ }
1713
+
1714
+ // Validate sessionId — only allow safe characters
1715
+ const safeSessionIdPattern = /^[a-zA-Z0-9_.\-:]+$/;
1716
+ if (sessionId && !safeSessionIdPattern.test(sessionId)) {
1717
+ ws.send(JSON.stringify({ type: 'error', message: 'Invalid session ID' }));
1718
+ return;
1719
+ }
1720
+
1721
+ // Build shell command — use cwd for project path (never interpolate into shell string)
1698
1722
  let shellCommand;
1699
1723
  if (isPlainShell) {
1700
- // Plain shell mode - just run the initial command in the project directory
1701
- if (os.platform() === 'win32') {
1702
- shellCommand = `Set-Location -Path "${projectPath}"; ${initialCommand}`;
1703
- } else {
1704
- shellCommand = `cd "${projectPath}" && ${initialCommand}`;
1705
- }
1724
+ // Plain shell mode - run the initial command in the project directory
1725
+ shellCommand = initialCommand;
1706
1726
  } else if (provider === 'cursor') {
1707
- // Use cursor-agent command
1708
- if (os.platform() === 'win32') {
1709
- if (hasSession && sessionId) {
1710
- shellCommand = `Set-Location -Path "${projectPath}"; cursor-agent --resume="${sessionId}"`;
1711
- } else {
1712
- shellCommand = `Set-Location -Path "${projectPath}"; cursor-agent`;
1713
- }
1727
+ if (hasSession && sessionId) {
1728
+ shellCommand = `cursor-agent --resume="${sessionId}"`;
1714
1729
  } else {
1715
- if (hasSession && sessionId) {
1716
- shellCommand = `cd "${projectPath}" && cursor-agent --resume="${sessionId}"`;
1717
- } else {
1718
- shellCommand = `cd "${projectPath}" && cursor-agent`;
1719
- }
1730
+ shellCommand = 'cursor-agent';
1720
1731
  }
1721
-
1722
1732
  } else if (provider === 'codex') {
1723
- // Use codex command
1724
- if (os.platform() === 'win32') {
1725
- if (hasSession && sessionId) {
1726
- // Try to resume session, but with fallback to a new session if it fails
1727
- shellCommand = `Set-Location -Path "${projectPath}"; codex resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { codex }`;
1728
- } else {
1729
- shellCommand = `Set-Location -Path "${projectPath}"; codex`;
1730
- }
1733
+ if (hasSession && sessionId) {
1734
+ shellCommand = `codex resume "${sessionId}" || codex`;
1731
1735
  } else {
1732
- if (hasSession && sessionId) {
1733
- // Try to resume session, but with fallback to a new session if it fails
1734
- shellCommand = `cd "${projectPath}" && codex resume "${sessionId}" || codex`;
1735
- } else {
1736
- shellCommand = `cd "${projectPath}" && codex`;
1737
- }
1736
+ shellCommand = 'codex';
1738
1737
  }
1739
1738
  } else if (provider === 'gemini') {
1740
- // Use gemini command
1741
1739
  const command = initialCommand || 'gemini';
1742
1740
  let resumeId = sessionId;
1743
1741
  if (hasSession && sessionId) {
@@ -1748,41 +1746,28 @@ function handleShellConnection(ws) {
1748
1746
  const sess = sessionManager.getSession(sessionId);
1749
1747
  if (sess && sess.cliSessionId) {
1750
1748
  resumeId = sess.cliSessionId;
1749
+ // Validate the looked-up CLI session ID too
1750
+ if (!safeSessionIdPattern.test(resumeId)) {
1751
+ resumeId = null;
1752
+ }
1751
1753
  }
1752
1754
  } catch (err) {
1753
1755
  console.error('Failed to get Gemini CLI session ID:', err);
1754
1756
  }
1755
1757
  }
1756
1758
 
1757
- if (os.platform() === 'win32') {
1758
- if (hasSession && resumeId) {
1759
- shellCommand = `Set-Location -Path "${projectPath}"; ${command} --resume "${resumeId}"`;
1760
- } else {
1761
- shellCommand = `Set-Location -Path "${projectPath}"; ${command}`;
1762
- }
1759
+ if (hasSession && resumeId) {
1760
+ shellCommand = `${command} --resume "${resumeId}"`;
1763
1761
  } else {
1764
- if (hasSession && resumeId) {
1765
- shellCommand = `cd "${projectPath}" && ${command} --resume "${resumeId}"`;
1766
- } else {
1767
- shellCommand = `cd "${projectPath}" && ${command}`;
1768
- }
1762
+ shellCommand = command;
1769
1763
  }
1770
1764
  } else {
1771
- // Use claude command (default) or initialCommand if provided
1765
+ // Claude (default provider)
1772
1766
  const command = initialCommand || 'claude';
1773
- if (os.platform() === 'win32') {
1774
- if (hasSession && sessionId) {
1775
- // Try to resume session, but with fallback to new session if it fails
1776
- shellCommand = `Set-Location -Path "${projectPath}"; claude --resume ${sessionId}; if ($LASTEXITCODE -ne 0) { claude }`;
1777
- } else {
1778
- shellCommand = `Set-Location -Path "${projectPath}"; ${command}`;
1779
- }
1767
+ if (hasSession && sessionId) {
1768
+ shellCommand = `claude --resume "${sessionId}" || claude`;
1780
1769
  } else {
1781
- if (hasSession && sessionId) {
1782
- shellCommand = `cd "${projectPath}" && claude --resume ${sessionId} || claude`;
1783
- } else {
1784
- shellCommand = `cd "${projectPath}" && ${command}`;
1785
- }
1770
+ shellCommand = command;
1786
1771
  }
1787
1772
  }
1788
1773
 
@@ -1801,7 +1786,7 @@ function handleShellConnection(ws) {
1801
1786
  name: 'xterm-256color',
1802
1787
  cols: termCols,
1803
1788
  rows: termRows,
1804
- cwd: os.homedir(),
1789
+ cwd: resolvedProjectPath,
1805
1790
  env: {
1806
1791
  ...process.env,
1807
1792
  TERM: 'xterm-256color',
@@ -2532,7 +2517,20 @@ async function startServer() {
2532
2517
 
2533
2518
  // Start watching the projects folder for changes
2534
2519
  await setupProjectsWatcher();
2520
+
2521
+ // Start server-side plugin processes for enabled plugins
2522
+ startEnabledPluginServers().catch(err => {
2523
+ console.error('[Plugins] Error during startup:', err.message);
2524
+ });
2535
2525
  });
2526
+
2527
+ // Clean up plugin processes on shutdown
2528
+ const shutdownPlugins = async () => {
2529
+ await stopAllPlugins();
2530
+ process.exit(0);
2531
+ };
2532
+ process.on('SIGTERM', () => void shutdownPlugins());
2533
+ process.on('SIGINT', () => void shutdownPlugins());
2536
2534
  } catch (error) {
2537
2535
  console.error('[ERROR] Failed to start server:', error);
2538
2536
  process.exit(1);
@@ -1,9 +1,9 @@
1
1
  import jwt from 'jsonwebtoken';
2
- import { userDb } from '../database/db.js';
2
+ import { userDb, appConfigDb } from '../database/db.js';
3
3
  import { IS_PLATFORM } from '../constants/config.js';
4
4
 
5
- // Get JWT secret from environment or use default (for development)
6
- const JWT_SECRET = process.env.JWT_SECRET || 'claude-ui-dev-secret-change-in-production';
5
+ // Use env var if set, otherwise auto-generate a unique secret per installation
6
+ const JWT_SECRET = process.env.JWT_SECRET || appConfigDb.getOrCreateJwtSecret();
7
7
 
8
8
  // Optional API key middleware
9
9
  const validateApiKey = (req, res, next) => {
@@ -58,6 +58,16 @@ const authenticateToken = async (req, res, next) => {
58
58
  return res.status(401).json({ error: 'Invalid token. User not found.' });
59
59
  }
60
60
 
61
+ // Auto-refresh: if token is past halfway through its lifetime, issue a new one
62
+ if (decoded.exp && decoded.iat) {
63
+ const now = Math.floor(Date.now() / 1000);
64
+ const halfLife = (decoded.exp - decoded.iat) / 2;
65
+ if (now > decoded.iat + halfLife) {
66
+ const newToken = generateToken(user);
67
+ res.setHeader('X-Refreshed-Token', newToken);
68
+ }
69
+ }
70
+
61
71
  req.user = user;
62
72
  next();
63
73
  } catch (error) {
@@ -66,15 +76,15 @@ const authenticateToken = async (req, res, next) => {
66
76
  }
67
77
  };
68
78
 
69
- // Generate JWT token (never expires)
79
+ // Generate JWT token
70
80
  const generateToken = (user) => {
71
81
  return jwt.sign(
72
- {
73
- userId: user.id,
74
- username: user.username
82
+ {
83
+ userId: user.id,
84
+ username: user.username
75
85
  },
76
- JWT_SECRET
77
- // No expiration - token lasts forever
86
+ JWT_SECRET,
87
+ { expiresIn: '7d' }
78
88
  );
79
89
  };
80
90
 
@@ -101,7 +111,12 @@ const authenticateWebSocket = (token) => {
101
111
 
102
112
  try {
103
113
  const decoded = jwt.verify(token, JWT_SECRET);
104
- return decoded;
114
+ // Verify user actually exists in database (matches REST authenticateToken behavior)
115
+ const user = userDb.getUserById(decoded.userId);
116
+ if (!user) {
117
+ return null;
118
+ }
119
+ return { userId: user.id, username: user.username };
105
120
  } catch (error) {
106
121
  console.error('WebSocket token verification error:', error);
107
122
  return null;
@@ -0,0 +1,303 @@
1
+ import express from 'express';
2
+ import path from 'path';
3
+ import http from 'http';
4
+ import mime from 'mime-types';
5
+ import fs from 'fs';
6
+ import {
7
+ scanPlugins,
8
+ getPluginsConfig,
9
+ getPluginsDir,
10
+ savePluginsConfig,
11
+ getPluginDir,
12
+ resolvePluginAssetPath,
13
+ installPluginFromGit,
14
+ updatePluginFromGit,
15
+ uninstallPlugin,
16
+ } from '../utils/plugin-loader.js';
17
+ import {
18
+ startPluginServer,
19
+ stopPluginServer,
20
+ getPluginPort,
21
+ isPluginRunning,
22
+ } from '../utils/plugin-process-manager.js';
23
+
24
+ const router = express.Router();
25
+
26
+ // GET / — List all installed plugins (includes server running status)
27
+ router.get('/', (req, res) => {
28
+ try {
29
+ const plugins = scanPlugins().map(p => ({
30
+ ...p,
31
+ serverRunning: p.server ? isPluginRunning(p.name) : false,
32
+ }));
33
+ res.json({ plugins });
34
+ } catch (err) {
35
+ res.status(500).json({ error: 'Failed to scan plugins', details: err.message });
36
+ }
37
+ });
38
+
39
+ // GET /:name/manifest — Get single plugin manifest
40
+ router.get('/:name/manifest', (req, res) => {
41
+ try {
42
+ if (!/^[a-zA-Z0-9_-]+$/.test(req.params.name)) {
43
+ return res.status(400).json({ error: 'Invalid plugin name' });
44
+ }
45
+ const plugins = scanPlugins();
46
+ const plugin = plugins.find(p => p.name === req.params.name);
47
+ if (!plugin) {
48
+ return res.status(404).json({ error: 'Plugin not found' });
49
+ }
50
+ res.json(plugin);
51
+ } catch (err) {
52
+ res.status(500).json({ error: 'Failed to read plugin manifest', details: err.message });
53
+ }
54
+ });
55
+
56
+ // GET /:name/assets/* — Serve plugin static files
57
+ router.get('/:name/assets/*', (req, res) => {
58
+ const pluginName = req.params.name;
59
+ if (!/^[a-zA-Z0-9_-]+$/.test(pluginName)) {
60
+ return res.status(400).json({ error: 'Invalid plugin name' });
61
+ }
62
+ const assetPath = req.params[0];
63
+
64
+ if (!assetPath) {
65
+ return res.status(400).json({ error: 'No asset path specified' });
66
+ }
67
+
68
+ const resolvedPath = resolvePluginAssetPath(pluginName, assetPath);
69
+ if (!resolvedPath) {
70
+ return res.status(404).json({ error: 'Asset not found' });
71
+ }
72
+
73
+ try {
74
+ const stat = fs.statSync(resolvedPath);
75
+ if (!stat.isFile()) {
76
+ return res.status(404).json({ error: 'Asset not found' });
77
+ }
78
+ } catch {
79
+ return res.status(404).json({ error: 'Asset not found' });
80
+ }
81
+
82
+ const contentType = mime.lookup(resolvedPath) || 'application/octet-stream';
83
+ res.setHeader('Content-Type', contentType);
84
+ const stream = fs.createReadStream(resolvedPath);
85
+ stream.on('error', () => {
86
+ if (!res.headersSent) {
87
+ res.status(500).json({ error: 'Failed to read asset' });
88
+ } else {
89
+ res.end();
90
+ }
91
+ });
92
+ stream.pipe(res);
93
+ });
94
+
95
+ // PUT /:name/enable — Toggle plugin enabled/disabled (starts/stops server if applicable)
96
+ router.put('/:name/enable', async (req, res) => {
97
+ try {
98
+ const { enabled } = req.body;
99
+ if (typeof enabled !== 'boolean') {
100
+ return res.status(400).json({ error: '"enabled" must be a boolean' });
101
+ }
102
+
103
+ const plugins = scanPlugins();
104
+ const plugin = plugins.find(p => p.name === req.params.name);
105
+ if (!plugin) {
106
+ return res.status(404).json({ error: 'Plugin not found' });
107
+ }
108
+
109
+ const config = getPluginsConfig();
110
+ config[req.params.name] = { ...config[req.params.name], enabled };
111
+ savePluginsConfig(config);
112
+
113
+ // Start or stop the plugin server as needed
114
+ if (plugin.server) {
115
+ if (enabled && !isPluginRunning(plugin.name)) {
116
+ const pluginDir = getPluginDir(plugin.name);
117
+ if (pluginDir) {
118
+ try {
119
+ await startPluginServer(plugin.name, pluginDir, plugin.server);
120
+ } catch (err) {
121
+ console.error(`[Plugins] Failed to start server for "${plugin.name}":`, err.message);
122
+ }
123
+ }
124
+ } else if (!enabled && isPluginRunning(plugin.name)) {
125
+ await stopPluginServer(plugin.name);
126
+ }
127
+ }
128
+
129
+ res.json({ success: true, name: req.params.name, enabled });
130
+ } catch (err) {
131
+ res.status(500).json({ error: 'Failed to update plugin', details: err.message });
132
+ }
133
+ });
134
+
135
+ // POST /install — Install plugin from git URL
136
+ router.post('/install', async (req, res) => {
137
+ try {
138
+ const { url } = req.body;
139
+ if (!url || typeof url !== 'string') {
140
+ return res.status(400).json({ error: '"url" is required and must be a string' });
141
+ }
142
+
143
+ // Basic URL validation
144
+ if (!url.startsWith('https://') && !url.startsWith('git@')) {
145
+ return res.status(400).json({ error: 'URL must start with https:// or git@' });
146
+ }
147
+
148
+ const manifest = await installPluginFromGit(url);
149
+
150
+ // Auto-start the server if the plugin has one (enabled by default)
151
+ if (manifest.server) {
152
+ const pluginDir = getPluginDir(manifest.name);
153
+ if (pluginDir) {
154
+ try {
155
+ await startPluginServer(manifest.name, pluginDir, manifest.server);
156
+ } catch (err) {
157
+ console.error(`[Plugins] Failed to start server for "${manifest.name}":`, err.message);
158
+ }
159
+ }
160
+ }
161
+
162
+ res.json({ success: true, plugin: manifest });
163
+ } catch (err) {
164
+ res.status(400).json({ error: 'Failed to install plugin', details: err.message });
165
+ }
166
+ });
167
+
168
+ // POST /:name/update — Pull latest from git (restarts server if running)
169
+ router.post('/:name/update', async (req, res) => {
170
+ try {
171
+ const pluginName = req.params.name;
172
+
173
+ if (!/^[a-zA-Z0-9_-]+$/.test(pluginName)) {
174
+ return res.status(400).json({ error: 'Invalid plugin name' });
175
+ }
176
+
177
+ const wasRunning = isPluginRunning(pluginName);
178
+ if (wasRunning) {
179
+ await stopPluginServer(pluginName);
180
+ }
181
+
182
+ const manifest = await updatePluginFromGit(pluginName);
183
+
184
+ // Restart server if it was running before the update
185
+ if (wasRunning && manifest.server) {
186
+ const pluginDir = getPluginDir(pluginName);
187
+ if (pluginDir) {
188
+ try {
189
+ await startPluginServer(pluginName, pluginDir, manifest.server);
190
+ } catch (err) {
191
+ console.error(`[Plugins] Failed to restart server for "${pluginName}":`, err.message);
192
+ }
193
+ }
194
+ }
195
+
196
+ res.json({ success: true, plugin: manifest });
197
+ } catch (err) {
198
+ res.status(400).json({ error: 'Failed to update plugin', details: err.message });
199
+ }
200
+ });
201
+
202
+ // ALL /:name/rpc/* — Proxy requests to plugin's server subprocess
203
+ router.all('/:name/rpc/*', async (req, res) => {
204
+ const pluginName = req.params.name;
205
+ const rpcPath = req.params[0] || '';
206
+
207
+ if (!/^[a-zA-Z0-9_-]+$/.test(pluginName)) {
208
+ return res.status(400).json({ error: 'Invalid plugin name' });
209
+ }
210
+
211
+ let port = getPluginPort(pluginName);
212
+ if (!port) {
213
+ // Lazily start the plugin server if it exists and is enabled
214
+ const plugins = scanPlugins();
215
+ const plugin = plugins.find(p => p.name === pluginName);
216
+ if (!plugin || !plugin.server) {
217
+ return res.status(503).json({ error: 'Plugin server is not running' });
218
+ }
219
+ if (!plugin.enabled) {
220
+ return res.status(503).json({ error: 'Plugin is disabled' });
221
+ }
222
+ const pluginDir = path.join(getPluginsDir(), plugin.dirName);
223
+ try {
224
+ port = await startPluginServer(pluginName, pluginDir, plugin.server);
225
+ } catch (err) {
226
+ return res.status(503).json({ error: 'Plugin server failed to start', details: err.message });
227
+ }
228
+ }
229
+
230
+ // Inject configured secrets as headers
231
+ const config = getPluginsConfig();
232
+ const pluginConfig = config[pluginName] || {};
233
+ const secrets = pluginConfig.secrets || {};
234
+
235
+ const headers = {
236
+ 'content-type': req.headers['content-type'] || 'application/json',
237
+ };
238
+
239
+ // Add per-plugin secrets as X-Plugin-Secret-* headers
240
+ for (const [key, value] of Object.entries(secrets)) {
241
+ headers[`x-plugin-secret-${key.toLowerCase()}`] = String(value);
242
+ }
243
+
244
+ // Reconstruct query string
245
+ const qs = req.url.includes('?') ? '?' + req.url.split('?').slice(1).join('?') : '';
246
+
247
+ const options = {
248
+ hostname: '127.0.0.1',
249
+ port,
250
+ path: `/${rpcPath}${qs}`,
251
+ method: req.method,
252
+ headers,
253
+ };
254
+
255
+ const proxyReq = http.request(options, (proxyRes) => {
256
+ res.writeHead(proxyRes.statusCode, proxyRes.headers);
257
+ proxyRes.pipe(res);
258
+ });
259
+
260
+ proxyReq.on('error', (err) => {
261
+ if (!res.headersSent) {
262
+ res.status(502).json({ error: 'Plugin server error', details: err.message });
263
+ } else {
264
+ res.end();
265
+ }
266
+ });
267
+
268
+ // Forward body (already parsed by express JSON middleware, so re-stringify).
269
+ // Check content-length to detect whether a body was actually sent, since
270
+ // req.body can be falsy for valid payloads like 0, false, null, or {}.
271
+ const hasBody = req.headers['content-length'] && parseInt(req.headers['content-length'], 10) > 0;
272
+ if (hasBody && req.body !== undefined) {
273
+ const bodyStr = JSON.stringify(req.body);
274
+ proxyReq.setHeader('content-length', Buffer.byteLength(bodyStr));
275
+ proxyReq.write(bodyStr);
276
+ }
277
+
278
+ proxyReq.end();
279
+ });
280
+
281
+ // DELETE /:name — Uninstall plugin (stops server first)
282
+ router.delete('/:name', async (req, res) => {
283
+ try {
284
+ const pluginName = req.params.name;
285
+
286
+ // Validate name format to prevent path traversal
287
+ if (!/^[a-zA-Z0-9_-]+$/.test(pluginName)) {
288
+ return res.status(400).json({ error: 'Invalid plugin name' });
289
+ }
290
+
291
+ // Stop server and wait for the process to fully exit before deleting files
292
+ if (isPluginRunning(pluginName)) {
293
+ await stopPluginServer(pluginName);
294
+ }
295
+
296
+ await uninstallPlugin(pluginName);
297
+ res.json({ success: true, name: pluginName });
298
+ } catch (err) {
299
+ res.status(400).json({ error: 'Failed to uninstall plugin', details: err.message });
300
+ }
301
+ });
302
+
303
+ export default router;