getzopu 0.5.0 → 0.5.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.
package/README.md CHANGED
@@ -64,8 +64,9 @@ it has no credential — a page to sign in to, a six-digit code to type there
64
64
  in `~/.config/zopu/machine/credential.json` (mode `0600`), and then installs the satellite as a
65
65
  service of your account and starts it, so the computer stays reachable with every window closed
66
66
  and after a restart: a launch agent on macOS (`~/Library/LaunchAgents/zopu-machines-<hash>.plist`),
67
- a systemd user unit on Linux (`~/.config/systemd/user/`, with `loginctl enable-linger` asked for).
68
- No root. The service runs a copy of this program kept under `~/.config/zopu/machine/`, with the
67
+ a systemd user unit on Linux (`~/.config/systemd/user/`, with `loginctl enable-linger` asked for),
68
+ a scheduled task on Windows (a hidden launcher hosts the program; it runs while you are signed in).
69
+ No administrator rights. The service runs a copy of this program kept under `~/.config/zopu/machine/`, with the
69
70
  runtime that ran `connect`, and writes to `satellite.log` there; it is restarted only when it
70
71
  crashes — a revoked or deliberately stopped satellite stays stopped. The service's name carries a
71
72
  hash of the machine's home, so a second Zopu on one computer never displaces the first. The shape
@@ -76,7 +77,7 @@ The satellite (`packages/machines/src/satellite/`) dials out to `/ws/machines` w
76
77
  as a bearer, comes back by itself after a drop (at once the first time, then on a ladder from 1 s
77
78
  to 30 s), and keeps a journal of every command it ran (`~/.config/zopu/machine/journal/`), so a
78
79
  command that outlives a drop is picked up where it was. Commands run as the user, in a process
79
- group of their own; nothing is scoped. `getzopu machines status` says whether the link is up, how
80
+ group of their own; nothing is scoped. On Windows the command runs in cmd.exe with no console window, and a stop ends its whole process tree. `getzopu machines status` says whether the link is up, how
80
81
  the service is, and the last lines of its log; `getzopu machines disconnect` stops and removes the
81
82
  service, revokes the computer on the server, and forgets the credential.
82
83
 
package/dist/getzopu.mjs CHANGED
@@ -362,7 +362,7 @@ var exports_machine = {};
362
362
  __export(exports_machine, {
363
363
  runMachine: () => runMachine
364
364
  });
