@omarestrella/panes 0.1.2 → 0.1.3

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 (3) hide show
  1. package/README.md +10 -0
  2. package/package.json +1 -1
  3. package/panes.js +172 -51
package/README.md CHANGED
@@ -18,4 +18,14 @@ This server is separate from any other Rex server on the machine. Its sessions a
18
18
 
19
19
  It runs in the foreground. Ctrl-C stops it, and your groups are still there next time.
20
20
 
21
+ To keep it running in the background instead:
22
+
23
+ ```sh
24
+ npx @omarestrella/panes daemon start # start it, and wait until it's ready
25
+ npx @omarestrella/panes daemon status # is it running, and at what address
26
+ npx @omarestrella/panes daemon stop # stop it
27
+ ```
28
+
29
+ `daemon start` shows the same steps, including the Tailscale link the first time, then leaves the server running after you close the terminal. Rex runs it (`rex server start`) on the server's own socket, so it doesn't touch your regular Rex server, and keeps its log: `daemon status` prints the command to read it. `daemon stop` and `daemon status` find the server by `--hostname`, so pass the one you started it with. It doesn't start again after a restart; run `daemon start` again.
30
+
21
31
  MIT licensed. Panes isn't affiliated with Superlogical, who make Rex.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omarestrella/panes",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Runs a Rex server for the Panes browser extension, reachable over your tailnet.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/panes.js CHANGED
@@ -12,19 +12,26 @@ var ids_default = {
12
12
  };
13
13
 
14
14
  // src/product.ts
15
- var VERSION = "0.1.2";
15
+ var VERSION = "0.1.3";
16
16
  var EXTENSION_IDS = [ids_default.dev, ids_default.store].filter((x) => typeof x === "string" && x.length === 32);
17
17
 
18
18
  // src/server/cli.ts
19
19
  var HELP = `panes ${VERSION}: run a Rex server for the Panes browser extension
20
20
 
21
- Usage: npx @omarestrella/panes [options]
21
+ Usage:
22
+ npx @omarestrella/panes [options] run the server in this terminal
23
+ npx @omarestrella/panes daemon start [options] run it in the background
24
+ npx @omarestrella/panes daemon stop [options] stop it
25
+ npx @omarestrella/panes daemon status [options] show whether it's running, and its address
22
26
 
27
+ Options:
23
28
  --hostname NAME the server's device name on your tailnet (default: panes)
24
- --state-dir DIR where the server keeps its sessions and Tailscale identity
29
+ --state-dir DIR where the server keeps its sessions, Tailscale identity and log
25
30
  (default: ${defaultStateDir("panes")})
26
31
  --extension-id ID also allow this extension ID (repeatable)
27
32
  -h, --help show this help
33
+
34
+ daemon stop and status find the server by --hostname, so pass the one you started it with.
28
35
  `;
