-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsystemActions.js
More file actions
495 lines (450 loc) · 17.6 KB
/
systemActions.js
File metadata and controls
495 lines (450 loc) · 17.6 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
import fs from 'fs';
import os from 'os';
import path from 'path';
import { exec, execSync } from 'child_process';
const APP_LAUNCHERS = {
win32: {
chrome: ['start "" chrome'],
whatsapp: ['start "" "https://web.whatsapp.com"'],
calculator: ['start "" calc'],
notepad: ['start "" notepad'],
settings: ['start "" ms-settings:'],
},
darwin: {
chrome: ['open -a "Google Chrome"'],
whatsapp: ['open -a "WhatsApp"'],
calculator: ['open -a "Calculator"'],
notepad: ['open -a "TextEdit"'],
settings: ['open -a "System Settings"'],
},
linux: {
chrome: ['google-chrome', 'chromium', 'chromium-browser'],
whatsapp: ['xdg-open "https://web.whatsapp.com"'],
calculator: ['gnome-calculator', 'kcalc', 'galculator'],
notepad: ['gedit', 'kate', 'mousepad', 'leafpad', 'nano'],
settings: ['gnome-control-center', 'systemsettings'],
},
};
const INTERPRETER_COMMANDS = {
win32: [
'start "" powershell',
'start "" cmd',
'start "" wt',
],
darwin: [
'open -a "Terminal"',
'open -a "iTerm"',
],
linux: [
'x-terminal-emulator',
'gnome-terminal',
'konsole',
'xfce4-terminal',
'lxterminal',
'xterm',
],
};
const execCommand = (command) => new Promise((resolve, reject) => {
exec(command, (err, stdout, stderr) => {
if (err) {
const output = `${stdout || ''}${stderr || ''}`.trim();
reject(new Error(output || err.message));
return;
}
resolve(stdout.trim());
});
});
const extractExecutable = (command = '') => {
const first = String(command).trim().split(/\s+/)[0] || '';
return first.replace(/^['"]|['"]$/g, '');
};
const commandExists = (binary) => {
const name = String(binary || '').trim();
if (!name) return false;
const platform = os.platform();
if (platform === 'win32' && name.toLowerCase() === 'start') {
// `start` is a cmd.exe builtin, not a standalone binary.
return true;
}
if (name.includes('/') && fs.existsSync(name)) return true;
try {
if (platform === 'win32') {
execSync(`where ${name} >nul 2>&1`, { stdio: 'ignore' });
return true;
}
execSync(`command -v ${name} >/dev/null 2>&1`, { stdio: 'ignore' });
return true;
} catch {
return false;
}
};
const filterAvailableCommands = (commands = []) => commands.filter((command) => {
const binary = extractExecutable(command);
return commandExists(binary);
});
const runCommandSequence = async (commands = []) => {
if (!commands.length) {
throw new Error('No commands available.');
}
let lastError = null;
for (const command of commands) {
try {
await execCommand(command);
return command;
} catch (error) {
lastError = error;
}
}
throw lastError || new Error('Command sequence failed.');
};
export const normalizeList = (value) => {
if (Array.isArray(value)) {
return value.map((entry) => String(entry).trim()).filter(Boolean);
}
if (typeof value === 'string') {
return value.split(',').map((entry) => entry.trim()).filter(Boolean);
}
return [];
};
const normalizeDomainEntry = (value) => {
const trimmed = String(value || '').trim().replace(/\/+$/, '');
if (!trimmed) return '';
if (trimmed.includes('://')) {
try {
return new URL(trimmed).hostname.toLowerCase();
} catch {
return '';
}
}
return trimmed.toLowerCase().split('/')[0];
};
const normalizeDomains = (value) => normalizeList(value)
.map(normalizeDomainEntry)
.filter(Boolean);
export const isPathAllowed = (targetPath, allowedPaths) => {
if (allowedPaths.length === 0) return true;
if (allowedPaths.includes('*')) return true;
const resolvedTarget = path.resolve(targetPath);
return allowedPaths.some((allowedPath) => {
const resolvedAllowed = path.resolve(allowedPath);
return resolvedTarget === resolvedAllowed || resolvedTarget.startsWith(`${resolvedAllowed}${path.sep}`);
});
};
export const isDomainAllowed = (targetUrl, allowedDomains) => {
if (allowedDomains.length === 0) return true;
if (allowedDomains.includes('*')) return true;
let parsed;
try {
parsed = new URL(targetUrl);
} catch {
return false;
}
const hostname = parsed.hostname.toLowerCase();
return allowedDomains.some((domain) => {
const normalized = domain.toLowerCase();
if (normalized.startsWith('*.')) {
const suffix = normalized.slice(2);
return hostname === suffix || hostname.endsWith(`.${suffix}`);
}
return hostname === normalized || hostname.endsWith(`.${normalized}`);
});
};
export const openExternal = (targetUrl, callback) => {
const platform = os.platform();
if (platform === 'win32') {
exec(`start "" "${targetUrl}"`, { shell: 'cmd.exe' }, callback);
return;
}
if (platform === 'darwin') {
exec(`open "${targetUrl}"`, callback);
return;
}
exec(`xdg-open "${targetUrl}"`, callback);
};
export const closeBrowserTabs = (browser) => {
const platform = os.platform();
if (platform === 'darwin') {
const target = browser?.toLowerCase() === 'safari' ? 'Safari' : 'Google Chrome';
const script = `osascript -e 'tell application "${target}" to close every tab of front window'`;
return new Promise((resolve, reject) => {
exec(script, (err) => {
if (err) {
reject(err);
return;
}
resolve({ supported: true, message: `Closed tabs in ${target}.` });
});
});
}
if (platform === 'win32') {
const script = [
'powershell -NoProfile -Command',
'"$wsh = New-Object -ComObject WScript.Shell;',
'1..10 | % { $wsh.SendKeys(\'^w\'); Start-Sleep -Milliseconds 150 }"',
].join(' ');
return execCommand(script)
.then(() => ({ supported: true, message: 'Sent Ctrl+W to close tabs.' }))
.catch((error) => ({ supported: false, message: `Failed to close tabs. ${error.message}` }));
}
if (platform === 'linux') {
if (!fs.existsSync('/usr/bin/xdotool') && !fs.existsSync('/bin/xdotool')) {
return Promise.resolve({ supported: false, message: 'xdotool not installed. Please install xdotool to close tabs on Linux.' });
}
const script = 'for i in {1..10}; do xdotool key --clearmodifiers ctrl+w; sleep 0.15; done';
return execCommand(script)
.then(() => ({ supported: true, message: 'Sent Ctrl+W to close tabs.' }))
.catch((error) => ({ supported: false, message: `Failed to close tabs. ${error.message}` }));
}
return Promise.resolve({ supported: false, message: 'Close tabs is not supported on this platform.' });
};
export const shutdownSystem = (delaySeconds = 0) => {
const platform = os.platform();
return new Promise((resolve, reject) => {
if (platform === 'win32') {
exec(`shutdown /s /t ${Math.max(0, Math.floor(delaySeconds))}`, (err) => {
if (err) {
reject(err);
return;
}
resolve({ message: 'Shutdown scheduled on Windows.' });
});
return;
}
const delayMinutes = delaySeconds > 0 ? Math.max(1, Math.ceil(delaySeconds / 60)) : 0;
const command = delayMinutes > 0 ? `shutdown -h +${delayMinutes}` : 'shutdown -h now';
exec(command, (err) => {
if (err) {
reject(err);
return;
}
resolve({ message: 'Shutdown scheduled.' });
});
});
};
const resolveAppCommands = (appName) => {
const platform = os.platform();
const normalized = String(appName || '').trim().toLowerCase();
if (!normalized) return [];
const map = APP_LAUNCHERS[platform] || APP_LAUNCHERS.linux;
const commands = map?.[normalized];
if (Array.isArray(commands)) {
return commands;
}
if (platform === 'win32') {
return [`start "" "${appName}"`];
}
if (platform === 'darwin') {
return [`open -a "${appName}"`];
}
return [appName];
};
const resolveVolumeCommands = (level) => {
const platform = os.platform();
const normalized = String(level || 'auto').toLowerCase();
if (platform === 'darwin') {
const value = normalized === 'mute' ? 0 : normalized === 'max' ? 100 : 50;
return [`osascript -e "set volume output volume ${value}"`];
}
if (platform === 'win32') {
const base = [
'powershell -NoProfile -Command',
'"$wsh = New-Object -ComObject WScript.Shell;"',
];
if (normalized === 'mute') {
return [`${base.join(' ')} $wsh.SendKeys([char]173)"`];
}
if (normalized === 'max') {
return [`${base.join(' ')} 1..30 | % { $wsh.SendKeys([char]175) }"`];
}
return [`${base.join(' ')} 1..8 | % { $wsh.SendKeys([char]175) }"`];
}
if (normalized === 'mute') {
return ['pactl set-sink-mute @DEFAULT_SINK@ toggle', 'amixer -D pulse set Master toggle'];
}
if (normalized === 'max') {
return ['pactl set-sink-volume @DEFAULT_SINK@ 100%', 'amixer -D pulse set Master 100%'];
}
return ['pactl set-sink-volume @DEFAULT_SINK@ 50%', 'amixer -D pulse set Master 50%'];
};
const resolveTypeCommands = (text) => {
const platform = os.platform();
const sanitized = String(text || '').replace(/"/g, '\\"');
if (!sanitized) return [];
if (platform === 'darwin') {
return [`osascript -e 'tell application "System Events" to keystroke "${sanitized}"'`];
}
if (platform === 'win32') {
return [
'powershell -NoProfile -Command',
`"Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SendKeys]::SendWait(\\"${sanitized}\\")"`,
];
}
return [`xdotool type --clearmodifiers "${sanitized}"`];
};
const resolveInterpreterCommands = () => {
const platform = os.platform();
return INTERPRETER_COMMANDS[platform] || INTERPRETER_COMMANDS.linux;
};
export const executeSystemAction = async ({ action, args = {}, access = {} }) => {
if (!access.enabled) {
return { status: 403, success: false, message: 'System tools are disabled in settings.' };
}
const allowedPaths = normalizeList(access.allowedPaths);
const allowedDomains = normalizeDomains(access.allowedDomains);
if (action === 'copy_folder') {
const { source, destination } = args;
if (!source || !destination) {
return { status: 400, success: false, message: 'Missing source or destination.' };
}
if (!isPathAllowed(source, allowedPaths) || !isPathAllowed(destination, allowedPaths)) {
return { status: 403, success: false, message: 'Path not in allowed list.' };
}
await fs.promises.cp(source, destination, { recursive: true, errorOnExist: false });
return { status: 200, success: true, message: 'Folder copied successfully.' };
}
if (action === 'open_url') {
const { url } = args;
if (!url) {
return { status: 400, success: false, message: 'Missing URL.' };
}
if (!isDomainAllowed(url, allowedDomains)) {
return { status: 403, success: false, message: 'Domain not in allowed list.' };
}
await new Promise((resolve, reject) => {
openExternal(url, (err) => (err ? reject(err) : resolve()));
});
return { status: 200, success: true, message: 'Opened in default browser.' };
}
if (action === 'open_whatsapp') {
const { phone, message } = args;
if (!phone || !message) {
return { status: 400, success: false, message: 'Missing phone or message.' };
}
const url = `https://wa.me/${encodeURIComponent(phone)}?text=${encodeURIComponent(message)}`;
if (!isDomainAllowed(url, allowedDomains)) {
return { status: 403, success: false, message: 'Domain not in allowed list.' };
}
await new Promise((resolve, reject) => {
openExternal(url, (err) => (err ? reject(err) : resolve()));
});
return { status: 200, success: true, message: 'WhatsApp Web opened with prefilled message.' };
}
if (action === 'open_youtube') {
const { query } = args;
if (!query) {
return { status: 400, success: false, message: 'Missing search query.' };
}
const url = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`;
if (!isDomainAllowed(url, allowedDomains)) {
return { status: 403, success: false, message: 'Domain not in allowed list.' };
}
await new Promise((resolve, reject) => {
openExternal(url, (err) => (err ? reject(err) : resolve()));
});
return { status: 200, success: true, message: 'YouTube search opened.' };
}
if (action === 'open_urls') {
const { urls } = args;
if (!Array.isArray(urls) || urls.length === 0) {
return { status: 400, success: false, message: 'Missing URLs.' };
}
const disallowed = urls.find((url) => !isDomainAllowed(url, allowedDomains));
if (disallowed) {
return { status: 403, success: false, message: 'One or more domains not in allowed list.' };
}
for (const url of urls) {
await new Promise((resolve, reject) => {
openExternal(url, (err) => (err ? reject(err) : resolve()));
});
}
return { status: 200, success: true, message: 'Opened URLs in browser.' };
}
if (action === 'close_tabs') {
if (!args.confirm) {
return { status: 400, success: false, message: 'Confirmation required to close tabs.' };
}
const result = await closeBrowserTabs(args.browser);
if (!result.supported) {
return { status: 501, success: false, message: result.message };
}
return { status: 200, success: true, message: result.message };
}
if (action === 'shutdown') {
if (!access.allowShutdown) {
return { status: 403, success: false, message: 'Shutdown disabled in settings.' };
}
if (!args.confirm) {
return { status: 400, success: false, message: 'Confirmation required to shutdown.' };
}
const result = await shutdownSystem(args.delaySeconds);
return { status: 200, success: true, message: result.message };
}
if (action === 'open_app') {
const { app_name: appName } = args;
if (!appName) {
return { status: 400, success: false, message: 'Missing app name.' };
}
const commands = resolveAppCommands(appName);
try {
await runCommandSequence(commands);
return { status: 200, success: true, message: `Opened ${appName}.` };
} catch (error) {
return { status: 500, success: false, message: `Failed to open ${appName}. ${error.message}` };
}
}
if (action === 'play_media') {
const { query } = args;
if (!query) {
return { status: 400, success: false, message: 'Missing media query.' };
}
const url = `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`;
if (!isDomainAllowed(url, allowedDomains)) {
return { status: 403, success: false, message: 'Domain not in allowed list.' };
}
await new Promise((resolve, reject) => {
openExternal(url, (err) => (err ? reject(err) : resolve()));
});
return { status: 200, success: true, message: 'Opened media search.' };
}
if (action === 'control_volume') {
const { level } = args;
const commands = resolveVolumeCommands(level);
try {
await runCommandSequence(commands);
return { status: 200, success: true, message: 'Volume updated.' };
} catch (error) {
return { status: 500, success: false, message: `Volume update failed. ${error.message}` };
}
}
if (action === 'type_text') {
const { text } = args;
if (!text) {
return { status: 400, success: false, message: 'Missing text.' };
}
const commands = resolveTypeCommands(text);
try {
await runCommandSequence(commands);
return { status: 200, success: true, message: 'Typed text in focused app.' };
} catch (error) {
return { status: 500, success: false, message: `Typing failed. ${error.message}` };
}
}
if (action === 'open_interpreter') {
const commands = resolveInterpreterCommands();
const available = filterAvailableCommands(commands);
if (!available.length) {
return {
status: 501,
success: false,
message: 'No terminal/interpreter app found on this machine. Install one (xterm/gnome-terminal/konsole) or run in local desktop environment.',
};
}
try {
await runCommandSequence(available);
return { status: 200, success: true, message: 'Opened system interpreter/terminal.' };
} catch (error) {
return { status: 500, success: false, message: `Failed to open interpreter. ${error.message}` };
}
}
return { status: 400, success: false, message: 'Unknown system action.' };
};