365
- import { spawn as spawn3, spawnSync } from "node:child_process";
365
+ import { spawn as spawn3, spawnSync as spawnSync2 } from "node:child_process";
366
366
  import {
367
367
  chmodSync,
368
368
  lstatSync,
@@ -413,7 +413,7 @@ var SSHD_PATH = "/usr/sbin/sshd", AUTHORIZED_KEY_ENV = "SSH_AUTHORIZED_KEY", SSH
413
413
  chmodSync(authorizedKeys, 384);
414
414
  prepareCacheTree();
415
415
  mkdirSync("/run/sshd", { recursive: true });
416
- const hostKeys = spawnSync("ssh-keygen", ["-A"], { stdio: "inherit" });
416
+ const hostKeys = spawnSync2("ssh-keygen", ["-A"], { stdio: "inherit" });
417
417
  if (hostKeys.error !== undefined) {
418
418
  throw new BootstrapError(`cannot run ssh-keygen: ${hostKeys.error.message}`);
419
419
  }
@@ -26411,6 +26411,7 @@ ${result3.text.slice(0, 4000)}` : "";
26411
26411
 
26412
26412
  // src/machines.ts
26413
26413
  import { spawn as spawn2 } from "node:child_process";
26414
+ import { appendFileSync as appendFileSync2 } from "node:fs";
26414
26415
  import { copyFile, mkdir as mkdir4, readFile as readFile3, stat as stat3, writeFile as writeFile4 } from "node:fs/promises";
26415
26416
  import { hostname as hostname2, platform as platform2 } from "node:os";
26416
26417
  import path4 from "node:path";
@@ -26831,6 +26832,7 @@ var servicePath = (runtime, installerPath) => [
26831
26832
  ].filter((directory) => directory !== ""))
26832
26833
  ].join(path2.delimiter);
26833
26834
  var systemctl = (args2) => ask("systemctl", ["--user", ...args2]);
26835
+ var schtasks = (args2) => ask("schtasks", args2);
26834
26836
  var execute = (command, args2) => () => new Promise((resolve3, reject) => {
26835
26837
  execFile(command, [...args2], { encoding: "utf-8", timeout: 20000 }, (error, stdout, stderr) => {
26836
26838
  if (error) {
@@ -26995,6 +26997,113 @@ var systemd = (plan) => {
26995
26997
  ]
26996
26998
  };
26997
26999
  };
27000
+ var writeUtf16 = (file, text) => exports_Effect.tryPromise({
27001
+ catch: (cause) => new ServiceCommandError({ code: null, command: `write ${file}`, stderr: String(cause) }),
27002
+ try: async () => {
27003
+ await fs.mkdir(path2.dirname(file), { recursive: true });
27004
+ await fs.writeFile(file, Buffer.concat([Buffer.from([255, 254]), Buffer.from(text, "utf16le")]));
27005
+ }
27006
+ });
27007
+ var vbs = (value4) => value4.replaceAll('"', '""');
27008
+ var renderLauncher = (plan, options) => [
27009
+ "' Zopu machines: the satellite, hidden. Written by `getzopu machines connect`; edited by nothing.",
27010
+ 'Set sh = CreateObject("WScript.Shell")',
27011
+ 'Set env = sh.Environment("PROCESS")',
27012
+ `env("PATH") = "${vbs(plan.path)}"`,
27013
+ `env("ZOPU_MACHINE_LOG") = "${vbs(options.logFile)}"`,
27014
+ ...Object.entries(plan.env).map(([key, value4]) => `env("${vbs(key)}") = "${vbs(value4)}"`),
27015
+ `code = sh.Run("${vbs(plan.program.map((word) => `"${word}"`).join(" "))}", 0, True)`,
27016
+ "WScript.Quit code",
27017
+ ""
27018
+ ].join(`\r
27019
+ `);
27020
+ var renderTask = (options) => {
27021
+ const wscript = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\wscript.exe`;
27022
+ return [
27023
+ '<?xml version="1.0" encoding="UTF-16"?>',
27024
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
27025
+ " <RegistrationInfo>",
27026
+ " <Description>Zopu machines — this computer, reachable by your threads</Description>",
27027
+ " </RegistrationInfo>",
27028
+ " <Triggers>",
27029
+ " <LogonTrigger>",
27030
+ " <Enabled>true</Enabled>",
27031
+ ` <UserId>${xml2(options.user)}</UserId>`,
27032
+ " </LogonTrigger>",
27033
+ " </Triggers>",
27034
+ " <Principals>",
27035
+ ' <Principal id="Author">',
27036
+ ` <UserId>${xml2(options.user)}</UserId>`,
27037
+ " <LogonType>InteractiveToken</LogonType>",
27038
+ " <RunLevel>LeastPrivilege</RunLevel>",
27039
+ " </Principal>",
27040
+ " </Principals>",
27041
+ " <Settings>",
27042
+ " <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>",
27043
+ " <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>",
27044
+ " <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>",
27045
+ " <AllowHardTerminate>true</AllowHardTerminate>",
27046
+ " <StartWhenAvailable>true</StartWhenAvailable>",
27047
+ " <Hidden>true</Hidden>",
27048
+ " <Enabled>true</Enabled>",
27049
+ " <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>",
27050
+ " <RestartOnFailure>",
27051
+ " <Interval>PT1M</Interval>",
27052
+ " <Count>999</Count>",
27053
+ " </RestartOnFailure>",
27054
+ " </Settings>",
27055
+ ' <Actions Context="Author">',
27056
+ " <Exec>",
27057
+ ` <Command>${xml2(wscript)}</Command>`,
27058
+ ` <Arguments>//B &quot;${xml2(options.launcher)}&quot;</Arguments>`,
27059
+ " </Exec>",
27060
+ " </Actions>",
27061
+ "</Task>",
27062
+ ""
27063
+ ].join(`\r
27064
+ `);
27065
+ };
27066
+ var windows = (plan) => {
27067
+ const name = plan.label;
27068
+ const taskFile = path2.join(plan.home, "zopu-machines.task.xml");
27069
+ const launcher = path2.join(plan.home, "zopu-machines.vbs");
27070
+ const state = () => ask("powershell", [
27071
+ "-NoProfile",
27072
+ "-NonInteractive",
27073
+ "-Command",
27074
+ `(Get-ScheduledTask -TaskName '${name.replaceAll("'", "''")}' -ErrorAction SilentlyContinue).State`
27075
+ ]);
27076
+ const user = process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${process.env.USERNAME ?? userInfo().username}` : process.env.USERNAME ?? userInfo().username;
27077
+ return {
27078
+ file: taskFile,
27079
+ install: [
27080
+ writeFile2(launcher, renderLauncher(plan, { logFile: plan.logFile })),
27081
+ writeUtf16(taskFile, renderTask({ launcher, user })),
27082
+ schtasks(["/Create", "/TN", name, "/XML", taskFile, "/F"]),
27083
+ schtasks(["/Run", "/TN", name])
27084
+ ],
27085
+ status: exports_Effect.gen(function* status() {
27086
+ const installed = yield* fileExists(taskFile);
27087
+ const shown = yield* exports_Effect.result(state());
27088
+ const running = !exports_Result.isFailure(shown) && /\bRunning\b/u.test(shown.success);
27089
+ let pid = null;
27090
+ if (running) {
27091
+ const held = yield* exports_Effect.result(exports_Effect.promise(() => fs.readFile(path2.join(plan.home, "state.json"), "utf-8")));
27092
+ if (!exports_Result.isFailure(held)) {
27093
+ const parsed = JSON.parse(held.success);
27094
+ pid = typeof parsed.pid === "number" ? parsed.pid : null;
27095
+ }
27096
+ }
27097
+ return { installed, linger: "yes", pid, running };
27098
+ }),
27099
+ uninstall: [
27100
+ attempt("schtasks", ["/End", "/TN", name]),
27101
+ attempt("schtasks", ["/Delete", "/TN", name, "/F"]),
27102
+ exports_Effect.asVoid(removeFile(taskFile)),
27103
+ exports_Effect.asVoid(removeFile(launcher))
27104
+ ]
27105
+ };
27106
+ };
26998
27107
  var serviceManager = (plan, platform = process.platform) => {
26999
27108
  if (platform === "darwin") {
27000
27109
  return exports_Effect.succeed(launchd(plan));
@@ -27002,10 +27111,13 @@ var serviceManager = (plan, platform = process.platform) => {
27002
27111
  if (platform === "linux") {
27003
27112
  return exports_Effect.succeed(systemd(plan));
27004
27113
  }
27114
+ if (platform === "win32") {
27115
+ return exports_Effect.succeed(windows(plan));
27116
+ }
27005
27117
  return exports_Effect.fail(new ServiceCommandError({
27006
27118
  code: null,
27007
27119
  command: "install the background service",
27008
- stderr: "The background service is available on macOS and Linux; on other systems run connect with --foreground."
27120
+ stderr: "The background service is available on macOS, Linux and Windows; on other systems run connect with --foreground."
27009
27121
  }));
27010
27122
  };
27011
27123
  var installService = (plan, platform) => exports_Effect.gen(function* install() {
@@ -27029,7 +27141,7 @@ var serviceStatus = (plan, platform) => exports_Effect.gen(function* status() {
27029
27141
  return yield* manager.success.status;
27030
27142
  });
27031
27143
  // ../../packages/machines/src/satellite/commands.ts
27032
- import { spawn } from "node:child_process";
27144
+ import { spawn, spawnSync } from "node:child_process";
27033
27145
  import { homedir as homedir3 } from "node:os";
27034
27146
  import { StringDecoder } from "node:string_decoder";
27035
27147
  var BATCH_MS = 50;
@@ -27074,10 +27186,19 @@ var flushAllOutput = (command, writer) => {
27074
27186
  }
27075
27187
  };
27076
27188
  var signalCommand = (child, signal) => {
27077
- const group = child.pid === undefined ? undefined : child.pid * -1;
27078
- if (group === undefined) {
27189
+ if (child.pid === undefined) {
27079
27190
  return;
27080
27191
  }
27192
+ if (process.platform === "win32") {
27193
+ try {
27194
+ spawnSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], {
27195
+ stdio: "ignore",
27196
+ windowsHide: true
27197
+ });
27198
+ } catch {}
27199
+ return;
27200
+ }
27201
+ const group = child.pid * -1;
27081
27202
  try {
27082
27203
  process.kill(group, signal);
27083
27204
  } catch {}
@@ -27167,7 +27288,8 @@ class Commands {
27167
27288
  detached: true,
27168
27289
  env: { ...process.env, ...request3.env },
27169
27290
  shell: true,
27170
- stdio: ["ignore", "pipe", "pipe"]
27291
+ stdio: ["ignore", "pipe", "pipe"],
27292
+ windowsHide: true
27171
27293
  });
27172
27294
  } catch (error) {
27173
27295
  const message = error instanceof Error ? error.message : "Could not start.";
@@ -27425,7 +27547,7 @@ var expand = (target) => {
27425
27547
  if (target === "~") {
27426
27548
  return homedir4();
27427
27549
  }
27428
- if (target.startsWith("~/")) {
27550
+ if (target.startsWith("~/") || target.startsWith("~\\")) {
27429
27551
  return nodePath.join(homedir4(), target.slice(2));
27430
27552
  }
27431
27553
  return target;
@@ -27825,9 +27947,24 @@ var serverUrl = (override) => {
27825
27947
  return parsed.origin;
27826
27948
  };
27827
27949
  var openBrowser = (url) => {
27828
- const [command, args2] = platform2() === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
27950
+ const here = platform2();
27951
+ let command = "xdg-open";
27952
+ let args2 = [url];
27953
+ if (here === "darwin") {
27954
+ command = "open";
27955
+ }
27956
+ if (here === "win32") {
27957
+ command = "rundll32";
27958
+ args2 = ["url.dll,FileProtocolHandler", url];
27959
+ }
27829
27960
  try {
27830
- spawn2(command, args2, { detached: true, stdio: "ignore" }).unref();
27961
+ const opened = spawn2(command, args2, {
27962
+ detached: true,
27963
+ stdio: "ignore",
27964
+ windowsHide: true
27965
+ });
27966
+ opened.on("error", () => null);
27967
+ opened.unref();
27831
27968
  } catch {}
27832
27969
  };
27833
27970
  var refusal = (reason, url) => {
@@ -27895,9 +28032,17 @@ var STATE_FILE = path4.join(HOME, "state.json");
27895
28032
  var PLAN_FILE = path4.join(HOME, "service.json");
27896
28033
  var writeState = async (link2) => {
27897
28034
  await mkdir4(HOME, { recursive: true });
27898
- const state = { at: Date.now(), link: link2 };
28035
+ const state = { at: Date.now(), link: link2, pid: process.pid };
27899
28036
  await writeFile4(STATE_FILE, JSON.stringify(state));
27900
28037
  };
28038
+ var SERVICE_LOG = process.env.ZOPU_MACHINE_LOG;
28039
+ var say = (line2) => {
28040
+ console.log(line2);
28041
+ if (SERVICE_LOG) {
28042
+ appendFileSync2(SERVICE_LOG, `${line2}
28043
+ `);
28044
+ }
28045
+ };
27901
28046
  var readState = async () => {
27902
28047
  try {
27903
28048
  return JSON.parse(await readFile3(STATE_FILE, "utf-8"));
@@ -27935,7 +28080,7 @@ var run2 = async () => {
27935
28080
  const end2 = await exports_Effect.runPromise(runSatellite({
27936
28081
  credential: credential2.credential,
27937
28082
  journalDir: journalDir(),
27938
- log: (line2) => console.log(line2),
28083
+ log: say,
27939
28084
  name: credential2.name || `${hostname2()} (${platform2()})`,
27940
28085
  serverUrl: credential2.serverUrl,
27941
28086
  signal: controller.signal,
@@ -27956,7 +28101,7 @@ var run2 = async () => {
27956
28101
  };
27957
28102
  var bundlePath = async () => {
27958
28103
  const file = import.meta.filename ?? "";
27959
- if (!file.endsWith("/dist/getzopu.mjs")) {
28104
+ if (path4.basename(file) !== "getzopu.mjs" || path4.basename(path4.dirname(file)) !== "dist") {
27960
28105
  throw new Error("The background service needs the published program (npx getzopu …). Run with --foreground from a source checkout.");
27961
28106
  }
27962
28107
  await stat3(file);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "getzopu",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Zopu CLI: projects, threads, and connecting your own computer to Zopu.",
5
5
  "license": "UNLICENSED",
6
6
  "bin": {