29
36
  function defaultStateDir(hostname) {
30
37
  const home = os.homedir();
@@ -36,13 +43,19 @@ function fail(message) {
36
43
  process.exit(1);
37
44
  }
38
45
  var args = process.argv.slice(2);
46
+ var command = "run";
39
47
  var HOSTNAME = "panes";
40
48
  var STATE = null;
41
49
  var ids = [...EXTENSION_IDS];
42
50
  for (let i = 0;i < args.length; i++) {
43
51
  const a = args[i];
44
52
  const value = () => args[++i] ?? fail(`${a} needs a value`);
45
- if (a === "-h" || a === "--help") {
53
+ if (a === "daemon") {
54
+ const sub = args[++i];
55
+ if (sub !== "start" && sub !== "stop" && sub !== "status")
56
+ fail(`daemon takes start, stop or status${sub ? `, not ${sub}` : ""} (see --help)`);
57
+ command = sub;
58
+ } else if (a === "-h" || a === "--help") {
46
59
  process.stdout.write(HELP);
47
60
  process.exit(0);
48
61
  } else if (a === "--hostname")
@@ -63,23 +76,97 @@ if (process.platform === "win32")
63
76
  fail("Windows isn't supported yet");
64
77
  var STATE_DIR = STATE ?? defaultStateDir(HOSTNAME);
65
78
  var SOCKET = path.join(process.env.XDG_RUNTIME_DIR || os.tmpdir(), `panes-server-${HOSTNAME}.sock`);
79
+ var SELF = "npx @omarestrella/panes";
80
+ var sameServer = HOSTNAME === "panes" ? "" : ` --hostname ${HOSTNAME}`;
81
+ var SERVER_OPTS = ["--state-dir", STATE_DIR, "--tailscale", "--tailscale-hostname", HOSTNAME, ...[...new Set(ids)].flatMap((id) => ["--websocket-origin-pattern", id])];
82
+ var NO_REX = "rex isn't installed, or isn't on your PATH. Install Rex first: https://www.superlogical.com/rex/";
83
+ function rexAt(...cmd) {
84
+ const r = spawnSync("rex", ["-S", `unix://${SOCKET}`, "--autostart=false", ...cmd], { encoding: "utf8" });
85
+ if (r.error)
86
+ fail(r.error.code === "ENOENT" ? NO_REX : `couldn't run rex: ${r.error.message}`);
87
+ return r;
88
+ }
89
+ function status() {
90
+ const r = rexAt("server", "status", "--json");
91
+ if (r.status !== 0)
92
+ return null;
93
+ try {
94
+ return JSON.parse(r.stdout);
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+ var READY = /tailnet https listener ready.*url=https:\/\/(\S+)/;
100
+ var LOGIN = /https:\/\/login\.tailscale\.com\/\S+/;
101
+ function addressFromLog() {
102
+ const lines = `${rexAt("server", "logs", "--state-dir", STATE_DIR, "-n", "2000").stdout}`.split(`
103
+ `);
104
+ let address = null;
105
+ for (const l of lines) {
106
+ if (/Rex server ready/.test(l))
107
+ address = null;
108
+ const m = l.match(READY);
109
+ if (m)
110
+ address = m[1];
111
+ }
112
+ return address;
113
+ }
114
+ if (command === "status") {
115
+ const s = status();
116
+ if (!s) {
117
+ console.log(`The Panes server isn't running. Start it with: ${SELF} daemon start${sameServer}`);
118
+ process.exit(3);
119
+ }
120
+ const ts = s.tailscale ?? {};
121
+ const address = ts.state === "needs_login" ? null : addressFromLog();
122
+ console.log(`The Panes server is running (pid ${s.pid}, since ${new Date(s.started_at).toLocaleString()}).`);
123
+ if (ts.state === "needs_login")
124
+ console.log(` waiting for Tailscale approval: ${ts.auth_url ?? "see its log"}`);
125
+ else if (address)
126
+ console.log(` address: ${address}`);
127
+ else
128
+ console.log(` tailnet: ${ts.state ?? "unknown"}${ts.https?.state ? `, certificate ${ts.https.state}` : ""}`);
129
+ console.log(` state: ${STATE_DIR}`);
130
+ console.log(` log: rex -S unix://${SOCKET} server logs --state-dir ${JSON.stringify(STATE_DIR)}`);
131
+ process.exit(0);
132
+ }
133
+ if (command === "stop") {
134
+ if (!status()) {
135
+ console.log("The Panes server isn't running.");
136
+ process.exit(0);
137
+ }
138
+ const r = rexAt("server", "stop");
139
+ if (r.status !== 0)
140
+ fail(`couldn't stop the server: ${`${r.stderr}${r.stdout}`.trim()}`);
141
+ console.log("Stopped the Panes server. Its groups are kept for next time.");
142
+ process.exit(0);
143
+ }
144
+ var already = status();
145
+ if (already) {
146
+ if (command === "start") {
147
+ const address = addressFromLog();
148
+ console.log(`The Panes server is already running (pid ${already.pid})${address ? ` at ${address}` : ""}. See: ${SELF} daemon status${sameServer}`);
149
+ process.exit(0);
150
+ }
151
+ fail(`the Panes server is already running (pid ${already.pid}). Stop it with: ${SELF} daemon stop${sameServer}`);
152
+ }
66
153
  var probe = spawnSync("rex", ["server", "run", "--help"], { encoding: "utf8" });
67
154
  if (probe.error)
68
- fail(probe.error.code === "ENOENT" ? "rex isn't installed, or isn't on your PATH. Install Rex first: https://www.superlogical.com/rex/" : `couldn't run rex: ${probe.error.message}`);
155
+ fail(probe.error.code === "ENOENT" ? NO_REX : `couldn't run rex: ${probe.error.message}`);
69
156
  if (!`${probe.stdout}${probe.stderr}`.includes("--websocket-origin-pattern"))
70
157
  fail("this Rex is too old for Panes. Update Rex to 1.0.1 or newer.");
71
158
  var tty = process.stdout.isTTY && !process.env.NO_COLOR;
72
159
  var out = (s) => process.stdout.write(s);
73
160
  var RAINBOW = [196, 202, 208, 214, 220, 226, 190, 154, 118, 82, 46, 48, 50, 51, 45, 39, 33, 27, 57, 93, 129, 165, 201, 199];
74
161
  var ART = [
75
- "╭─────────────╮",
76
- "│ ● ● ● │",
77
- "├──────┬──────┤",
78
- "│░░░░░░│▒▒▒▒▒▒│",
79
- "│░░░░░░│▒▒▒▒▒▒│",
80
- "│░░░░░░│▒▒▒▒▒▒│",
81
- "│░░░░░░│▒▒▒▒▒▒│",
82
- "╰──────┴──────╯"
162
+ "╭───────────────────────╮",
163
+ "│ ● ● ● │",
164
+ "├───────────┬───────────┤",
165
+ "│░░░░░░░░░░░│▒▒▒▒▒▒▒▒▒▒▒│",
166
+ "│░░░░░░░░░░░│▒▒▒▒▒▒▒▒▒▒▒│",
167
+ "│░░░░░░░░░░░│▒▒▒▒▒▒▒▒▒▒▒│",
168
+ "│░░░░░░░░░░░│▒▒▒▒▒▒▒▒▒▒▒│",
169
+ "╰───────────┴───────────╯"
83
170
  ];
84
171
  var BESIDE = ["", "", "", "\x1B[1mPanes\x1B[0m server", "\x1B[2ma Rex server just for Panes\x1B[0m", "", "", ""];
85
172
  var dim = (s) => tty ? `\x1B[2m${s}\x1B[0m` : s;
@@ -146,32 +233,22 @@ line();
146
233
  line(` This runs a Rex server just for Panes, apart from any other Rex`);
147
234
  line(` server on this machine. It keeps its own sessions, and listens on`);
148
235
  line(` nothing but your tailnet, as a device named ${bold(HOSTNAME)}.`);
236
+ if (command === "start")
237
+ line(` It runs in the background, and keeps running after you close this.`);
149
238
  line();
150
- fs.mkdirSync(STATE_DIR, { recursive: true, mode: 448 });
151
- var rex = spawn("rex", [
152
- "server",
153
- "run",
154
- "--listen",
155
- `unix://${SOCKET}`,
156
- "--state-dir",
157
- STATE_DIR,
158
- "--tailscale",
159
- "--tailscale-hostname",
160
- HOSTNAME,
161
- ...[...new Set(ids)].flatMap((id) => ["--websocket-origin-pattern", id])
162
- ], { stdio: ["ignore", "pipe", "pipe"] });
163
- step("Starting the Rex server…");
164
239
  var phase = "starting";
240
+ var follower = null;
165
241
  var finish = () => {
166
242
  if (animation)
167
243
  clearInterval(animation);
168
244
  if (tty && spinning !== null)
169
245
  out("\r\x1B[2K");
170
246
  spinning = null;
247
+ follower?.kill();
171
248
  };
172
249
  function onLog(l) {
173
- const login = l.match(/https:\/\/login\.tailscale\.com\/\S+/);
174
- const ready = l.match(/tailnet https listener ready.*url=https:\/\/(\S+)/);
250
+ const login = l.match(LOGIN);
251
+ const ready = l.match(READY);
175
252
  if (phase === "starting" && /Rex server ready/.test(l)) {
176
253
  done("Rex server started");
177
254
  phase = "joining";
@@ -199,34 +276,78 @@ function onLog(l) {
199
276
  line(` ${bold(ready[1])}`);
200
277
  line(` Each computer you use Panes on must be on this tailnet.`);
201
278
  line();
279
+ if (command === "start") {
280
+ line(dim(` It keeps running in the background. Check on it or stop it with:`));
281
+ line(dim(` ${SELF} daemon status${sameServer}`));
282
+ line(dim(` ${SELF} daemon stop${sameServer}`));
283
+ process.exit(0);
284
+ }
202
285
  line(dim(` Ctrl-C stops the server. Its groups are kept for next time, in`));
203
286
  line(dim(` ${STATE_DIR}`));
204
287
  } else if (/\bERROR\b/.test(l)) {
205
288
  line(dim(` ${l.replace(/^\S+ \S+ /, "").slice(0, (process.stdout.columns || 80) - 6)}`));
206
289
  }
207
290
  }
208
- var buf = "";
209
- var read = (chunk) => {
210
- buf += chunk.toString();
211
- for (let i = buf.indexOf(`
291
+ function lines(stream, keep = () => true) {
292
+ let buf = "";
293
+ stream.on("data", (chunk) => {
294
+ buf += chunk.toString();
295
+ for (let i = buf.indexOf(`
212
296
  `);i >= 0; i = buf.indexOf(`
213
297
  `)) {
214
- onLog(buf.slice(0, i));
215
- buf = buf.slice(i + 1);
298
+ const l = buf.slice(0, i);
299
+ buf = buf.slice(i + 1);
300
+ if (keep(l))
301
+ onLog(l);
302
+ }
303
+ });
304
+ }
305
+ fs.mkdirSync(STATE_DIR, { recursive: true, mode: 448 });
306
+ step("Starting the Rex server…");
307
+ if (command === "run") {
308
+ const rex = spawn("rex", ["server", "run", "--listen", `unix://${SOCKET}`, ...SERVER_OPTS], { stdio: ["ignore", "pipe", "pipe"] });
309
+ rex.on("error", (e) => {
310
+ finish();
311
+ done(`couldn't start rex: ${e.message}`, "✗");
312
+ process.exit(1);
313
+ });
314
+ lines(rex.stdout);
315
+ lines(rex.stderr);
316
+ rex.on("exit", (code) => {
317
+ finish();
318
+ if (phase !== "ready" || code)
319
+ line(` The Rex server stopped${code ? ` (exit code ${code})` : ""}.`);
320
+ process.exit(code ?? 0);
321
+ });
322
+ for (const sig of ["SIGINT", "SIGTERM"])
323
+ process.on(sig, () => rex.kill("SIGTERM"));
324
+ } else {
325
+ const since = Math.floor(Date.now() / 1000) * 1000;
326
+ const started = rexAt("server", "start", ...SERVER_OPTS, "--json");
327
+ if (started.status !== 0) {
328
+ finish();
329
+ done(`couldn't start the server: ${`${started.stderr}${started.stdout}`.trim()}`, "✗");
330
+ process.exit(1);
216
331
  }
217
- };
218
- rex.stdout.on("data", read);
219
- rex.stderr.on("data", read);
220
- rex.on("error", (e) => {
221
- finish();
222
- done(`couldn't start rex: ${e.message}`, "✗");
223
- process.exit(1);
224
- });
225
- rex.on("exit", (code) => {
226
- finish();
227
- if (phase !== "ready" || code)
228
- line(` The Rex server stopped${code ? ` (exit code ${code})` : ""}.`);
229
- process.exit(code ?? 0);
230
- });
231
- for (const sig of ["SIGINT", "SIGTERM"])
232
- process.on(sig, () => rex.kill("SIGTERM"));
332
+ const fresh = (l) => {
333
+ const m = l.match(/^(\d{4})\/(\d\d)\/(\d\d) (\d\d):(\d\d):(\d\d)/);
334
+ return !m || new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]).getTime() >= since;
335
+ };
336
+ follower = spawn("rex", ["-S", `unix://${SOCKET}`, "--autostart=false", "server", "logs", "--follow", "--state-dir", STATE_DIR, "-n", "500"], { stdio: ["ignore", "pipe", "pipe"] });
337
+ lines(follower.stdout, fresh);
338
+ setInterval(() => {
339
+ if (status())
340
+ return;
341
+ finish();
342
+ done("The Rex server stopped while starting", "✗");
343
+ line(dim(` Its log: rex -S unix://${SOCKET} server logs --state-dir ${JSON.stringify(STATE_DIR)}`));
344
+ process.exit(1);
345
+ }, 2000);
346
+ process.on("SIGINT", () => {
347
+ finish();
348
+ line();
349
+ line(` The server keeps starting in the background.`);
350
+ line(` Check on it with: ${SELF} daemon status${sameServer}`);
351
+ process.exit(0);
352
+ });
353
+ }