shellway 0.5.0 → 0.6.1

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.
Files changed (2) hide show
  1. package/package.json +2 -2
  2. package/shellway.js +182 -12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shellway",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Shellway agent: lets ChatGPT, Claude and Cursor work on this computer through the Shellway relay.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -28,4 +28,4 @@
28
28
  },
29
29
  "author": "Sandeep Kumar Saini",
30
30
  "license": "UNLICENSED"
31
- }
31
+ }
package/shellway.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from 'node:child_process';
3
3
  import { homedir, hostname, platform, release } from 'node:os';
4
- import { join, resolve } from 'node:path';
5
- import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync, copyFileSync, rmSync } from 'node:fs';
4
+ import { join, resolve, dirname, basename, sep } from 'node:path';
5
+ import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync, copyFileSync, rmSync, statSync, realpathSync } from 'node:fs';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { execFileSync } from 'node:child_process';
8
8
  import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, cp, rm } from 'node:fs/promises';
9
9
 
10
- const AGENT_VERSION = '0.5.0'; // keep equal to agent/package.json
10
+ const AGENT_VERSION = '0.6.1'; // keep equal to agent/package.json
11
11
  if (Number(process.versions.node.split('.')[0]) < 22) {
12
12
  console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
13
13
  process.exit(1);
@@ -508,12 +508,148 @@ const handlers = {
508
508
  };
509
509
  const writeMethods = new Set(['run_command', 'write_file', 'edit_block', 'move_file', 'create_directory', 'start_process', 'interact_with_process', 'force_terminate', 'download_file']);
510
510
 
511
+ // ---- safety rules set by the computer's owner (~/.shellway/policy.json, edited with `shellway policy ...`) ----
512
+ // No file = no extra rules. The file lives on this computer, so the AI and the relay cannot change it.
513
+ const POLICY = join(CONF_DIR, 'policy.json');
514
+ const DELETE_WORDS = ['rm', 'rmdir', 'del', 'erase', 'rd', 'Remove-Item', 'shred', 'unlink', 'format', 'mkfs', 'diskpart'];
515
+ let policyCache = { mtime: -1, value: null };
516
+ function emptyPolicy() { return { allowed_folders: [], blocked_commands: [], commands: true, backups: false }; }
517
+ function loadPolicy() {
518
+ let st; try { st = statSync(POLICY); } catch { policyCache = { mtime: -1, value: null }; return null; }
519
+ if (st.mtimeMs === policyCache.mtime) return policyCache.value;
520
+ let v;
521
+ try { v = { ...emptyPolicy(), ...JSON.parse(readFileSync(POLICY, 'utf8')) }; }
522
+ catch { v = { ...emptyPolicy(), commands: false, broken: true }; } // unreadable rules: fail closed for commands
523
+ v.allowed_folders = (Array.isArray(v.allowed_folders) ? v.allowed_folders : []).map(String).filter(Boolean);
524
+ v.blocked_commands = (Array.isArray(v.blocked_commands) ? v.blocked_commands : []).map(String).filter(Boolean);
525
+ policyCache = { mtime: st.mtimeMs, value: v };
526
+ return v;
527
+ }
528
+ function savePolicy(p) {
529
+ mkdirSync(CONF_DIR, { recursive: true });
530
+ const { broken, ...clean } = p;
531
+ writeFileSync(POLICY, JSON.stringify(clean, null, 2));
532
+ policyCache = { mtime: -1, value: null };
533
+ }
534
+ const isWin = platform() === 'win32';
535
+ const normCase = (p) => (isWin ? p.toLowerCase() : p);
536
+ // Real location of a path, following symlinks; for a path that does not exist yet, of its nearest existing parent.
537
+ function realLocation(p) {
538
+ let cur = resolve(p), rest = [];
539
+ for (;;) {
540
+ try { return join(realpathSync.native(cur), ...rest); }
541
+ catch {
542
+ const parent = dirname(cur);
543
+ if (parent === cur) return resolve(p);
544
+ rest.unshift(basename(cur)); cur = parent;
545
+ }
546
+ }
547
+ }
548
+ function insideAllowed(p, pol) {
549
+ const real = normCase(realLocation(p));
550
+ return pol.allowed_folders.some((f) => {
551
+ const root = normCase(realLocation(f));
552
+ return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep);
553
+ });
554
+ }
555
+ const PATH_PARAMS = {
556
+ read_file: ['path'], write_file: ['path'], edit_block: ['path'], search_files: ['path'], read_multiple_files: ['paths'],
557
+ get_file_info: ['path'], move_file: ['source', 'destination'], create_directory: ['path'], list_directory: ['path'],
558
+ start_search: ['path'], download_file: ['path'], open_file: ['path'], run_command: ['cwd'], start_process: ['cwd'],
559
+ };
560
+ const COMMAND_METHODS = new Set(['run_command', 'start_process', 'interact_with_process']);
561
+ const escRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
562
+ function blockedBy(text, pol) {
563
+ return pol.blocked_commands.find((b) => new RegExp(`(^|[^\\w-])${escRe(b.trim()).replace(/\s+/g, '\\s+')}($|[^\\w-])`, 'i').test(text));
564
+ }
565
+ // Throws when the owner's rules forbid this call. May fill in a default cwd inside an allowed folder.
566
+ function checkPolicy(method, params) {
567
+ const pol = loadPolicy();
568
+ if (!pol) return params;
569
+ const fix = 'The owner of this computer set this rule; it can only be changed on the computer (shellway policy).';
570
+ if (COMMAND_METHODS.has(method)) {
571
+ if (!pol.commands) throw new Error(`Commands are turned off on this computer${pol.broken ? ' (its safety rules file could not be read)' : ''}; only file tools work. ${fix}`);
572
+ const text = method === 'interact_with_process' ? String(params.input ?? '') : String(params.command ?? '');
573
+ const hit = blockedBy(text, pol);
574
+ if (hit) throw new Error(`Blocked: "${hit}" is on this computer's list of blocked commands. Nothing was run. ${fix}`);
575
+ }
576
+ if (pol.allowed_folders.length && PATH_PARAMS[method]) {
577
+ const out = { ...params };
578
+ if ((method === 'run_command' || method === 'start_process') && !out.cwd) out.cwd = pol.allowed_folders[0];
579
+ for (const k of PATH_PARAMS[method]) {
580
+ const vals = k === 'paths' ? (Array.isArray(out[k]) ? out[k] : []) : (out[k] === undefined ? [] : [out[k]]);
581
+ for (const v of vals) {
582
+ if (method === 'open_file' && /^https?:\/\//.test(String(v))) continue;
583
+ if (!insideAllowed(String(v), pol)) throw new Error(`Not allowed: ${resolve(String(v))} is outside the folders this computer allows (${pol.allowed_folders.join(', ')}). Nothing changed. ${fix}`);
584
+ }
585
+ }
586
+ return out;
587
+ }
588
+ return params;
589
+ }
590
+ // With backups on, a copy of a file is kept before write_file or edit_block replaces it.
591
+ async function backupBeforeChange(method, params) {
592
+ const pol = loadPolicy();
593
+ if (!pol || !pol.backups || !['write_file', 'edit_block'].includes(method) || (method === 'write_file' && params.append)) return '';
594
+ const p = resolve(String(params.path || ''));
595
+ let st; try { st = await stat(p); } catch { return ''; }
596
+ if (!st.isFile()) return '';
597
+ const day = new Date().toISOString().slice(0, 10);
598
+ const dir = join(CONF_DIR, 'backups', day);
599
+ await mkdir(dir, { recursive: true });
600
+ const dest = join(dir, `${new Date().toISOString().slice(11, 19).replace(/:/g, '')}-${basename(p)}`);
601
+ await cp(p, dest);
602
+ return `\n(backup of the old file: ${dest})`;
603
+ }
604
+
605
+ function policyCli() {
606
+ const sub = args[1], val = args.slice(2).join(' ').trim();
607
+ const p = loadPolicy() || emptyPolicy();
608
+ const show = () => {
609
+ const q = loadPolicy();
610
+ if (!q) { console.log('No safety rules set: the AI can use every folder and run any command (unless you start with --readonly).'); return; }
611
+ console.log(`Allowed folders: ${q.allowed_folders.length ? q.allowed_folders.join(', ') : 'all'}`);
612
+ console.log(`Commands: ${q.commands ? 'on' : 'OFF (file tools only)'}`);
613
+ console.log(`Blocked commands: ${q.blocked_commands.length ? q.blocked_commands.join(', ') : 'none'}`);
614
+ console.log(`Backups before a file is changed: ${q.backups ? `on (${join(CONF_DIR, 'backups')})` : 'off'}`);
615
+ if (q.allowed_folders.length && q.commands) console.log('Note: commands start inside an allowed folder, but a command can still reach other folders. For a strict lock, also run: shellway policy commands off');
616
+ console.log('Rules apply right away; no restart needed.');
617
+ };
618
+ const need = () => { if (!val) { console.error('Missing value. See: shellway policy help'); process.exit(1); } };
619
+ if (!sub || sub === 'show') return show();
620
+ if (sub === 'allow') { need(); const f = resolve(val); if (!existsSync(f)) { console.error(`Folder not found: ${f}`); process.exit(1); } if (!p.allowed_folders.includes(f)) p.allowed_folders.push(f); }
621
+ else if (sub === 'disallow') { need(); const f = resolve(val); p.allowed_folders = p.allowed_folders.filter((x) => x !== f && x !== val); }
622
+ else if (sub === 'block') { need(); if (!p.blocked_commands.includes(val)) p.blocked_commands.push(val); }
623
+ else if (sub === 'unblock') { need(); p.blocked_commands = p.blocked_commands.filter((x) => x !== val); }
624
+ else if (sub === 'block-deletes') { for (const w of DELETE_WORDS) if (!p.blocked_commands.includes(w)) p.blocked_commands.push(w); }
625
+ else if (sub === 'commands' && (val === 'on' || val === 'off')) p.commands = val === 'on';
626
+ else if (sub === 'backups' && (val === 'on' || val === 'off')) p.backups = val === 'on';
627
+ else if (sub === 'reset') { rmSync(POLICY, { force: true }); policyCache = { mtime: -1, value: null }; console.log('Safety rules removed.'); return; }
628
+ else {
629
+ console.log(`shellway policy show the rules
630
+ shellway policy allow <folder> let the AI use only these folders (add one or more)
631
+ shellway policy disallow <folder>
632
+ shellway policy block "<command>" refuse commands containing this word, e.g. "shutdown"
633
+ shellway policy unblock "<command>"
634
+ shellway policy block-deletes block delete commands (rm, del, Remove-Item, format ...)
635
+ shellway policy commands on|off off = file tools only, no commands
636
+ shellway policy backups on|off keep a copy of a file before the AI changes it
637
+ shellway policy reset remove all rules`);
638
+ return;
639
+ }
640
+ savePolicy(p);
641
+ show();
642
+ }
643
+
511
644
  // One entry point for every request from the relay, so it can be tested without a network.
512
645
  async function dispatch(method, params) {
513
646
  if (readonly && writeMethods.has(method)) throw new Error('This computer is in read-only mode');
514
647
  const h = handlers[method];
515
648
  if (!h) throw new Error(`unknown method ${method}`);
516
- return h(params || {});
649
+ const p = checkPolicy(method, params || {});
650
+ const note = await backupBeforeChange(method, p);
651
+ const r = await h(p);
652
+ return note && typeof r === 'string' ? r + note : r;
517
653
  }
518
654
  export { dispatch, writeMethods };
519
655
 
@@ -547,7 +683,7 @@ function start() {
547
683
  connect();
548
684
  }
549
685
 
550
- // ---- auto-start service (systemd user unit / launchd agent / Windows scheduled task) ----
686
+ // ---- auto-start service (systemd user unit / launchd agent / Windows Startup-folder launcher) ----
551
687
  const xml = (v) => String(v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
552
688
  function serviceSpec() {
553
689
  // Copy ourselves to a stable path so the service survives npx cache cleanup.
@@ -557,6 +693,27 @@ function serviceSpec() {
557
693
  }
558
694
  const run = (c, a, opts = {}) => execFileSync(c, a, { stdio: opts.quiet ? 'pipe' : 'inherit', encoding: 'utf8' });
559
695
 
696
+ // Windows auto-start without admin rights: a hidden launcher in the user's Startup folder runs a small
697
+ // loop that restarts the agent after a crash (exit 78 = device removed: stop).
698
+ const winStartup = () => join(process.env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', 'Shellway.vbs');
699
+ const winLoop = () => join(CONF_DIR, 'shellway-agent.cmd');
700
+ function renderWinLoop(argv, home = process.env.SHELLWAY_HOME) {
701
+ const q = (a) => `"${a}"`;
702
+ return ['@echo off', 'rem Shellway agent, kept running in the background. Remove Shellway.vbs from the Startup folder to stop it.',
703
+ ...(home ? [`set "SHELLWAY_HOME=${home}"`] : []),
704
+ ':loop', `${argv.map(q).join(' ')} >> ${q(join(CONF_DIR, 'agent.log'))} 2>&1`,
705
+ 'if %errorlevel%==78 exit /b 78', 'ping -n 11 127.0.0.1 >nul', 'goto loop', ''].join('\r\n');
706
+ }
707
+ function renderWinVbs(loopPath) {
708
+ return `' Starts the Shellway agent hidden at login. Delete this file to stop auto-start.\r\nCreateObject("WScript.Shell").Run """${loopPath}""", 0, False\r\n`;
709
+ }
710
+ const winStopAgents = () => {
711
+ // stop running background agents started from ~/.shellway (not this process)
712
+ const ps = `Get-CimInstance Win32_Process | Where-Object { ($_.Name -eq 'node.exe' -or $_.Name -eq 'cmd.exe') -and $_.CommandLine -like '*${CONF_DIR.replace(/'/g, "''")}*' -and $_.ProcessId -ne ${process.pid} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;
713
+ try { run('powershell', ['-NoProfile', '-Command', ps], { quiet: true }); } catch {}
714
+ };
715
+ export { renderWinLoop, renderWinVbs };
716
+
560
717
  function renderService(os, argv) {
561
718
  const home = process.env.SHELLWAY_HOME ? `Environment=SHELLWAY_HOME=${process.env.SHELLWAY_HOME}\n` : '';
562
719
  if (os === 'linux') return `[Unit]\nDescription=Shellway agent\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\n${home}ExecStart=${argv.map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(' ')}\nRestart=always\nRestartSec=5\nRestartPreventExitStatus=78\n\n[Install]\nWantedBy=default.target\n`;
@@ -573,7 +730,7 @@ function service() {
573
730
  if (!['install', 'uninstall', 'status', 'print'].includes(sub)) {
574
731
  console.log('shellway service install [--readonly] start Shellway automatically at login / boot\nshellway service uninstall\nshellway service status'); return;
575
732
  }
576
- if (sub === 'print') { console.log(renderService(os, argv) ?? '(Windows uses a scheduled task)'); return; }
733
+ if (sub === 'print') { console.log(os === 'win32' ? renderWinLoop(argv) : renderService(os, argv)); return; }
577
734
  if (!['linux', 'darwin', 'win32'].includes(os)) { console.error(`Auto-start is not supported on ${os}. Use: shellway start`); process.exit(1); }
578
735
  if (sub === 'install') {
579
736
  loadConf();
@@ -592,16 +749,23 @@ function service() {
592
749
  try { run('launchctl', ['unload', unitPath], { quiet: true }); } catch {}
593
750
  run('launchctl', ['load', '-w', unitPath]);
594
751
  } else {
595
- const tr = argv.map((a) => `"${a}"`).join(' ');
596
- run('schtasks', ['/Create', '/F', '/SC', 'ONLOGON', '/RL', 'LIMITED', '/TN', 'Shellway', '/TR', tr]);
597
- run('schtasks', ['/Run', '/TN', 'Shellway']);
752
+ try { run('schtasks', ['/Delete', '/F', '/TN', 'Shellway'], { quiet: true }); } catch {} // older versions used a task
753
+ winStopAgents();
754
+ writeFileSync(winLoop(), renderWinLoop(argv));
755
+ mkdirSync(dirname(winStartup()), { recursive: true });
756
+ writeFileSync(winStartup(), renderWinVbs(winLoop()));
757
+ spawn('wscript', [winStartup()], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
758
+ console.log(`Auto-start file: ${winStartup()}`);
598
759
  }
599
760
  console.log(`Done. Shellway now starts automatically${has('readonly') ? ' (read-only)' : ''}. Check: shellway service status`);
600
761
  } else if (sub === 'uninstall') {
601
762
  try {
602
763
  if (os === 'linux') { try { run('systemctl', ['--user', 'disable', '--now', 'shellway.service']); } catch {} rmSync(unitPath, { force: true }); try { run('systemctl', ['--user', 'daemon-reload'], { quiet: true }); } catch {} }
603
764
  else if (os === 'darwin') { try { run('launchctl', ['unload', '-w', unitPath], { quiet: true }); } catch {} rmSync(unitPath, { force: true }); }
604
- else { try { run('schtasks', ['/End', '/TN', 'Shellway'], { quiet: true }); } catch {} run('schtasks', ['/Delete', '/F', '/TN', 'Shellway']); }
765
+ else {
766
+ try { run('schtasks', ['/End', '/TN', 'Shellway'], { quiet: true }); run('schtasks', ['/Delete', '/F', '/TN', 'Shellway'], { quiet: true }); } catch {}
767
+ rmSync(winStartup(), { force: true }); rmSync(winLoop(), { force: true }); winStopAgents();
768
+ }
605
769
  } catch (e) { console.error(e.message); process.exit(1); }
606
770
  rmSync(dest, { force: true });
607
771
  console.log('Auto-start removed. (Your pairing is kept; run "shellway start" to run manually.)');
@@ -609,7 +773,12 @@ function service() {
609
773
  try {
610
774
  if (os === 'linux') run('systemctl', ['--user', 'status', 'shellway.service', '--no-pager', '-n', '5']);
611
775
  else if (os === 'darwin') run('launchctl', ['list', 'com.getshellway.agent']);
612
- else run('schtasks', ['/Query', '/TN', 'Shellway']);
776
+ else {
777
+ if (!existsSync(winStartup())) throw new Error('not installed');
778
+ let n = 0;
779
+ try { n = Number(run('powershell', ['-NoProfile', '-Command', `(Get-CimInstance Win32_Process | Where-Object { $_.Name -eq 'node.exe' -and $_.CommandLine -like '*${CONF_DIR.replace(/'/g, "''")}*agent.mjs*' }).Count`], { quiet: true }).trim()) || 0; } catch {}
780
+ console.log(`Auto-start installed (${winStartup()}). Background agent: ${n > 0 ? 'running' : 'not running - log out and in, or run the install again'}. Log: ${join(CONF_DIR, 'agent.log')}`);
781
+ }
613
782
  } catch { console.log('Auto-start is not installed (or not running).'); }
614
783
  }
615
784
  }
@@ -618,4 +787,5 @@ if (process.env.SHELLWAY_NO_CLI) { /* imported by tests: do not run the command
618
787
  else if (cmd === 'pair') await pair();
619
788
  else if (cmd === 'start') start();
620
789
  else if (cmd === 'service') service();
621
- else console.log('shellway pair <CODE> [--server URL] [--name NAME]\nshellway start [--readonly]\nshellway service install|uninstall|status [--readonly]');
790
+ else if (cmd === 'policy') policyCli();
791
+ else console.log('shellway pair <CODE> [--server URL] [--name NAME]\nshellway start [--readonly]\nshellway service install|uninstall|status [--readonly]\nshellway policy safety rules: allowed folders, blocked commands, backups (shellway policy help)');