@livedesk/client 0.1.250 → 0.1.251

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.
@@ -7,7 +7,8 @@ import crypto from 'crypto';
7
7
  import { existsSync, promises as fs, statfsSync } from 'fs';
8
8
  import { spawn } from 'child_process';
9
9
  import { createRequire } from 'node:module';
10
- import { fileURLToPath } from 'node:url';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { resolveAgentShellCommand } from '../src/runtime/agent-shell.js';
11
12
 
12
13
  const require = createRequire(import.meta.url);
13
14
  const CLIENT_UPDATE_BOOTSTRAP_PATH = fileURLToPath(
@@ -1142,9 +1143,10 @@ async function resolveAgentPath(options, value, permissionMode, rejectSensitive
1142
1143
  return resolved;
1143
1144
  }
1144
1145
 
1145
- function runNodeAgentProcess(executable, args, timeoutMs = 15000, cwd = undefined) {
1146
- return new Promise((resolve, reject) => {
1147
- const child = spawn(executable, args, { cwd, windowsHide: true, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
1146
+ function runNodeAgentProcess(executable, args, timeoutMs = 15000, cwd = undefined, maxTimeoutMs = 30000) {
1147
+ return new Promise((resolve, reject) => {
1148
+ const startedAt = Date.now();
1149
+ const child = spawn(executable, args, { cwd, windowsHide: true, shell: false, stdio: ['ignore', 'pipe', 'pipe'] });
1148
1150
  let output = '';
1149
1151
  let timedOut = false;
1150
1152
  const append = chunk => { output = `${output}${String(chunk || '')}`.replace(/[\0\r]/g, ' ').slice(0, MAX_AGENT_OUTPUT_CHARS); };
@@ -1154,11 +1156,55 @@ function runNodeAgentProcess(executable, args, timeoutMs = 15000, cwd = undefine
1154
1156
  timedOut = true;
1155
1157
  child.kill('SIGTERM');
1156
1158
  setTimeout(() => child.kill('SIGKILL'), 1000).unref?.();
1157
- }, Math.max(1000, Math.min(30000, Number(timeoutMs) || 15000)));
1158
- child.once('error', error => { clearTimeout(timer); reject(error); });
1159
- child.once('close', code => { clearTimeout(timer); resolve({ output: redactAgentOutput(`${output}${timedOut ? '\n[timeout]' : ''}`.trim()), exitCode: timedOut ? -1 : code ?? -1, timedOut }); });
1160
- });
1161
- }
1159
+ }, Math.max(1000, Math.min(maxTimeoutMs, Number(timeoutMs) || 15000)));
1160
+ child.once('error', error => { clearTimeout(timer); reject(error); });
1161
+ child.once('close', code => { clearTimeout(timer); resolve({ output: redactAgentOutput(`${output}${timedOut ? '\n[timeout]' : ''}`.trim()), exitCode: timedOut ? -1 : code ?? -1, timedOut, durationMs: Date.now() - startedAt }); });
1162
+ });
1163
+ }
1164
+
1165
+ async function searchNodeAgentFiles(options, args, permissionMode) {
1166
+ const root = await resolveAgentPath(options, args.path, permissionMode);
1167
+ const query = String(args.query || '').trim().toLowerCase();
1168
+ if (!query || query.length > 160 || /[\0\r\n]/.test(query)) throw new Error('search query is invalid');
1169
+ const maxResults = Math.max(1, Math.min(200, Number(args.maxResults) || 100));
1170
+ const maxDepth = Math.max(0, Math.min(8, Number(args.maxDepth) || 4));
1171
+ const maxScannedEntries = Math.max(maxResults, Math.min(5000, Number(args.maxScannedEntries) || 2000));
1172
+ const queue = [{ directory: root, depth: 0 }];
1173
+ const matches = [];
1174
+ let scannedEntries = 0;
1175
+ while (queue.length > 0 && matches.length < maxResults && scannedEntries < maxScannedEntries) {
1176
+ const current = queue.shift();
1177
+ let entries;
1178
+ try {
1179
+ entries = await fs.readdir(current.directory, { withFileTypes: true });
1180
+ } catch {
1181
+ continue;
1182
+ }
1183
+ for (const entry of entries) {
1184
+ if (matches.length >= maxResults || scannedEntries >= maxScannedEntries) break;
1185
+ scannedEntries += 1;
1186
+ const entryPath = path.join(current.directory, entry.name);
1187
+ if (isSensitiveAgentPath(entryPath)) continue;
1188
+ const isDirectory = entry.isDirectory();
1189
+ if (entry.name.toLowerCase().includes(query)) {
1190
+ matches.push({ name: entry.name, path: entryPath, type: isDirectory ? 'directory' : 'file' });
1191
+ }
1192
+ if (isDirectory && current.depth < maxDepth && !entry.isSymbolicLink()) {
1193
+ queue.push({ directory: entryPath, depth: current.depth + 1 });
1194
+ }
1195
+ }
1196
+ }
1197
+ return {
1198
+ summary: `Found ${matches.length} matching path${matches.length === 1 ? '' : 's'}.`,
1199
+ data: {
1200
+ path: root,
1201
+ query,
1202
+ matches,
1203
+ scannedEntries,
1204
+ truncated: matches.length >= maxResults || scannedEntries >= maxScannedEntries
1205
+ }
1206
+ };
1207
+ }
1162
1208
 
