@siteboon/claude-code-ui 1.23.2 → 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.
@@ -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;
@@ -311,13 +311,11 @@ router.post('/create-workspace', async (req, res) => {
311
311
  * Helper function to get GitHub token from database
312
312
  */
313
313
  async function getGithubTokenById(tokenId, userId) {
314
- const { getDatabase } = await import('../database/db.js');
315
- const db = await getDatabase();
314
+ const { db } = await import('../database/db.js');
316
315
 
317
- const credential = await db.get(
318
- 'SELECT * FROM user_credentials WHERE id = ? AND user_id = ? AND credential_type = ? AND is_active = 1',
319
- [tokenId, userId, 'github_token']
320
- );
316
+ const credential = db.prepare(
317
+ 'SELECT * FROM user_credentials WHERE id = ? AND user_id = ? AND credential_type = ? AND is_active = 1'
318
+ ).get(tokenId, userId, 'github_token');
321
319
 
322
320
  // Return in the expected format (github_token field for compatibility)
323
321
  if (credential) {
@@ -2,12 +2,29 @@ import express from 'express';
2
2
  import { userDb } from '../database/db.js';
3
3
  import { authenticateToken } from '../middleware/auth.js';
4
4
  import { getSystemGitConfig } from '../utils/gitConfig.js';
5
- import { exec } from 'child_process';
6
- import { promisify } from 'util';
5
+ import { spawn } from 'child_process';
7
6
 
8
- const execAsync = promisify(exec);
9
7
  const router = express.Router();
10
8
 
9
+ function spawnAsync(command, args, options = {}) {
10
+ return new Promise((resolve, reject) => {
11
+ const child = spawn(command, args, { ...options, shell: false });
12
+ let stdout = '';
13
+ let stderr = '';
14
+ child.stdout.on('data', (data) => { stdout += data.toString(); });
15
+ child.stderr.on('data', (data) => { stderr += data.toString(); });
16
+ child.on('error', (error) => { reject(error); });
17
+ child.on('close', (code) => {
18
+ if (code === 0) { resolve({ stdout, stderr }); return; }
19
+ const error = new Error(`Command failed: ${command} ${args.join(' ')}`);
20
+ error.code = code;
21
+ error.stdout = stdout;
22
+ error.stderr = stderr;
23
+ reject(error);
24
+ });
25
+ });
26
+ }
27
+
11
28
  router.get('/git-config', authenticateToken, async (req, res) => {
12
29
  try {
13
30
  const userId = req.user.id;
@@ -55,8 +72,8 @@ router.post('/git-config', authenticateToken, async (req, res) => {
55
72
  userDb.updateGitConfig(userId, gitName, gitEmail);
56
73
 
57
74
  try {
58
- await execAsync(`git config --global user.name "${gitName.replace(/"/g, '\\"')}"`);
59
- await execAsync(`git config --global user.email "${gitEmail.replace(/"/g, '\\"')}"`);
75
+ await spawnAsync('git', ['config', '--global', 'user.name', gitName]);
76
+ await spawnAsync('git', ['config', '--global', 'user.email', gitEmail]);
60
77
  console.log(`Applied git config globally: ${gitName} <${gitEmail}>`);
61
78
  } catch (gitError) {
62
79
  console.error('Error applying git config:', gitError);
@@ -1,7 +1,17 @@
1
- import { exec } from 'child_process';
2
- import { promisify } from 'util';
1
+ import { spawn } from 'child_process';
3
2
 
4
- const execAsync = promisify(exec);
3
+ function spawnAsync(command, args) {
4
+ return new Promise((resolve, reject) => {
5
+ const child = spawn(command, args, { shell: false });
6
+ let stdout = '';
7
+ child.stdout.on('data', (data) => { stdout += data.toString(); });
8
+ child.on('error', (error) => { reject(error); });
9
+ child.on('close', (code) => {
10
+ if (code === 0) { resolve({ stdout }); return; }
11
+ reject(new Error(`Command failed with code ${code}`));
12
+ });
13
+ });
14
+ }
5
15
 
6
16
  /**
7
17
  * Read git configuration from system's global git config
@@ -10,8 +20,8 @@ const execAsync = promisify(exec);
10
20
  export async function getSystemGitConfig() {
11
21
  try {
12
22
  const [nameResult, emailResult] = await Promise.all([
13
- execAsync('git config --global user.name').catch(() => ({ stdout: '' })),
14
- execAsync('git config --global user.email').catch(() => ({ stdout: '' }))
23
+ spawnAsync('git', ['config', '--global', 'user.name']).catch(() => ({ stdout: '' })),
24
+ spawnAsync('git', ['config', '--global', 'user.email']).catch(() => ({ stdout: '' }))
15
25
  ]);
16
26
 
17
27
  return {