@siteboon/claude-code-ui 1.8.12 → 1.9.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 matter from 'gray-matter';
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import { execFile } from 'child_process';
5
+ import { promisify } from 'util';
6
+ import { parse as parseShellCommand } from 'shell-quote';
7
+
8
+ const execFileAsync = promisify(execFile);
9
+
10
+ // Configuration
11
+ const MAX_INCLUDE_DEPTH = 3;
12
+ const BASH_TIMEOUT = 30000; // 30 seconds
13
+ const BASH_COMMAND_ALLOWLIST = [
14
+ 'echo',
15
+ 'ls',
16
+ 'pwd',
17
+ 'date',
18
+ 'whoami',
19
+ 'git',
20
+ 'npm',
21
+ 'node',
22
+ 'cat',
23
+ 'grep',
24
+ 'find',
25
+ 'task-master'
26
+ ];
27
+
28
+ /**
29
+ * Parse a markdown command file and extract frontmatter and content
30
+ * @param {string} content - Raw markdown content
31
+ * @returns {object} Parsed command with data (frontmatter) and content
32
+ */
33
+ export function parseCommand(content) {
34
+ try {
35
+ const parsed = matter(content);
36
+ return {
37
+ data: parsed.data || {},
38
+ content: parsed.content || '',
39
+ raw: content
40
+ };
41
+ } catch (error) {
42
+ throw new Error(`Failed to parse command: ${error.message}`);
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Replace argument placeholders in content
48
+ * @param {string} content - Content with placeholders
49
+ * @param {string|array} args - Arguments to replace (string or array)
50
+ * @returns {string} Content with replaced arguments
51
+ */
52
+ export function replaceArguments(content, args) {
53
+ if (!content) return content;
54
+
55
+ let result = content;
56
+
57
+ // Convert args to array if it's a string
58
+ const argsArray = Array.isArray(args) ? args : (args ? [args] : []);
59
+
60
+ // Replace $ARGUMENTS with all arguments joined by space
61
+ const allArgs = argsArray.join(' ');
62
+ result = result.replace(/\$ARGUMENTS/g, allArgs);
63
+
64
+ // Replace positional arguments $1-$9
65
+ for (let i = 1; i <= 9; i++) {
66
+ const regex = new RegExp(`\\$${i}`, 'g');
67
+ const value = argsArray[i - 1] || '';
68
+ result = result.replace(regex, value);
69
+ }
70
+
71
+ return result;
72
+ }
73
+
74
+ /**
75
+ * Validate file path to prevent directory traversal
76
+ * @param {string} filePath - Path to validate
77
+ * @param {string} basePath - Base directory path
78
+ * @returns {boolean} True if path is safe
79
+ */
80
+ export function isPathSafe(filePath, basePath) {
81
+ const resolvedPath = path.resolve(basePath, filePath);
82
+ const resolvedBase = path.resolve(basePath);
83
+ const relative = path.relative(resolvedBase, resolvedPath);
84
+ return (
85
+ relative !== '' &&
86
+ !relative.startsWith('..') &&
87
+ !path.isAbsolute(relative)
88
+ );
89
+ }
90
+
91
+ /**
92
+ * Process file includes in content (@filename syntax)
93
+ * @param {string} content - Content with @filename includes
94
+ * @param {string} basePath - Base directory for resolving file paths
95
+ * @param {number} depth - Current recursion depth
96
+ * @returns {Promise<string>} Content with includes resolved
97
+ */
98
+ export async function processFileIncludes(content, basePath, depth = 0) {
99
+ if (!content) return content;
100
+
101
+ // Prevent infinite recursion
102
+ if (depth >= MAX_INCLUDE_DEPTH) {
103
+ throw new Error(`Maximum include depth (${MAX_INCLUDE_DEPTH}) exceeded`);
104
+ }
105
+
106
+ // Match @filename patterns (at start of line or after whitespace)
107
+ const includePattern = /(?:^|\s)@([^\s]+)/gm;
108
+ const matches = [...content.matchAll(includePattern)];
109
+
110
+ if (matches.length === 0) {
111
+ return content;
112
+ }
113
+
114
+ let result = content;
115
+
116
+ for (const match of matches) {
117
+ const fullMatch = match[0];
118
+ const filename = match[1];
119
+
120
+ // Security: prevent directory traversal
121
+ if (!isPathSafe(filename, basePath)) {
122
+ throw new Error(`Invalid file path (directory traversal detected): ${filename}`);
123
+ }
124
+
125
+ try {
126
+ const filePath = path.resolve(basePath, filename);
127
+ const fileContent = await fs.readFile(filePath, 'utf-8');
128
+
129
+ // Recursively process includes in the included file
130
+ const processedContent = await processFileIncludes(fileContent, basePath, depth + 1);
131
+
132
+ // Replace the @filename with the file content
133
+ result = result.replace(fullMatch, fullMatch.startsWith(' ') ? ' ' + processedContent : processedContent);
134
+ } catch (error) {
135
+ if (error.code === 'ENOENT') {
136
+ throw new Error(`File not found: ${filename}`);
137
+ }
138
+ throw error;
139
+ }
140
+ }
141
+
142
+ return result;
143
+ }
144
+
145
+ /**
146
+ * Validate that a command and its arguments are safe
147
+ * @param {string} commandString - Command string to validate
148
+ * @returns {{ allowed: boolean, command: string, args: string[], error?: string }} Validation result
149
+ */
150
+ export function validateCommand(commandString) {
151
+ const trimmedCommand = commandString.trim();
152
+ if (!trimmedCommand) {
153
+ return { allowed: false, command: '', args: [], error: 'Empty command' };
154
+ }
155
+
156
+ // Parse the command using shell-quote to handle quotes properly
157
+ const parsed = parseShellCommand(trimmedCommand);
158
+
159
+ // Check for shell operators or control structures
160
+ const hasOperators = parsed.some(token =>
161
+ typeof token === 'object' && token.op
162
+ );
163
+
164
+ if (hasOperators) {
165
+ return {
166
+ allowed: false,
167
+ command: '',
168
+ args: [],
169
+ error: 'Shell operators (&&, ||, |, ;, etc.) are not allowed'
170
+ };
171
+ }
172
+
173
+ // Extract command and args (all should be strings after validation)
174
+ const tokens = parsed.filter(token => typeof token === 'string');
175
+
176
+ if (tokens.length === 0) {
177
+ return { allowed: false, command: '', args: [], error: 'No valid command found' };
178
+ }
179
+
180
+ const [command, ...args] = tokens;
181
+
182
+ // Extract just the command name (remove path if present)
183
+ const commandName = path.basename(command);
184
+
185
+ // Check if command exactly matches allowlist (no prefix matching)
186
+ const isAllowed = BASH_COMMAND_ALLOWLIST.includes(commandName);
187
+
188
+ if (!isAllowed) {
189
+ return {
190
+ allowed: false,
191
+ command: commandName,
192
+ args,
193
+ error: `Command '${commandName}' is not in the allowlist`
194
+ };
195
+ }
196
+
197
+ // Validate arguments don't contain dangerous metacharacters
198
+ const dangerousPattern = /[;&|`$()<>{}[\]\\]/;
199
+ for (const arg of args) {
200
+ if (dangerousPattern.test(arg)) {
201
+ return {
202
+ allowed: false,
203
+ command: commandName,
204
+ args,
205
+ error: `Argument contains dangerous characters: ${arg}`
206
+ };
207
+ }
208
+ }
209
+
210
+ return { allowed: true, command: commandName, args };
211
+ }
212
+
213
+ /**
214
+ * Backward compatibility: Check if command is allowed (deprecated)
215
+ * @deprecated Use validateCommand() instead for better security
216
+ * @param {string} command - Command to validate
217
+ * @returns {boolean} True if command is allowed
218
+ */
219
+ export function isBashCommandAllowed(command) {
220
+ const result = validateCommand(command);
221
+ return result.allowed;
222
+ }
223
+
224
+ /**
225
+ * Sanitize bash command output
226
+ * @param {string} output - Raw command output
227
+ * @returns {string} Sanitized output
228
+ */
229
+ export function sanitizeOutput(output) {
230
+ if (!output) return '';
231
+
232
+ // Remove control characters except \t, \n, \r
233
+ return [...output]
234
+ .filter(ch => {
235
+ const code = ch.charCodeAt(0);
236
+ return code === 9 // \t
237
+ || code === 10 // \n
238
+ || code === 13 // \r
239
+ || (code >= 32 && code !== 127);
240
+ })
241
+ .join('');
242
+ }
243
+
244
+ /**
245
+ * Process bash commands in content (!command syntax)
246
+ * @param {string} content - Content with !command syntax
247
+ * @param {object} options - Options for bash execution
248
+ * @returns {Promise<string>} Content with bash commands executed and replaced
249
+ */
250
+ export async function processBashCommands(content, options = {}) {
251
+ if (!content) return content;
252
+
253
+ const { cwd = process.cwd(), timeout = BASH_TIMEOUT } = options;
254
+
255
+ // Match !command patterns (at start of line or after whitespace)
256
+ const commandPattern = /(?:^|\n)!(.+?)(?=\n|$)/g;
257
+ const matches = [...content.matchAll(commandPattern)];
258
+
259
+ if (matches.length === 0) {
260
+ return content;
261
+ }
262
+
263
+ let result = content;
264
+
265
+ for (const match of matches) {
266
+ const fullMatch = match[0];
267
+ const commandString = match[1].trim();
268
+
269
+ // Security: validate command and parse args
270
+ const validation = validateCommand(commandString);
271
+
272
+ if (!validation.allowed) {
273
+ throw new Error(`Command not allowed: ${commandString} - ${validation.error}`);
274
+ }
275
+
276
+ try {
277
+ // Execute without shell using execFile with parsed args
278
+ const { stdout, stderr } = await execFileAsync(
279
+ validation.command,
280
+ validation.args,
281
+ {
282
+ cwd,
283
+ timeout,
284
+ maxBuffer: 1024 * 1024, // 1MB max output
285
+ shell: false, // IMPORTANT: No shell interpretation
286
+ env: { ...process.env, PATH: process.env.PATH } // Inherit PATH for finding commands
287
+ }
288
+ );
289
+
290
+ const output = sanitizeOutput(stdout || stderr || '');
291
+
292
+ // Replace the !command with the output
293
+ result = result.replace(fullMatch, fullMatch.startsWith('\n') ? '\n' + output : output);
294
+ } catch (error) {
295
+ if (error.killed) {
296
+ throw new Error(`Command timeout: ${commandString}`);
297
+ }
298
+ throw new Error(`Command failed: ${commandString} - ${error.message}`);
299
+ }
300
+ }
301
+
302
+ return result;
303
+ }