-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathjest.setup.cjs
More file actions
364 lines (310 loc) · 11.9 KB
/
jest.setup.cjs
File metadata and controls
364 lines (310 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
// Mock the ESM modules with CommonJS equivalents for Jest
const fs = require('fs');
const path = require('path');
const { EventEmitter } = require('events');
const { execFile } = require('child_process');
const { promisify } = require('util');
const { randomUUID } = require('crypto');
// Define the CommandSecurityLevel enum
const CommandSecurityLevel = {
SAFE: 'safe',
REQUIRES_APPROVAL: 'requires_approval',
FORBIDDEN: 'forbidden'
};
// Define the PlatformType enum
const PlatformType = {
WINDOWS: 'windows',
MACOS: 'macos',
LINUX: 'linux',
UNKNOWN: 'unknown'
};
// Mock the platform-utils module
const detectPlatform = () => {
const platform = process.platform;
if (platform === 'win32') return PlatformType.WINDOWS;
if (platform === 'darwin') return PlatformType.MACOS;
if (platform === 'linux') return PlatformType.LINUX;
return PlatformType.UNKNOWN;
};
const getDefaultShell = () => {
const platform = detectPlatform();
switch (platform) {
case PlatformType.WINDOWS:
return process.env.COMSPEC || 'cmd.exe';
case PlatformType.MACOS:
return '/bin/zsh';
case PlatformType.LINUX:
return process.env.SHELL || '/bin/bash';
default:
return process.env.SHELL || '/bin/sh';
}
};
const validateShellPath = (shellPath) => {
try {
return fs.existsSync(shellPath) && fs.statSync(shellPath).isFile();
} catch (error) {
return false;
}
};
const getShellSuggestions = () => ({
[PlatformType.WINDOWS]: ['cmd.exe', 'powershell.exe', 'pwsh.exe'],
[PlatformType.MACOS]: ['/bin/zsh', '/bin/bash', '/bin/sh'],
[PlatformType.LINUX]: ['/bin/bash', '/bin/sh', '/bin/zsh'],
[PlatformType.UNKNOWN]: ['/bin/sh']
});
const getCommonShellLocations = () => {
const platform = detectPlatform();
switch (platform) {
case PlatformType.WINDOWS:
return [
process.env.COMSPEC || 'C:\\Windows\\System32\\cmd.exe',
'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',
'C:\\Program Files\\PowerShell\\7\\pwsh.exe'
];
case PlatformType.MACOS:
return ['/bin/zsh', '/bin/bash', '/bin/sh'];
case PlatformType.LINUX:
return ['/bin/bash', '/bin/sh', '/usr/bin/bash', '/usr/bin/zsh'];
default:
return ['/bin/sh'];
}
};
const getShellConfigurationHelp = () => {
const platform = detectPlatform();
const suggestions = getShellSuggestions()[platform];
const locations = getCommonShellLocations();
let message = 'Shell Configuration Help:\n\n';
message += `Detected platform: ${platform}\n\n`;
message += 'Suggested shells for this platform:\n';
suggestions.forEach(shell => {
message += `- ${shell}\n`;
});
message += '\nCommon shell locations on this platform:\n';
locations.forEach(location => {
message += `- ${location}\n`;
});
message += '\nTo configure a custom shell, provide the full path to the shell executable.';
return message;
};
// Mock the CommandService class
class CommandService extends EventEmitter {
constructor(options = {}) {
super();
this.shell = options.shell || getDefaultShell();
this.useShell = options.useShell ?? false;
this.whitelist = new Map();
this.pendingCommands = new Map();
this.defaultTimeout = options.defaultTimeout ?? 30000;
this.initializeDefaultWhitelist();
}
getShell() {
return this.shell;
}
isShellEnabled() {
return this.useShell;
}
initializeDefaultWhitelist() {
const platform = detectPlatform();
const commands = [];
// Common commands for all platforms
commands.push({ command: 'echo', securityLevel: CommandSecurityLevel.SAFE, description: 'Print text to standard output' });
// Platform-specific commands
if (platform === PlatformType.WINDOWS) {
commands.push({ command: 'dir', securityLevel: CommandSecurityLevel.SAFE, description: 'List directory contents' });
commands.push({ command: 'copy', securityLevel: CommandSecurityLevel.REQUIRES_APPROVAL, description: 'Copy files' });
commands.push({ command: 'mkdir', securityLevel: CommandSecurityLevel.REQUIRES_APPROVAL, description: 'Create directories' });
commands.push({ command: 'del', securityLevel: CommandSecurityLevel.FORBIDDEN, description: 'Delete files' });
} else {
commands.push({ command: 'ls', securityLevel: CommandSecurityLevel.SAFE, description: 'List directory contents' });
commands.push({ command: 'cat', securityLevel: CommandSecurityLevel.SAFE, description: 'Concatenate and print files' });
commands.push({ command: 'grep', securityLevel: CommandSecurityLevel.SAFE, description: 'Search for patterns in files' });
commands.push({ command: 'find', securityLevel: CommandSecurityLevel.SAFE, description: 'Find files in a directory hierarchy' });
commands.push({ command: 'cd', securityLevel: CommandSecurityLevel.SAFE, description: 'Change directory' });
commands.push({ command: 'head', securityLevel: CommandSecurityLevel.SAFE, description: 'Output the first part of files' });
commands.push({ command: 'tail', securityLevel: CommandSecurityLevel.SAFE, description: 'Output the last part of files' });
commands.push({ command: 'wc', securityLevel: CommandSecurityLevel.SAFE, description: 'Print newline, word, and byte counts' });
commands.push({ command: 'mv', securityLevel: CommandSecurityLevel.REQUIRES_APPROVAL, description: 'Move (rename) files' });
commands.push({ command: 'cp', securityLevel: CommandSecurityLevel.REQUIRES_APPROVAL, description: 'Copy files and directories' });
commands.push({ command: 'mkdir', securityLevel: CommandSecurityLevel.REQUIRES_APPROVAL, description: 'Create directories' });
commands.push({ command: 'touch', securityLevel: CommandSecurityLevel.REQUIRES_APPROVAL, description: 'Change file timestamps or create empty files' });
commands.push({ command: 'chmod', securityLevel: CommandSecurityLevel.REQUIRES_APPROVAL, description: 'Change file mode bits' });
commands.push({ command: 'chown', securityLevel: CommandSecurityLevel.REQUIRES_APPROVAL, description: 'Change file owner and group' });
commands.push({ command: 'rm', securityLevel: CommandSecurityLevel.FORBIDDEN, description: 'Remove files or directories' });
commands.push({ command: 'sudo', securityLevel: CommandSecurityLevel.FORBIDDEN, description: 'Execute a command as another user' });
}
commands.forEach(entry => {
this.whitelist.set(entry.command, entry);
});
}
addToWhitelist(entry) {
this.whitelist.set(entry.command, entry);
}
removeFromWhitelist(command) {
this.whitelist.delete(command);
}
updateSecurityLevel(command, securityLevel) {
const entry = this.whitelist.get(command);
if (entry) {
entry.securityLevel = securityLevel;
this.whitelist.set(command, entry);
}
}
getWhitelist() {
return Array.from(this.whitelist.values());
}
getPendingCommands() {
return Array.from(this.pendingCommands.values());
}
validateCommand(command, args) {
const baseCommand = path.basename(command);
const entry = this.whitelist.get(baseCommand);
if (!entry) {
return null;
}
if (entry.securityLevel === CommandSecurityLevel.FORBIDDEN) {
return CommandSecurityLevel.FORBIDDEN;
}
if (entry.allowedArgs && entry.allowedArgs.length > 0) {
const allArgsValid = args.every((arg, index) => {
if (index >= (entry.allowedArgs?.length || 0)) {
return false;
}
const pattern = entry.allowedArgs?.[index];
if (!pattern) {
return false;
}
if (typeof pattern === 'string') {
return arg === pattern;
} else {
return pattern.test(arg);
}
});
if (!allArgsValid) {
return CommandSecurityLevel.REQUIRES_APPROVAL;
}
}
return entry.securityLevel;
}
async executeCommand(command, args = [], options = {}) {
const securityLevel = this.validateCommand(command, args);
if (securityLevel === null) {
throw new Error(`Command not whitelisted: ${command}`);
}
if (securityLevel === CommandSecurityLevel.FORBIDDEN) {
throw new Error(`Command is forbidden: ${command}`);
}
if (securityLevel === CommandSecurityLevel.REQUIRES_APPROVAL) {
return this.queueCommandForApproval(command, args, options.requestedBy);
}
try {
const timeout = options.timeout || this.defaultTimeout;
const execFileAsync = promisify(execFile);
const { stdout, stderr } = await execFileAsync(command, args, {
timeout,
shell: this.useShell ? this.shell : false
});
return { stdout, stderr };
} catch (error) {
if (error instanceof Error) {
throw new Error(`Command execution failed: ${error.message}`);
}
throw error;
}
}
queueCommandForApproval(command, args = [], requestedBy) {
return new Promise((resolve, reject) => {
const id = randomUUID();
const pendingCommand = {
id,
command,
args,
requestedAt: new Date(),
requestedBy,
resolve: (result) => resolve(result),
reject: (error) => reject(error)
};
this.pendingCommands.set(id, pendingCommand);
this.emit('command:pending', pendingCommand);
setTimeout(() => {
if (this.pendingCommands.has(id)) {
this.emit('command:approval_timeout', {
commandId: id,
message: 'Command approval timed out. If you approved this command in the UI, please use get_pending_commands and approve_command to complete the process.'
});
}
}, 5000);
});
}
queueCommandForApprovalNonBlocking(command, args = [], requestedBy) {
const id = randomUUID();
const pendingCommand = {
id,
command,
args,
requestedAt: new Date(),
requestedBy,
resolve: () => {},
reject: () => {}
};
this.pendingCommands.set(id, pendingCommand);
this.emit('command:pending', pendingCommand);
setTimeout(() => {
if (this.pendingCommands.has(id)) {
this.emit('command:approval_timeout', {
commandId: id,
message: 'Command approval timed out. If you approved this command in the UI, please use get_pending_commands and approve_command to complete the process.'
});
}
}, 5000);
return id;
}
async approveCommand(commandId) {
const pendingCommand = this.pendingCommands.get(commandId);
if (!pendingCommand) {
throw new Error(`No pending command with ID: ${commandId}`);
}
try {
const execFileAsync = promisify(execFile);
const { stdout, stderr } = await execFileAsync(
pendingCommand.command,
pendingCommand.args,
{ shell: this.useShell ? this.shell : false }
);
this.pendingCommands.delete(commandId);
this.emit('command:approved', { commandId, stdout, stderr });
pendingCommand.resolve({ stdout, stderr });
return { stdout, stderr };
} catch (error) {
this.pendingCommands.delete(commandId);
this.emit('command:failed', { commandId, error });
if (error instanceof Error) {
pendingCommand.reject(error);
throw error;
}
const genericError = new Error('Command execution failed');
pendingCommand.reject(genericError);
throw genericError;
}
}
denyCommand(commandId, reason = 'Command denied') {
const pendingCommand = this.pendingCommands.get(commandId);
if (!pendingCommand) {
throw new Error(`No pending command with ID: ${commandId}`);
}
this.pendingCommands.delete(commandId);
this.emit('command:denied', { commandId, reason });
pendingCommand.reject(new Error(reason));
}
}
// Export the mocked modules
module.exports = {
CommandService,
CommandSecurityLevel,
detectPlatform,
PlatformType,
getDefaultShell,
validateShellPath,
getShellSuggestions,
getCommonShellLocations,
getShellConfigurationHelp
};