1163
1209
  function redactAgentOutput(value) {
1164
1210
  let output = String(value || '').replace(/[\0\r]/g, ' ');
@@ -1324,7 +1370,7 @@ async function executeNodeAgentOperation(options, operation, payload = {}) {
1324
1370
  else await fs.unlink(filePath);
1325
1371
  return { summary: `Deleted ${path.basename(filePath)}.`, data: { path: filePath, recursive: args.recursive === true } };
1326
1372
  }
1327
- if (operation === 'file.list') {
1373
+ if (operation === 'file.list') {
1328
1374
  const directory = await resolveAgentPath(options, args.path, permissionMode);
1329
1375
  const entries = await fs.readdir(directory, { withFileTypes: true });
1330
1376
  const maxEntries = Math.max(1, Math.min(500, Number(args.maxEntries) || 200));
@@ -1334,8 +1380,15 @@ async function executeNodeAgentOperation(options, operation, payload = {}) {
1334
1380
  if (isSensitiveAgentPath(entryPath)) continue;
1335
1381
  data.push({ name: entry.name, path: entryPath, type: entry.isDirectory() ? 'directory' : 'file', sizeBytes: entry.isDirectory() ? 0 : (await fs.stat(entryPath)).size });
1336
1382
  }
1337
- return { summary: `Listed ${data.length} entries.`, data: { path: directory, entries: data, truncated: entries.length > maxEntries } };
1338
- }
1383
+ return { summary: `Listed ${data.length} entries.`, data: { path: directory, entries: data, truncated: entries.length > maxEntries } };
1384
+ }
1385
+ if (operation === 'file.search') return searchNodeAgentFiles(options, args, permissionMode);
1386
+ if (operation === 'directory.create') {
1387
+ let directory = await resolveAgentPath(options, args.path, permissionMode);
1388
+ await fs.mkdir(directory, { recursive: true });
1389
+ directory = await resolveAgentPath(options, args.path, permissionMode);
1390
+ return { summary: `Created directory ${path.basename(directory)}.`, data: { path: directory, created: true } };
1391
+ }
1339
1392
  if (operation === 'application.launch') {
1340
1393
  const executable = String(args.executable || '').trim();
1341
1394
  if (!executable || executable.length > 400 || /[\0\r\n]/.test(executable)) throw new Error('executable is invalid');
@@ -1389,12 +1442,13 @@ async function executeNodeAgentOperation(options, operation, payload = {}) {
1389
1442
  if (!ok) throw new Error(`Service ${action} failed for ${service}.`);
1390
1443
  return { summary: `Service ${action} completed for ${service}.`, data: { service, action, results } };
1391
1444
  }
1392
- if (operation === 'command.run') {
1393
- const command = String(args.command || '');
1394
- const executable = process.platform === 'win32' ? 'cmd.exe' : '/bin/sh';
1395
- const commandArgs = process.platform === 'win32' ? ['/d', '/s', '/c', command] : ['-lc', command];
1396
- const result = await runNodeAgentProcess(executable, commandArgs, args.timeoutMs, args.workingDirectory ? await resolveAgentPath(options, args.workingDirectory, permissionMode, false) : undefined);
1397
- return { summary: result.timedOut ? 'Command timed out.' : `Command exited with code ${result.exitCode}.`, data: { ...result, output: redactAgentOutput(result.output) } };
1445
+ if (operation === 'command.run') {
1446
+ const command = String(args.command || '');
1447
+ if (!command || command.length > 16000 || /\0/.test(command)) throw new Error('command is invalid');
1448
+ const shellCommand = resolveAgentShellCommand({ shell: args.shell, command });
1449
+ const workingDirectory = args.workingDirectory ? await resolveAgentPath(options, args.workingDirectory, permissionMode, false) : undefined;
1450
+ const result = await runNodeAgentProcess(shellCommand.executable, shellCommand.args, args.timeoutMs, workingDirectory, 300000);
1451
+ return { summary: result.timedOut ? `${shellCommand.shell} command timed out.` : `${shellCommand.shell} command exited with code ${result.exitCode}.`, data: { ...result, output: redactAgentOutput(result.output), shell: shellCommand.shell, workingDirectory: workingDirectory || process.cwd() } };
1398
1452
  }
1399
1453
  if (operation === 'script.run') {
1400
1454
  const scriptPath = await resolveAgentPath(options, args.path, permissionMode);
@@ -1481,7 +1535,7 @@ function normalizeNodeAgentTaskResult(result) {
1481
1535
  return { ...result, ok, status: ok ? 'completed' : 'failed', error };
1482
1536
  }
1483
1537
 
1484
- const NODE_AGENT_OPERATIONS = new Set(['process.control', 'service.control', 'application.launch', 'application.close', 'file.read', 'file.write', 'file.delete', 'file.list', 'command.run', 'script.run', 'software.install', 'network.status', 'system.power', 'system.configure', 'logs.collect']);
1538
+ const NODE_AGENT_OPERATIONS = new Set(['process.control', 'service.control', 'application.launch', 'application.close', 'file.read', 'file.write', 'file.delete', 'file.list', 'file.search', 'directory.create', 'command.run', 'script.run', 'software.install', 'network.status', 'system.power', 'system.configure', 'logs.collect']);
1485
1539
 
1486
1540
  function remotePolicyAllows(options, command) {
1487
1541
  const policy = options.effectivePolicy;
@@ -1723,7 +1777,7 @@ async function handleRemoteCommand(socket, options, message, nextFrameSeq, activ
1723
1777
  summary: result.summary,
1724
1778
  error: result.error || undefined,
1725
1779
  data: result.data,
1726
- sideEffects: ['file.read', 'file.list', 'network.status', 'logs.collect'].includes(command) ? 'none' : 'audited',
1780
+ sideEffects: ['file.read', 'file.list', 'file.search', 'network.status', 'logs.collect'].includes(command) ? 'none' : 'audited',
1727
1781
  completedAt: new Date().toISOString()
1728
1782
  }
1729
1783
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@livedesk/client",
3
- "version": "0.1.250",
3
+ "version": "0.1.251",
4
4
  "description": "LiveDesk local remote client",
5
5
  "type": "module",
6
6
  "bin": {
@@ -42,10 +42,10 @@
42
42
  "ws": "^8.18.3"
43
43
  },
44
44
  "optionalDependencies": {
45
- "@livedesk/fast-linux-x64": "0.1.446",
46
- "@livedesk/fast-osx-arm64": "0.1.446",
47
- "@livedesk/fast-osx-x64": "0.1.446",
48
- "@livedesk/fast-win-x64": "0.1.446"
45
+ "@livedesk/fast-linux-x64": "0.1.447",
46
+ "@livedesk/fast-osx-arm64": "0.1.447",
47
+ "@livedesk/fast-osx-x64": "0.1.447",
48
+ "@livedesk/fast-win-x64": "0.1.447"
49
49
  },
50
50
  "publishConfig": {
51
51
  "access": "public"
@@ -0,0 +1,66 @@
1
+ import { existsSync } from 'node:fs';
2
+
3
+ export const AGENT_SHELL_NAMES = Object.freeze([
4
+ 'auto',
5
+ 'powershell',
6
+ 'pwsh',
7
+ 'cmd',
8
+ 'sh',
9
+ 'bash',
10
+ 'zsh'
11
+ ]);
12
+
13
+ function unixShellPath(shell, platform, fileExists) {
14
+ if (shell === 'sh') return '/bin/sh';
15
+ if (shell === 'bash') return '/bin/bash';
16
+ if (shell === 'zsh') return '/bin/zsh';
17
+ if (shell === 'pwsh') return 'pwsh';
18
+ if (shell === 'powershell' || shell === 'cmd') {
19
+ throw new Error(`${shell} is not available on ${platform}.`);
20
+ }
21
+ if (platform === 'darwin' && fileExists('/bin/zsh')) return '/bin/zsh';
22
+ if (fileExists('/bin/bash')) return '/bin/bash';
23
+ return '/bin/sh';
24
+ }
25
+
26
+ export function resolveAgentShellCommand({
27
+ platform = process.platform,
28
+ shell = 'auto',
29
+ command = '',
30
+ fileExists = existsSync
31
+ } = {}) {
32
+ const normalizedShell = String(shell || 'auto').trim().toLowerCase();
33
+ if (!AGENT_SHELL_NAMES.includes(normalizedShell)) {
34
+ throw new Error(`Unsupported shell: ${normalizedShell || 'empty'}.`);
35
+ }
36
+ if (platform === 'win32') {
37
+ if (['sh', 'bash', 'zsh'].includes(normalizedShell)) {
38
+ throw new Error(`${normalizedShell} is not available on Windows.`);
39
+ }
40
+ if (normalizedShell === 'cmd') {
41
+ return {
42
+ shell: 'cmd',
43
+ executable: process.env.ComSpec || 'cmd.exe',
44
+ args: ['/d', '/s', '/c', String(command)]
45
+ };
46
+ }
47
+ const powershellCore = normalizedShell === 'pwsh';
48
+ return {
49
+ shell: powershellCore ? 'pwsh' : 'powershell',
50
+ executable: powershellCore ? 'pwsh.exe' : 'powershell.exe',
51
+ args: ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', String(command)]
52
+ };
53
+ }
54
+
55
+ const executable = unixShellPath(normalizedShell, platform, fileExists);
56
+ if (executable.startsWith('/') && !fileExists(executable)) {
57
+ throw new Error(`${normalizedShell} is not installed at ${executable}.`);
58
+ }
59
+ return {
60
+ shell: normalizedShell === 'auto'
61
+ ? executable.endsWith('/zsh') ? 'zsh' : executable.endsWith('/bash') ? 'bash' : 'sh'
62
+ : normalizedShell,
63
+ executable,
64
+ args: ['-lc', String(command)]
65
+ };
66
+ }