@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,408 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { spawn } from 'child_process';
5
+
6
+ const PLUGINS_DIR = path.join(os.homedir(), '.claude-code-ui', 'plugins');
7
+ const PLUGINS_CONFIG_PATH = path.join(os.homedir(), '.claude-code-ui', 'plugins.json');
8
+
9
+ const REQUIRED_MANIFEST_FIELDS = ['name', 'displayName', 'entry'];
10
+
11
+ /** Strip embedded credentials from a repo URL before exposing it to the client. */
12
+ function sanitizeRepoUrl(raw) {
13
+ try {
14
+ const u = new URL(raw);
15
+ u.username = '';
16
+ u.password = '';
17
+ return u.toString().replace(/\/$/, '');
18
+ } catch {
19
+ // Not a parseable URL (e.g. SSH shorthand) — strip user:pass@ segment
20
+ return raw.replace(/\/\/[^@/]+@/, '//');
21
+ }
22
+ }
23
+ const ALLOWED_TYPES = ['react', 'module'];
24
+ const ALLOWED_SLOTS = ['tab'];
25
+
26
+ export function getPluginsDir() {
27
+ if (!fs.existsSync(PLUGINS_DIR)) {
28
+ fs.mkdirSync(PLUGINS_DIR, { recursive: true });
29
+ }
30
+ return PLUGINS_DIR;
31
+ }
32
+
33
+ export function getPluginsConfig() {
34
+ try {
35
+ if (fs.existsSync(PLUGINS_CONFIG_PATH)) {
36
+ return JSON.parse(fs.readFileSync(PLUGINS_CONFIG_PATH, 'utf-8'));
37
+ }
38
+ } catch {
39
+ // Corrupted config, start fresh
40
+ }
41
+ return {};
42
+ }
43
+
44
+ export function savePluginsConfig(config) {
45
+ const dir = path.dirname(PLUGINS_CONFIG_PATH);
46
+ if (!fs.existsSync(dir)) {
47
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
48
+ }
49
+ fs.writeFileSync(PLUGINS_CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });
50
+ }
51
+
52
+ export function validateManifest(manifest) {
53
+ if (!manifest || typeof manifest !== 'object') {
54
+ return { valid: false, error: 'Manifest must be a JSON object' };
55
+ }
56
+
57
+ for (const field of REQUIRED_MANIFEST_FIELDS) {
58
+ if (!manifest[field] || typeof manifest[field] !== 'string') {
59
+ return { valid: false, error: `Missing or invalid required field: ${field}` };
60
+ }
61
+ }
62
+
63
+ // Sanitize name — only allow alphanumeric, hyphens, underscores
64
+ if (!/^[a-zA-Z0-9_-]+$/.test(manifest.name)) {
65
+ return { valid: false, error: 'Plugin name must only contain letters, numbers, hyphens, and underscores' };
66
+ }
67
+
68
+ if (manifest.type && !ALLOWED_TYPES.includes(manifest.type)) {
69
+ return { valid: false, error: `Invalid plugin type: ${manifest.type}. Must be one of: ${ALLOWED_TYPES.join(', ')}` };
70
+ }
71
+
72
+ if (manifest.slot && !ALLOWED_SLOTS.includes(manifest.slot)) {
73
+ return { valid: false, error: `Invalid plugin slot: ${manifest.slot}. Must be one of: ${ALLOWED_SLOTS.join(', ')}` };
74
+ }
75
+
76
+ // Validate entry is a relative path without traversal
77
+ if (manifest.entry.includes('..') || path.isAbsolute(manifest.entry)) {
78
+ return { valid: false, error: 'Entry must be a relative path without ".."' };
79
+ }
80
+
81
+ if (manifest.server !== undefined && manifest.server !== null) {
82
+ if (typeof manifest.server !== 'string' || manifest.server.includes('..') || path.isAbsolute(manifest.server)) {
83
+ return { valid: false, error: 'Server entry must be a relative path string without ".."' };
84
+ }
85
+ }
86
+
87
+ if (manifest.permissions !== undefined) {
88
+ if (!Array.isArray(manifest.permissions) || !manifest.permissions.every(p => typeof p === 'string')) {
89
+ return { valid: false, error: 'Permissions must be an array of strings' };
90
+ }
91
+ }
92
+
93
+ return { valid: true };
94
+ }
95
+
96
+ export function scanPlugins() {
97
+ const pluginsDir = getPluginsDir();
98
+ const config = getPluginsConfig();
99
+ const plugins = [];
100
+
101
+ let entries;
102
+ try {
103
+ entries = fs.readdirSync(pluginsDir, { withFileTypes: true });
104
+ } catch {
105
+ return plugins;
106
+ }
107
+
108
+ const seenNames = new Set();
109
+
110
+ for (const entry of entries) {
111
+ if (!entry.isDirectory()) continue;
112
+ // Skip transient temp directories from in-progress installs
113
+ if (entry.name.startsWith('.tmp-')) continue;
114
+
115
+ const manifestPath = path.join(pluginsDir, entry.name, 'manifest.json');
116
+ if (!fs.existsSync(manifestPath)) continue;
117
+
118
+ try {
119
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
120
+ const validation = validateManifest(manifest);
121
+ if (!validation.valid) {
122
+ console.warn(`[Plugins] Skipping ${entry.name}: ${validation.error}`);
123
+ continue;
124
+ }
125
+
126
+ // Skip duplicate manifest names
127
+ if (seenNames.has(manifest.name)) {
128
+ console.warn(`[Plugins] Skipping ${entry.name}: duplicate plugin name "${manifest.name}"`);
129
+ continue;
130
+ }
131
+ seenNames.add(manifest.name);
132
+
133
+ // Try to read git remote URL
134
+ let repoUrl = null;
135
+ try {
136
+ const gitConfigPath = path.join(pluginsDir, entry.name, '.git', 'config');
137
+ if (fs.existsSync(gitConfigPath)) {
138
+ const gitConfig = fs.readFileSync(gitConfigPath, 'utf-8');
139
+ const match = gitConfig.match(/url\s*=\s*(.+)/);
140
+ if (match) {
141
+ repoUrl = match[1].trim().replace(/\.git$/, '');
142
+ // Convert SSH URLs to HTTPS
143
+ if (repoUrl.startsWith('git@')) {
144
+ repoUrl = repoUrl.replace(/^git@([^:]+):/, 'https://$1/');
145
+ }
146
+ // Strip embedded credentials (e.g. https://user:pass@host/...)
147
+ repoUrl = sanitizeRepoUrl(repoUrl);
148
+ }
149
+ }
150
+ } catch { /* ignore */ }
151
+
152
+ plugins.push({
153
+ name: manifest.name,
154
+ displayName: manifest.displayName,
155
+ version: manifest.version || '0.0.0',
156
+ description: manifest.description || '',
157
+ author: manifest.author || '',
158
+ icon: manifest.icon || 'Puzzle',
159
+ type: manifest.type || 'module',
160
+ slot: manifest.slot || 'tab',
161
+ entry: manifest.entry,
162
+ server: manifest.server || null,
163
+ permissions: manifest.permissions || [],
164
+ enabled: config[manifest.name]?.enabled !== false, // enabled by default
165
+ dirName: entry.name,
166
+ repoUrl,
167
+ });
168
+ } catch (err) {
169
+ console.warn(`[Plugins] Failed to read manifest for ${entry.name}:`, err.message);
170
+ }
171
+ }
172
+
173
+ return plugins;
174
+ }
175
+
176
+ export function getPluginDir(name) {
177
+ const plugins = scanPlugins();
178
+ const plugin = plugins.find(p => p.name === name);
179
+ if (!plugin) return null;
180
+ return path.join(getPluginsDir(), plugin.dirName);
181
+ }
182
+
183
+ export function resolvePluginAssetPath(name, assetPath) {
184
+ const pluginDir = getPluginDir(name);
185
+ if (!pluginDir) return null;
186
+
187
+ const resolved = path.resolve(pluginDir, assetPath);
188
+
189
+ // Prevent path traversal — canonicalize via realpath to defeat symlink bypasses
190
+ if (!fs.existsSync(resolved)) return null;
191
+
192
+ const realResolved = fs.realpathSync(resolved);
193
+ const realPluginDir = fs.realpathSync(pluginDir);
194
+ if (!realResolved.startsWith(realPluginDir + path.sep) && realResolved !== realPluginDir) {
195
+ return null;
196
+ }
197
+
198
+ return realResolved;
199
+ }
200
+
201
+ export function installPluginFromGit(url) {
202
+ return new Promise((resolve, reject) => {
203
+ if (typeof url !== 'string' || !url.trim()) {
204
+ return reject(new Error('Invalid URL: must be a non-empty string'));
205
+ }
206
+ if (url.startsWith('-')) {
207
+ return reject(new Error('Invalid URL: must not start with "-"'));
208
+ }
209
+
210
+ // Extract repo name from URL for directory name
211
+ const urlClean = url.replace(/\.git$/, '').replace(/\/$/, '');
212
+ const repoName = urlClean.split('/').pop();
213
+
214
+ if (!repoName || !/^[a-zA-Z0-9_.-]+$/.test(repoName)) {
215
+ return reject(new Error('Could not determine a valid directory name from the URL'));
216
+ }
217
+
218
+ const pluginsDir = getPluginsDir();
219
+ const targetDir = path.resolve(pluginsDir, repoName);
220
+
221
+ // Ensure the resolved target directory stays within the plugins directory
222
+ if (!targetDir.startsWith(pluginsDir + path.sep)) {
223
+ return reject(new Error('Invalid plugin directory path'));
224
+ }
225
+
226
+ if (fs.existsSync(targetDir)) {
227
+ return reject(new Error(`Plugin directory "${repoName}" already exists`));
228
+ }
229
+
230
+ // Clone into a temp directory so scanPlugins() never sees a partially-installed plugin
231
+ const tempDir = fs.mkdtempSync(path.join(pluginsDir, `.tmp-${repoName}-`));
232
+
233
+ const cleanupTemp = () => {
234
+ try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch {}
235
+ };
236
+
237
+ const finalize = (manifest) => {
238
+ try {
239
+ fs.renameSync(tempDir, targetDir);
240
+ } catch (err) {
241
+ cleanupTemp();
242
+ return reject(new Error(`Failed to move plugin into place: ${err.message}`));
243
+ }
244
+ resolve(manifest);
245
+ };
246
+
247
+ const gitProcess = spawn('git', ['clone', '--depth', '1', '--', url, tempDir], {
248
+ stdio: ['ignore', 'pipe', 'pipe'],
249
+ });
250
+
251
+ let stderr = '';
252
+ gitProcess.stderr.on('data', (data) => { stderr += data.toString(); });
253
+
254
+ gitProcess.on('close', (code) => {
255
+ if (code !== 0) {
256
+ cleanupTemp();
257
+ return reject(new Error(`git clone failed (exit code ${code}): ${stderr.trim()}`));
258
+ }
259
+
260
+ // Validate manifest exists
261
+ const manifestPath = path.join(tempDir, 'manifest.json');
262
+ if (!fs.existsSync(manifestPath)) {
263
+ cleanupTemp();
264
+ return reject(new Error('Cloned repository does not contain a manifest.json'));
265
+ }
266
+
267
+ let manifest;
268
+ try {
269
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
270
+ } catch {
271
+ cleanupTemp();
272
+ return reject(new Error('manifest.json is not valid JSON'));
273
+ }
274
+
275
+ const validation = validateManifest(manifest);
276
+ if (!validation.valid) {
277
+ cleanupTemp();
278
+ return reject(new Error(`Invalid manifest: ${validation.error}`));
279
+ }
280
+
281
+ // Reject if another installed plugin already uses this name
282
+ const existing = scanPlugins().find(p => p.name === manifest.name);
283
+ if (existing) {
284
+ cleanupTemp();
285
+ return reject(new Error(`A plugin named "${manifest.name}" is already installed (in "${existing.dirName}")`));
286
+ }
287
+
288
+ // Run npm install if package.json exists.
289
+ // --ignore-scripts prevents postinstall hooks from executing arbitrary code.
290
+ const packageJsonPath = path.join(tempDir, 'package.json');
291
+ if (fs.existsSync(packageJsonPath)) {
292
+ const npmProcess = spawn('npm', ['install', '--production', '--ignore-scripts'], {
293
+ cwd: tempDir,
294
+ stdio: ['ignore', 'pipe', 'pipe'],
295
+ });
296
+
297
+ npmProcess.on('close', (npmCode) => {
298
+ if (npmCode !== 0) {
299
+ cleanupTemp();
300
+ return reject(new Error(`npm install for ${repoName} failed (exit code ${npmCode})`));
301
+ }
302
+ finalize(manifest);
303
+ });
304
+
305
+ npmProcess.on('error', (err) => {
306
+ cleanupTemp();
307
+ reject(err);
308
+ });
309
+ } else {
310
+ finalize(manifest);
311
+ }
312
+ });
313
+
314
+ gitProcess.on('error', (err) => {
315
+ cleanupTemp();
316
+ reject(new Error(`Failed to spawn git: ${err.message}`));
317
+ });
318
+ });
319
+ }
320
+
321
+ export function updatePluginFromGit(name) {
322
+ return new Promise((resolve, reject) => {
323
+ const pluginDir = getPluginDir(name);
324
+ if (!pluginDir) {
325
+ return reject(new Error(`Plugin "${name}" not found`));
326
+ }
327
+
328
+ // Only fast-forward to avoid silent divergence
329
+ const gitProcess = spawn('git', ['pull', '--ff-only', '--'], {
330
+ cwd: pluginDir,
331
+ stdio: ['ignore', 'pipe', 'pipe'],
332
+ });
333
+
334
+ let stderr = '';
335
+ gitProcess.stderr.on('data', (data) => { stderr += data.toString(); });
336
+
337
+ gitProcess.on('close', (code) => {
338
+ if (code !== 0) {
339
+ return reject(new Error(`git pull failed (exit code ${code}): ${stderr.trim()}`));
340
+ }
341
+
342
+ // Re-validate manifest after update
343
+ const manifestPath = path.join(pluginDir, 'manifest.json');
344
+ let manifest;
345
+ try {
346
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
347
+ } catch {
348
+ return reject(new Error('manifest.json is not valid JSON after update'));
349
+ }
350
+
351
+ const validation = validateManifest(manifest);
352
+ if (!validation.valid) {
353
+ return reject(new Error(`Invalid manifest after update: ${validation.error}`));
354
+ }
355
+
356
+ // Re-run npm install if package.json exists
357
+ const packageJsonPath = path.join(pluginDir, 'package.json');
358
+ if (fs.existsSync(packageJsonPath)) {
359
+ const npmProcess = spawn('npm', ['install', '--production', '--ignore-scripts'], {
360
+ cwd: pluginDir,
361
+ stdio: ['ignore', 'pipe', 'pipe'],
362
+ });
363
+ npmProcess.on('close', (npmCode) => {
364
+ if (npmCode !== 0) {
365
+ return reject(new Error(`npm install for ${name} failed (exit code ${npmCode})`));
366
+ }
367
+ resolve(manifest);
368
+ });
369
+ npmProcess.on('error', (err) => reject(err));
370
+ } else {
371
+ resolve(manifest);
372
+ }
373
+ });
374
+
375
+ gitProcess.on('error', (err) => {
376
+ reject(new Error(`Failed to spawn git: ${err.message}`));
377
+ });
378
+ });
379
+ }
380
+
381
+ export async function uninstallPlugin(name) {
382
+ const pluginDir = getPluginDir(name);
383
+ if (!pluginDir) {
384
+ throw new Error(`Plugin "${name}" not found`);
385
+ }
386
+
387
+ // On Windows, file handles may be released slightly after process exit.
388
+ // Retry a few times with a short delay before giving up.
389
+ const MAX_RETRIES = 5;
390
+ const RETRY_DELAY_MS = 500;
391
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
392
+ try {
393
+ fs.rmSync(pluginDir, { recursive: true, force: true });
394
+ break;
395
+ } catch (err) {
396
+ if (err.code === 'EBUSY' && attempt < MAX_RETRIES) {
397
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
398
+ } else {
399
+ throw err;
400
+ }
401
+ }
402
+ }
403
+
404
+ // Remove from config
405
+ const config = getPluginsConfig();
406
+ delete config[name];
407
+ savePluginsConfig(config);
408
+ }
@@ -0,0 +1,184 @@
1
+ import { spawn } from 'child_process';
2
+ import path from 'path';
3
+ import { scanPlugins, getPluginsConfig, getPluginDir } from './plugin-loader.js';
4
+
5
+ // Map<pluginName, { process, port }>
6
+ const runningPlugins = new Map();
7
+ // Map<pluginName, Promise<port>> — in-flight start operations
8
+ const startingPlugins = new Map();
9
+
10
+ /**
11
+ * Start a plugin's server subprocess.
12
+ * The plugin's server entry must print a JSON line with { ready: true, port: <number> }
13
+ * to stdout within 10 seconds.
14
+ */
15
+ export function startPluginServer(name, pluginDir, serverEntry) {
16
+ if (runningPlugins.has(name)) {
17
+ return Promise.resolve(runningPlugins.get(name).port);
18
+ }
19
+
20
+ // Coalesce concurrent starts for the same plugin
21
+ if (startingPlugins.has(name)) {
22
+ return startingPlugins.get(name);
23
+ }
24
+
25
+ const startPromise = new Promise((resolve, reject) => {
26
+
27
+ const serverPath = path.join(pluginDir, serverEntry);
28
+
29
+ // Restricted env — only essentials, no host secrets
30
+ const pluginProcess = spawn('node', [serverPath], {
31
+ cwd: pluginDir,
32
+ env: {
33
+ PATH: process.env.PATH,
34
+ HOME: process.env.HOME,
35
+ NODE_ENV: process.env.NODE_ENV || 'production',
36
+ PLUGIN_NAME: name,
37
+ },
38
+ stdio: ['ignore', 'pipe', 'pipe'],
39
+ });
40
+
41
+ let resolved = false;
42
+ let stdout = '';
43
+
44
+ const timeout = setTimeout(() => {
45
+ if (!resolved) {
46
+ resolved = true;
47
+ pluginProcess.kill();
48
+ reject(new Error('Plugin server did not report ready within 10 seconds'));
49
+ }
50
+ }, 10000);
51
+
52
+ pluginProcess.stdout.on('data', (data) => {
53
+ if (resolved) return;
54
+ stdout += data.toString();
55
+
56
+ // Look for the JSON ready line
57
+ const lines = stdout.split('\n');
58
+ for (const line of lines) {
59
+ try {
60
+ const msg = JSON.parse(line.trim());
61
+ if (msg.ready && typeof msg.port === 'number') {
62
+ clearTimeout(timeout);
63
+ resolved = true;
64
+ runningPlugins.set(name, { process: pluginProcess, port: msg.port });
65
+
66
+ pluginProcess.on('exit', () => {
67
+ runningPlugins.delete(name);
68
+ });
69
+
70
+ console.log(`[Plugins] Server started for "${name}" on port ${msg.port}`);
71
+ resolve(msg.port);
72
+ }
73
+ } catch {
74
+ // Not JSON yet, keep buffering
75
+ }
76
+ }
77
+ });
78
+
79
+ pluginProcess.stderr.on('data', (data) => {
80
+ console.warn(`[Plugin:${name}] ${data.toString().trim()}`);
81
+ });
82
+
83
+ pluginProcess.on('error', (err) => {
84
+ clearTimeout(timeout);
85
+ if (!resolved) {
86
+ resolved = true;
87
+ reject(new Error(`Failed to start plugin server: ${err.message}`));
88
+ }
89
+ });
90
+
91
+ pluginProcess.on('exit', (code) => {
92
+ clearTimeout(timeout);
93
+ runningPlugins.delete(name);
94
+ if (!resolved) {
95
+ resolved = true;
96
+ reject(new Error(`Plugin server exited with code ${code} before reporting ready`));
97
+ }
98
+ });
99
+ }).finally(() => {
100
+ startingPlugins.delete(name);
101
+ });
102
+
103
+ startingPlugins.set(name, startPromise);
104
+ return startPromise;
105
+ }
106
+
107
+ /**
108
+ * Stop a plugin's server subprocess.
109
+ * Returns a Promise that resolves when the process has fully exited.
110
+ */
111
+ export function stopPluginServer(name) {
112
+ const entry = runningPlugins.get(name);
113
+ if (!entry) return Promise.resolve();
114
+
115
+ return new Promise((resolve) => {
116
+ const cleanup = () => {
117
+ clearTimeout(forceKillTimer);
118
+ runningPlugins.delete(name);
119
+ resolve();
120
+ };
121
+
122
+ entry.process.once('exit', cleanup);
123
+
124
+ entry.process.kill('SIGTERM');
125
+
126
+ // Force kill after 5 seconds if still running
127
+ const forceKillTimer = setTimeout(() => {
128
+ if (runningPlugins.has(name)) {
129
+ entry.process.kill('SIGKILL');
130
+ cleanup();
131
+ }
132
+ }, 5000);
133
+
134
+ console.log(`[Plugins] Server stopped for "${name}"`);
135
+ });
136
+ }
137
+
138
+ /**
139
+ * Get the port a running plugin server is listening on.
140
+ */
141
+ export function getPluginPort(name) {
142
+ return runningPlugins.get(name)?.port ?? null;
143
+ }
144
+
145
+ /**
146
+ * Check if a plugin's server is running.
147
+ */
148
+ export function isPluginRunning(name) {
149
+ return runningPlugins.has(name);
150
+ }
151
+
152
+ /**
153
+ * Stop all running plugin servers (called on host shutdown).
154
+ */
155
+ export function stopAllPlugins() {
156
+ const stops = [];
157
+ for (const [name] of runningPlugins) {
158
+ stops.push(stopPluginServer(name));
159
+ }
160
+ return Promise.all(stops);
161
+ }
162
+
163
+ /**
164
+ * Start servers for all enabled plugins that have a server entry.
165
+ * Called once on host server boot.
166
+ */
167
+ export async function startEnabledPluginServers() {
168
+ const plugins = scanPlugins();
169
+ const config = getPluginsConfig();
170
+
171
+ for (const plugin of plugins) {
172
+ if (!plugin.server) continue;
173
+ if (config[plugin.name]?.enabled === false) continue;
174
+
175
+ const pluginDir = getPluginDir(plugin.name);
176
+ if (!pluginDir) continue;
177
+
178
+ try {
179
+ await startPluginServer(plugin.name, pluginDir, plugin.server);
180
+ } catch (err) {
181
+ console.error(`[Plugins] Failed to start server for "${plugin.name}":`, err.message);
182
+ }
183
+ }
184
+ }