relayrunner 0.3.0 → 0.5.0

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 +29 -6
  2. package/dist/cli.js +562 -199
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -21,15 +21,36 @@ npx relayrunner connect
21
21
 
22
22
  The first run signs you in: it shows a code and opens the dashboard, where you
23
23
  pick the workspace and name for this machine and approve. The machine token is
24
- saved to `~/.relayrunner/machine.json` (mode 0600); later runs reuse it.
24
+ saved to `~/.relayrunner/machine.json` (mode 0600); later runs reuse it. The
25
+ gateway sends a new token every time `connect` comes online and the old one
26
+ stops working, so a copy of `machine.json` from a backup or a synced dotfiles
27
+ folder can't sign in as the machine.
25
28
 
26
29
  While it runs, the machine is online: it keeps a WebSocket open to the gateway,
27
- runs the jobs it's sent (one at a time) and prints what happens. It reconnects
28
- on its own if the connection drops. Ctrl-C takes it offline; a job that's
29
- running stops with it.
30
+ runs the jobs it's sent (one at a time) and prints what happens, including the
31
+ repo each job is from. It reconnects on its own if the connection drops. Ctrl-C
32
+ takes it offline; a job that's running stops with it. Press `p` to pause or
33
+ resume it without going offline (see `relayrunner pause`). The terminal tab's
34
+ title shows the machine and what it's doing, such as
35
+ `RelayRunner · M3P0 · Waiting for jobs`.
36
+
37
+ Before it starts a job, `connect` checks the job's runner config: it must hold
38
+ only the files GitHub's do, every server in it must be GitHub's, over https, and
39
+ the runner must be named for that job. Anything else is refused and reported as
40
+ a failed job, so a gateway that was tampered with can't point the runner at a
41
+ server of its own or write files outside the runner. It can't tell a job the
42
+ gateway routed here from a runner it minted on a GitHub repo of its own, so the
43
+ terminal shows which repo each job is from.
44
+
45
+ If another `connect` signs in as this machine while it's online, this one stops
46
+ and says so. When that happens from a different network, the person who
47
+ approved the machine also gets an email, since someone else may have its token.
30
48
 
31
49
  - `--server <url>` or `RELAYRUNNER_URL` points it at another gateway. Changing it signs in again.
32
- - `--name <name>` changes the suggested machine name (default: the hostname).
50
+ It must be https, except for `localhost` while developing, since the token goes
51
+ out on every connect.
52
+ - `--name <name>` changes the suggested machine name (default: the hostname if
53
+ one is set, otherwise the Mac's Computer Name from System Settings).
33
54
  - `--share only-me|anyone` sets who can run jobs on this machine without asking.
34
55
  It works on a machine that's already signed in too.
35
56
  - If the machine is removed in the dashboard, `connect` deletes the saved token.
@@ -49,7 +70,7 @@ as [`relayrunner init`](#relayrunner-init). No is remembered for that repo in
49
70
  works there. It never asks outside a repo, in a public repo, in a repo that's
50
71
  already set up, or without a terminal to answer.
51
72
 
52
- Jobs run in `actions/runner`, which is downloaded into
73
+ Jobs run in `actions/runner`, GitHub's official self-hosted runner, which is downloaded into
53
74
  `~/.relayrunner/runner/<version>` on first connect and checked against its
54
75
  SHA-256. Set `RELAYRUNNER_HOME` to keep everything somewhere else.
55
76
 
@@ -129,6 +150,7 @@ Pausing stops new jobs routing to this machine while it stays connected and
129
150
  enrolled. A job it's already running finishes. `resume` lets jobs route here
130
151
  again. Anyone in the workspace can do the same from the machine's ⋯ menu on the
131
152
  Runners page, and a running `relayrunner connect` prints when that happens.
153
+ In the terminal running `relayrunner connect`, `p` does the same.
132
154
  Both exit 1 when not signed in or when the token is no longer valid.
133
155
 
134
156
  ## `relayrunner share`
@@ -149,3 +171,4 @@ shows it too. Exits 1 when not signed in or when the token is no longer valid.
149
171
 
150
172
  `pnpm --filter relayrunner build` bundles the CLI into `dist/cli.js` with
151
173
  tsdown, including the workspace's `@relayrunner/machine-protocol` package.
174
+ Releases go out through changesets; see [.changeset/README.md](../../.changeset/README.md).
package/dist/cli.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { arch, cpus, homedir, hostname, platform, totalmem } from "node:os";
3
2
  import * as clack from "@clack/prompts";
4
3
  import { defineCommand, runMain } from "citty";
5
4
  import { z } from "zod";
5
+ import { arch, cpus, homedir, hostname, platform, totalmem } from "node:os";
6
6
  import { basename, dirname, join, resolve } from "node:path";
7
7
  import { chmodSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
8
8
  import { execFile, spawn } from "node:child_process";
9
- import { styleText } from "node:util";
10
- import { Scalar, YAMLSeq, isMap, isScalar, isSeq, parseDocument } from "yaml";
11
9
  import { createHash } from "node:crypto";
12
10
  import { Readable, Transform } from "node:stream";
13
11
  import { pipeline } from "node:stream/promises";
12
+ import { styleText } from "node:util";
13
+ import { Scalar, YAMLSeq, isMap, isScalar, isSeq, parseDocument } from "yaml";
14
14
  const version = z.literal(1);
15
15
  const routeId = z.string().min(1);
16
16
  const DeviceKind = z.enum([
@@ -45,7 +45,8 @@ const HelloMessage = z.object({
45
45
  "arm"
46
46
  ]),
47
47
  runnerVersion: z.string().min(1),
48
- device: Device.optional().catch(void 0)
48
+ device: Device.optional().catch(void 0),
49
+ rotatesToken: z.boolean().optional()
49
50
  });
50
51
  const StatusMessage = z.object({
51
52
  v: version,
@@ -63,10 +64,15 @@ const JobMessage = z.object({
63
64
  ]),
64
65
  message: z.string().optional()
65
66
  });
67
+ const TokenSavedMessage = z.object({
68
+ v: version,
69
+ type: z.literal("token_saved")
70
+ });
66
71
  z.discriminatedUnion("type", [
67
72
  HelloMessage,
68
73
  StatusMessage,
69
- JobMessage
74
+ JobMessage,
75
+ TokenSavedMessage
70
76
  ]);
71
77
  const RunMessage = z.object({
72
78
  v: version,
@@ -86,10 +92,16 @@ const PausedMessage = z.object({
86
92
  paused: z.boolean(),
87
93
  by: z.string().nullable()
88
94
  });
95
+ const TokenMessage = z.object({
96
+ v: version,
97
+ type: z.literal("token"),
98
+ token: z.string().min(1)
99
+ });
89
100
  const GatewayMessage = z.discriminatedUnion("type", [
90
101
  RunMessage,
91
102
  ErrorMessage,
92
- PausedMessage
103
+ PausedMessage,
104
+ TokenMessage
93
105
  ]);
94
106
  function parseGatewayMessage(frame) {
95
107
  return parse(GatewayMessage, frame);
@@ -125,6 +137,11 @@ function parse(schema, frame) {
125
137
  message: result.data
126
138
  };
127
139
  }
140
+ // ../../packages/machine-protocol/src/runner-name.ts
141
+ /** Whether `runnerName` is a machineRunnerName() for `routeId`, whatever the machine is called. */
142
+ function isRunnerForRoute(runnerName, routeId) {
143
+ return runnerName.endsWith(`-${routeId}`);
144
+ }
128
145
  // paths.ts
129
146
  function relayrunnerHome() {
130
147
  return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), ".relayrunner"));
@@ -152,6 +169,7 @@ async function connect(options) {
152
169
  const signal = options.signal;
153
170
  let state = "idle";
154
171
  let socket = null;
172
+ let token = options.token;
155
173
  const pending = [];
156
174
  let gatewayError = "";
157
175
  const send = (message) => {
@@ -163,6 +181,23 @@ async function connect(options) {
163
181
  type: "status",
164
182
  state
165
183
  });
184
+ const saveToken = (next) => {
185
+ if (!options.saveToken) return;
186
+ try {
187
+ options.saveToken(next);
188
+ } catch (error) {
189
+ emit({
190
+ type: "token-not-saved",
191
+ message: error instanceof Error ? error.message : String(error)
192
+ });
193
+ return;
194
+ }
195
+ token = next;
196
+ send({
197
+ v: 1,
198
+ type: "token_saved"
199
+ });
200
+ };
166
201
  const startJob = (run) => {
167
202
  if (state === "busy") {
168
203
  emit({
@@ -206,7 +241,7 @@ async function connect(options) {
206
241
  let opened = false;
207
242
  let heartbeat;
208
243
  const ws = new NodeWebSocket(connectUrl(options.server), { headers: {
209
- authorization: `Bearer ${options.token}`,
244
+ authorization: `Bearer ${token}`,
210
245
  "user-agent": userAgent
211
246
  } });
212
247
  socket = ws;
@@ -231,10 +266,12 @@ async function connect(options) {
231
266
  ws.addEventListener("open", () => {
232
267
  opened = true;
233
268
  emit({ type: "connected" });
269
+ const rotatesToken = options.saveToken ? true : void 0;
234
270
  ws.send(encodeMessage({
235
271
  v: 1,
236
272
  type: "hello",
237
- ...options.hello
273
+ ...options.hello,
274
+ rotatesToken
238
275
  }));
239
276
  sendStatus();
240
277
  for (const message of pending.splice(0)) send(message);
@@ -258,6 +295,7 @@ async function connect(options) {
258
295
  paused: message.paused,
259
296
  by: message.by
260
297
  });
298
+ else if (message.type === "token") saveToken(message.token);
261
299
  else {
262
300
  gatewayError = message.message;
263
301
  emit({
@@ -274,7 +312,7 @@ async function connect(options) {
274
312
  });
275
313
  const tokenRejected = () => fetch(new URL("/api/machines/connect", options.server), {
276
314
  headers: {
277
- authorization: `Bearer ${options.token}`,
315
+ authorization: `Bearer ${token}`,
278
316
  "user-agent": userAgent
279
317
  },
280
318
  signal: AbortSignal.timeout(1e4)
@@ -321,9 +359,175 @@ function delay(ms, signal) {
321
359
  }
322
360
  });
323
361
  }
362
+ // install.ts
363
+ var RunnerError = class extends Error {
364
+ code;
365
+ constructor(code, message) {
366
+ super(message);
367
+ this.code = code;
368
+ }
369
+ };
370
+ const LATEST_RELEASE = "https://api.github.com/repos/actions/runner/releases/latest";
371
+ const ARCHIVE_URL = /^https:\/\/github\.com\/actions\/runner\/releases\/download\/v[\d.]+\/actions-runner-[\w.-]+\.tar\.gz$/;
372
+ const SHA256 = /^[a-f\d]{64}$/;
373
+ const Release = z.object({
374
+ tag_name: z.string().regex(/^v\d+\.\d+\.\d+$/),
375
+ body: z.string().nullish(),
376
+ assets: z.array(z.object({
377
+ name: z.string(),
378
+ browser_download_url: z.string(),
379
+ digest: z.string().nullish()
380
+ }))
381
+ });
382
+ function runnerPlatform() {
383
+ const system = platform();
384
+ const os = system === "darwin" ? "osx" : system;
385
+ const architecture = arch();
386
+ if (os !== "osx" && os !== "linux" || architecture !== "x64" && architecture !== "arm64" || process.getuid?.() === 0) throw new RunnerError("UNSUPPORTED_MACHINE", "Run as a regular user on macOS or Linux (x64 or arm64).");
387
+ return {
388
+ os,
389
+ arch: architecture
390
+ };
391
+ }
392
+ function pickDownload(release, target) {
393
+ const parsed = Release.safeParse(release);
394
+ if (!parsed.success) throw new RunnerError("RUNNER_DOWNLOAD", "GitHub returned an unexpected runner release.");
395
+ const { tag_name, body, assets } = parsed.data;
396
+ const version = tag_name.slice(1);
397
+ const name = `actions-runner-${target.os}-${target.arch}-${version}.tar.gz`;
398
+ const asset = assets.find((item) => item.name === name);
399
+ const key = `${target.os}-${target.arch}`;
400
+ const fromNotes = body?.match(new RegExp(`<!-- BEGIN SHA ${key} -->\\s*([a-fA-F\\d]{64})\\s*<!-- END SHA ${key} -->`))?.[1]?.toLowerCase();
401
+ const fromDigest = asset?.digest?.match(/^sha256:([a-fA-F\d]{64})$/)?.[1]?.toLowerCase();
402
+ const sha256 = fromDigest ?? fromNotes;
403
+ if (!asset || !ARCHIVE_URL.test(asset.browser_download_url) || !sha256 || !SHA256.test(sha256) || fromDigest && fromNotes && fromDigest !== fromNotes) throw new RunnerError("RUNNER_DOWNLOAD", `GitHub did not provide a ${name} archive with a SHA-256 checksum.`);
404
+ return {
405
+ version,
406
+ url: asset.browser_download_url,
407
+ sha256
408
+ };
409
+ }
410
+ async function latestDownload(target) {
411
+ const response = await fetch(LATEST_RELEASE, { headers: {
412
+ accept: "application/vnd.github+json",
413
+ "user-agent": userAgent
414
+ } });
415
+ if (!response.ok) throw new RunnerError("RUNNER_DOWNLOAD", `Could not look up the latest actions/runner release (HTTP ${response.status}).`);
416
+ return pickDownload(await response.json(), target);
417
+ }
418
+ function installedRunners(root = runnersDir()) {
419
+ if (!existsSync(root)) return [];
420
+ return readdirSync(root).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && existsSync(join(root, name, "run.sh"))).sort((a, b) => compareVersions(b, a)).map((version) => ({
421
+ version,
422
+ dir: join(root, version)
423
+ }));
424
+ }
425
+ function compareVersions(a, b) {
426
+ const [x, y] = [a, b].map((v) => v.split(".").map(Number));
427
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
428
+ return 0;
429
+ }
430
+ async function ensureRunner(options = {}) {
431
+ const root = options.root ?? runnersDir();
432
+ const log = options.log ?? (() => {});
433
+ const target = runnerPlatform();
434
+ let download;
435
+ try {
436
+ download = await latestDownload(target);
437
+ } catch (error) {
438
+ const [newest] = installedRunners(root);
439
+ if (newest) {
440
+ log(`Couldn't check for a newer runner (${error.message}). Using ${newest.version}.`);
441
+ return newest;
442
+ }
443
+ throw error;
444
+ }
445
+ const dir = join(root, download.version);
446
+ if (existsSync(join(dir, "run.sh"))) return {
447
+ version: download.version,
448
+ dir
449
+ };
450
+ log(`Downloading GitHub's official runner (actions/runner ${download.version})…`);
451
+ await install(root, download);
452
+ log(`Installed actions/runner ${download.version} in ${dir}`);
453
+ return {
454
+ version: download.version,
455
+ dir
456
+ };
457
+ }
458
+ async function install(root, download, fetcher = fetch) {
459
+ mkdirSync(root, {
460
+ recursive: true,
461
+ mode: 448
462
+ });
463
+ const temp = mkdtempSync(join(root, ".install-"));
464
+ try {
465
+ const archive = join(temp, "runner.tar.gz");
466
+ const response = await fetcher(download.url, {
467
+ headers: { "user-agent": userAgent },
468
+ signal: AbortSignal.timeout(6e5)
469
+ });
470
+ if (!response.ok || !response.body) throw new RunnerError("RUNNER_DOWNLOAD", `Runner download failed (HTTP ${response.status}). Check network access.`);
471
+ const hash = createHash("sha256");
472
+ await pipeline(Readable.fromWeb(response.body), new Transform({ transform(chunk, _encoding, done) {
473
+ hash.update(chunk);
474
+ done(null, chunk);
475
+ } }), createWriteStream(archive, { mode: 384 }));
476
+ if (hash.digest("hex") !== download.sha256) throw new RunnerError("RUNNER_CHECKSUM", "The runner archive failed SHA-256 verification.");
477
+ const unpacked = join(temp, "runner");
478
+ mkdirSync(unpacked, { mode: 448 });
479
+ if (await exitCode("tar", [
480
+ "-xzf",
481
+ archive,
482
+ "-C",
483
+ unpacked
484
+ ]) !== 0) throw new RunnerError("RUNNER_EXTRACT", "Could not unpack the runner archive. Check tar and available disk space.");
485
+ try {
486
+ renameSync(unpacked, join(root, download.version));
487
+ } catch (error) {
488
+ const code = error.code;
489
+ if (code !== "EEXIST" && code !== "ENOTEMPTY") throw error;
490
+ }
491
+ } finally {
492
+ rmSync(temp, {
493
+ recursive: true,
494
+ force: true
495
+ });
496
+ }
497
+ }
498
+ function exitCode(command, args) {
499
+ return new Promise((resolve) => {
500
+ const child = spawn(command, args, { stdio: "ignore" });
501
+ child.once("error", () => resolve(null));
502
+ child.once("exit", (code) => resolve(code));
503
+ });
504
+ }
505
+ // server.ts
506
+ /** The URL's origin. Throws a USAGE RunnerError for anything but https, or http to localhost. */
507
+ function normalizeServer(value) {
508
+ let url;
509
+ try {
510
+ url = new URL(value);
511
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error();
512
+ } catch {
513
+ throw new RunnerError("USAGE", `Not a valid RelayRunner URL: ${value}`);
514
+ }
515
+ if (!sendsTokenSafely(url)) throw new RunnerError("USAGE", `${url.origin} isn't https. RelayRunner only uses plain http for localhost, since the machine token is sent on every connect.`);
516
+ return url.origin;
517
+ }
518
+ /**
519
+ * The machine token goes out on every connect, so plain http is only for a gateway on this
520
+ * computer (local development). Credentials saved for any other http gateway aren't read either.
521
+ */
522
+ function sendsTokenSafely(url) {
523
+ return url.protocol === "https:" || url.protocol === "http:" && isLoopback(url.hostname);
524
+ }
525
+ function isLoopback(hostname) {
526
+ return hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname);
527
+ }
324
528
  // credentials.ts
325
529
  const Credentials = z.object({
326
- server: z.url(),
530
+ server: z.url().refine((server) => sendsTokenSafely(new URL(server))),
327
531
  machine: z.object({
328
532
  id: z.string().min(1),
329
533
  name: z.string()
@@ -367,6 +571,35 @@ function writeCredentials(credentials, path = credentialsPath()) {
367
571
  function deleteCredentials(path = credentialsPath()) {
368
572
  rmSync(path, { force: true });
369
573
  }
574
+ /** Whether two sign-ins are the same machine on the same gateway (the token may differ). */
575
+ function sameMachine(a, b) {
576
+ return a.machine.id === b.machine.id && a.server === b.server;
577
+ }
578
+ /**
579
+ * Calls the gateway with the saved token, and once more with the file's token when it was
580
+ * rejected and has changed since `credentials` was read: a running `connect` rotates the token, so
581
+ * one read just before a rotation goes stale.
582
+ */
583
+ async function withCurrentToken(credentials, call, path = credentialsPath()) {
584
+ const first = await call(credentials.token);
585
+ if (first.status !== "revoked") return first;
586
+ const now = readCredentials(path);
587
+ if (!now || now.token === credentials.token || !sameMachine(now, credentials)) return first;
588
+ return call(now.token);
589
+ }
590
+ /**
591
+ * Saves a token the gateway rotated, for the sign-in `credentials` holds. Throws, saving nothing,
592
+ * when the file now holds another sign-in (`relayrunner login` ran meanwhile) or is gone.
593
+ */
594
+ function saveRotatedToken(credentials, token, path = credentialsPath()) {
595
+ const now = readCredentials(path);
596
+ if (!now) throw new Error("machine.json was removed");
597
+ if (!sameMachine(now, credentials)) throw new Error("machine.json now holds another sign-in");
598
+ writeCredentials({
599
+ ...now,
600
+ token
601
+ }, path);
602
+ }
370
603
  // device.ts
371
604
  const run = (command, args) => new Promise((resolve) => {
372
605
  execFile(command, args, {
@@ -1098,148 +1331,136 @@ function shortFile(file) {
1098
1331
  function colorDiff(diff) {
1099
1332
  return diff.split("\n").map((line) => line.startsWith("+") && !line.startsWith("+++") ? styleText("green", line) : line.startsWith("-") && !line.startsWith("---") ? styleText("red", line) : styleText("dim", line)).join("\n");
1100
1333
  }
1101
- // install.ts
1102
- var RunnerError = class extends Error {
1103
- code;
1104
- constructor(code, message) {
1105
- super(message);
1106
- this.code = code;
1334
+ // machine-name.ts
1335
+ const MAX_LENGTH = 64;
1336
+ async function defaultMachineName(run$1 = run, system = platform(), host = hostname()) {
1337
+ const names = [];
1338
+ if (system === "darwin") for (const key of [
1339
+ "HostName",
1340
+ "ComputerName",
1341
+ "LocalHostName"
1342
+ ]) names.push(await run$1("scutil", ["--get", key]));
1343
+ names.push(host.replace(/\.local$/i, ""));
1344
+ return (names.find((name) => name?.trim()) ?? "").trim().slice(0, MAX_LENGTH);
1345
+ }
1346
+ // jit-config.ts
1347
+ const GITHUB_HOSTS = [
1348
+ /^github\.com$/,
1349
+ /\.github\.com$/,
1350
+ /\.githubusercontent\.com$/
1351
+ ];
1352
+ const FILES = [
1353
+ ".runner",
1354
+ ".credentials",
1355
+ ".credentials_rsaparams"
1356
+ ];
1357
+ const URL_FIELDS = /* @__PURE__ */ new Set([
1358
+ "serverurl",
1359
+ "serverurlv2",
1360
+ "githuburl",
1361
+ "authorizationurl"
1362
+ ]);
1363
+ function checkJitConfig(encoded, routeId) {
1364
+ let files;
1365
+ try {
1366
+ files = decodeJson(encoded);
1367
+ if (!files || typeof files !== "object") throw new Error();
1368
+ } catch {
1369
+ return {
1370
+ ok: false,
1371
+ reason: "it isn't a runner config"
1372
+ };
1107
1373
  }
1108
- };
1109
- const LATEST_RELEASE = "https://api.github.com/repos/actions/runner/releases/latest";
1110
- const ARCHIVE_URL = /^https:\/\/github\.com\/actions\/runner\/releases\/download\/v[\d.]+\/actions-runner-[\w.-]+\.tar\.gz$/;
1111
- const SHA256 = /^[a-f\d]{64}$/;
1112
- const Release = z.object({
1113
- tag_name: z.string().regex(/^v\d+\.\d+\.\d+$/),
1114
- body: z.string().nullish(),
1115
- assets: z.array(z.object({
1116
- name: z.string(),
1117
- browser_download_url: z.string(),
1118
- digest: z.string().nullish()
1119
- }))
1120
- });
1121
- function runnerPlatform() {
1122
- const system = platform();
1123
- const os = system === "darwin" ? "osx" : system;
1124
- const architecture = arch();
1125
- if (os !== "osx" && os !== "linux" || architecture !== "x64" && architecture !== "arm64" || process.getuid?.() === 0) throw new RunnerError("UNSUPPORTED_MACHINE", "Run as a regular user on macOS or Linux (x64 or arm64).");
1126
- return {
1127
- os,
1128
- arch: architecture
1129
- };
1130
- }
1131
- function pickDownload(release, target) {
1132
- const parsed = Release.safeParse(release);
1133
- if (!parsed.success) throw new RunnerError("RUNNER_DOWNLOAD", "GitHub returned an unexpected runner release.");
1134
- const { tag_name, body, assets } = parsed.data;
1135
- const version = tag_name.slice(1);
1136
- const name = `actions-runner-${target.os}-${target.arch}-${version}.tar.gz`;
1137
- const asset = assets.find((item) => item.name === name);
1138
- const key = `${target.os}-${target.arch}`;
1139
- const fromNotes = body?.match(new RegExp(`<!-- BEGIN SHA ${key} -->\\s*([a-fA-F\\d]{64})\\s*<!-- END SHA ${key} -->`))?.[1]?.toLowerCase();
1140
- const fromDigest = asset?.digest?.match(/^sha256:([a-fA-F\d]{64})$/)?.[1]?.toLowerCase();
1141
- const sha256 = fromDigest ?? fromNotes;
1142
- if (!asset || !ARCHIVE_URL.test(asset.browser_download_url) || !sha256 || !SHA256.test(sha256) || fromDigest && fromNotes && fromDigest !== fromNotes) throw new RunnerError("RUNNER_DOWNLOAD", `GitHub did not provide a ${name} archive with a SHA-256 checksum.`);
1143
- return {
1144
- version,
1145
- url: asset.browser_download_url,
1146
- sha256
1374
+ const names = Object.keys(files);
1375
+ if (names.length !== FILES.length || !FILES.every((name) => names.includes(name))) return {
1376
+ ok: false,
1377
+ reason: `it holds ${names.join(", ") || "nothing"}, not GitHub's files`
1147
1378
  };
1148
- }
1149
- async function latestDownload(target) {
1150
- const response = await fetch(LATEST_RELEASE, { headers: {
1151
- accept: "application/vnd.github+json",
1152
- "user-agent": userAgent
1153
- } });
1154
- if (!response.ok) throw new RunnerError("RUNNER_DOWNLOAD", `Could not look up the latest actions/runner release (HTTP ${response.status}).`);
1155
- return pickDownload(await response.json(), target);
1156
- }
1157
- function installedRunners(root = runnersDir()) {
1158
- if (!existsSync(root)) return [];
1159
- return readdirSync(root).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && existsSync(join(root, name, "run.sh"))).sort((a, b) => compareVersions(b, a)).map((version) => ({
1160
- version,
1161
- dir: join(root, version)
1162
- }));
1163
- }
1164
- function compareVersions(a, b) {
1165
- const [x, y] = [a, b].map((v) => v.split(".").map(Number));
1166
- for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
1167
- return 0;
1168
- }
1169
- async function ensureRunner(options = {}) {
1170
- const root = options.root ?? runnersDir();
1171
- const log = options.log ?? (() => {});
1172
- const target = runnerPlatform();
1173
- let download;
1174
- try {
1175
- download = await latestDownload(target);
1176
- } catch (error) {
1177
- const [newest] = installedRunners(root);
1178
- if (newest) {
1179
- log(`Couldn't check for a newer runner (${error.message}). Using ${newest.version}.`);
1180
- return newest;
1379
+ const decoded = {};
1380
+ for (const [name, value] of Object.entries(files)) {
1381
+ if (typeof value !== "string") return {
1382
+ ok: false,
1383
+ reason: `${name} isn't a file`
1384
+ };
1385
+ try {
1386
+ decoded[name] = decodeJson(value);
1387
+ } catch {
1388
+ return {
1389
+ ok: false,
1390
+ reason: `${name} isn't JSON`
1391
+ };
1181
1392
  }
1182
- throw error;
1183
1393
  }
1184
- const dir = join(root, download.version);
1185
- if (existsSync(join(dir, "run.sh"))) return {
1186
- version: download.version,
1187
- dir
1394
+ const runner = decoded[".runner"];
1395
+ if (!runner || typeof runner !== "object") return {
1396
+ ok: false,
1397
+ reason: "it has no .runner"
1398
+ };
1399
+ const duplicate = duplicateKey(decoded);
1400
+ if (duplicate) return {
1401
+ ok: false,
1402
+ reason: `it has ${duplicate} twice`
1403
+ };
1404
+ for (const url of urls(decoded)) {
1405
+ const parsed = URL.canParse(url) ? new URL(url) : null;
1406
+ if (!parsed) return {
1407
+ ok: false,
1408
+ reason: `it names a URL that doesn't parse: ${url}`
1409
+ };
1410
+ if (parsed.protocol !== "https:" || !GITHUB_HOSTS.some((host) => host.test(parsed.hostname))) return {
1411
+ ok: false,
1412
+ reason: `it points the runner at ${parsed.origin}, not GitHub`
1413
+ };
1414
+ }
1415
+ const field = (key) => {
1416
+ const entry = Object.entries(runner).find(([name]) => name.toLowerCase() === key);
1417
+ return typeof entry?.[1] === "string" ? entry[1] : null;
1418
+ };
1419
+ if (!field("serverurl") && !field("serverurlv2")) return {
1420
+ ok: false,
1421
+ reason: "it doesn't say which GitHub server to use"
1422
+ };
1423
+ const runnerName = field("agentname");
1424
+ if (!runnerName || !isRunnerForRoute(runnerName, routeId)) return {
1425
+ ok: false,
1426
+ reason: `its runner ${runnerName ?? "(no name)"} isn't for job ${routeId}`
1188
1427
  };
1189
- log(`Downloading actions/runner ${download.version}…`);
1190
- await install(root, download);
1191
- log(`Installed actions/runner ${download.version} in ${dir}`);
1192
1428
  return {
1193
- version: download.version,
1194
- dir
1429
+ ok: true,
1430
+ target: target(field("githuburl"))
1195
1431
  };
1196
1432
  }
1197
- async function install(root, download, fetcher = fetch) {
1198
- mkdirSync(root, {
1199
- recursive: true,
1200
- mode: 448
1201
- });
1202
- const temp = mkdtempSync(join(root, ".install-"));
1203
- try {
1204
- const archive = join(temp, "runner.tar.gz");
1205
- const response = await fetcher(download.url, {
1206
- headers: { "user-agent": userAgent },
1207
- signal: AbortSignal.timeout(6e5)
1208
- });
1209
- if (!response.ok || !response.body) throw new RunnerError("RUNNER_DOWNLOAD", `Runner download failed (HTTP ${response.status}). Check network access.`);
1210
- const hash = createHash("sha256");
1211
- await pipeline(Readable.fromWeb(response.body), new Transform({ transform(chunk, _encoding, done) {
1212
- hash.update(chunk);
1213
- done(null, chunk);
1214
- } }), createWriteStream(archive, { mode: 384 }));
1215
- if (hash.digest("hex") !== download.sha256) throw new RunnerError("RUNNER_CHECKSUM", "The runner archive failed SHA-256 verification.");
1216
- const unpacked = join(temp, "runner");
1217
- mkdirSync(unpacked, { mode: 448 });
1218
- if (await exitCode("tar", [
1219
- "-xzf",
1220
- archive,
1221
- "-C",
1222
- unpacked
1223
- ]) !== 0) throw new RunnerError("RUNNER_EXTRACT", "Could not unpack the runner archive. Check tar and available disk space.");
1224
- try {
1225
- renameSync(unpacked, join(root, download.version));
1226
- } catch (error) {
1227
- const code = error.code;
1228
- if (code !== "EEXIST" && code !== "ENOTEMPTY") throw error;
1433
+ function target(url) {
1434
+ if (!url || !URL.canParse(url)) return null;
1435
+ const path = new URL(url).pathname.split("/").filter(Boolean).slice(0, 2);
1436
+ return path.length ? path.join("/") : null;
1437
+ }
1438
+ function urls(value, found = [], key = "") {
1439
+ if (typeof value === "string") {
1440
+ const text = value.trim();
1441
+ if (text && (URL_FIELDS.has(key.toLowerCase()) || /^[a-z][a-z0-9+.-]*:/i.test(text))) found.push(text);
1442
+ } else if (Array.isArray(value)) for (const item of value) urls(item, found);
1443
+ else if (value && typeof value === "object") for (const [name, item] of Object.entries(value)) urls(item, found, name);
1444
+ return found;
1445
+ }
1446
+ function duplicateKey(value) {
1447
+ if (Array.isArray(value)) for (const item of value) {
1448
+ const found = duplicateKey(item);
1449
+ if (found) return found;
1450
+ }
1451
+ else if (value && typeof value === "object") {
1452
+ const seen = /* @__PURE__ */ new Set();
1453
+ for (const [name, item] of Object.entries(value)) {
1454
+ if (seen.has(name.toLowerCase())) return name;
1455
+ seen.add(name.toLowerCase());
1456
+ const found = duplicateKey(item);
1457
+ if (found) return found;
1229
1458
  }
1230
- } finally {
1231
- rmSync(temp, {
1232
- recursive: true,
1233
- force: true
1234
- });
1235
1459
  }
1460
+ return null;
1236
1461
  }
1237
- function exitCode(command, args) {
1238
- return new Promise((resolve) => {
1239
- const child = spawn(command, args, { stdio: "ignore" });
1240
- child.once("error", () => resolve(null));
1241
- child.once("exit", (code) => resolve(code));
1242
- });
1462
+ function decodeJson(base64) {
1463
+ return JSON.parse(Buffer.from(base64, "base64").toString("utf8").replace(/^/, ""));
1243
1464
  }
1244
1465
  // job.ts
1245
1466
  const runnerEnv = () => Object.fromEntries([
@@ -1265,6 +1486,13 @@ async function runJob(run, options) {
1265
1486
  report(update);
1266
1487
  return update;
1267
1488
  };
1489
+ const checked = checkJitConfig(run.jitConfig, run.routeId);
1490
+ if (!checked.ok) return finish({
1491
+ routeId: run.routeId,
1492
+ state: "failed",
1493
+ message: `Refused the job's runner config: ${checked.reason}.`
1494
+ });
1495
+ options.onChecked?.(checked.target);
1268
1496
  const lock = join(runner.dir, "job.lock");
1269
1497
  if (!takeLock(lock)) return finish({
1270
1498
  routeId: run.routeId,
@@ -1344,6 +1572,118 @@ function isAlive(pid) {
1344
1572
  return error.code === "EPERM";
1345
1573
  }
1346
1574
  }
1575
+ // live.ts
1576
+ const INITIAL_STATE = {
1577
+ link: "connecting",
1578
+ paused: false,
1579
+ job: null
1580
+ };
1581
+ /** The state after a connection event. */
1582
+ function nextState(state, event) {
1583
+ switch (event.type) {
1584
+ case "connecting": return {
1585
+ ...state,
1586
+ link: state.link === "online" ? "reconnecting" : state.link
1587
+ };
1588
+ case "connected": return {
1589
+ ...state,
1590
+ link: "online"
1591
+ };
1592
+ case "disconnected": return {
1593
+ ...state,
1594
+ link: "reconnecting"
1595
+ };
1596
+ case "run": return {
1597
+ ...state,
1598
+ job: event.routeId
1599
+ };
1600
+ case "job": return event.update.state === "started" || event.update.routeId !== state.job ? state : {
1601
+ ...state,
1602
+ job: null
1603
+ };
1604
+ case "paused": return {
1605
+ ...state,
1606
+ paused: event.paused
1607
+ };
1608
+ default: return state;
1609
+ }
1610
+ }
1611
+ /**
1612
+ * The terminal title for a state, such as "RelayRunner · M3P0 · Waiting for jobs". It leads with
1613
+ * the product so the tab says what's running in it, and ends with the part that changes.
1614
+ */
1615
+ function titleFor(state, machine) {
1616
+ return `RelayRunner · ${machine} · ${statusText(state)}`;
1617
+ }
1618
+ function statusText({ link, paused, job }) {
1619
+ if (link === "connecting") return "Connecting…";
1620
+ if (link === "reconnecting") return job ? "Running a job, reconnecting…" : "Reconnecting…";
1621
+ if (job) return paused ? "Running a job, then paused" : "Running a job";
1622
+ return paused ? "Paused" : "Waiting for jobs";
1623
+ }
1624
+ const ESC = "\x1B";
1625
+ const BEL = "\x07";
1626
+ const SAVE_TITLE = `${ESC}[22;0t`;
1627
+ const RESTORE_TITLE = `${ESC}[23;0t`;
1628
+ function titleSequence(title) {
1629
+ return `${ESC}]0;${title.replace(/[\u0000-\u001f\u007f]/g, "")}${BEL}`;
1630
+ }
1631
+ /** What a key pressed in the terminal asks for. */
1632
+ function keyAction(key) {
1633
+ if (key === "") return "interrupt";
1634
+ if (key === "p" || key === "P") return "toggle-pause";
1635
+ return null;
1636
+ }
1637
+ /**
1638
+ * Starts the live title (when stdout is a terminal) and the keys (when stdin is one): `p` calls
1639
+ * onTogglePause, and Ctrl-C is sent on as SIGINT, since raw mode stops the terminal doing that.
1640
+ */
1641
+ function startLive(options) {
1642
+ const { stdin, stdout } = process;
1643
+ const showTitle = stdout.isTTY;
1644
+ const keys = stdin.isTTY;
1645
+ let state = INITIAL_STATE;
1646
+ let title = titleFor(state, options.machine);
1647
+ let ended = false;
1648
+ if (showTitle) stdout.write(SAVE_TITLE + titleSequence(title));
1649
+ const onKey = (key) => {
1650
+ const action = keyAction(key);
1651
+ if (action === "toggle-pause") options.onTogglePause(state);
1652
+ else if (action === "interrupt") try {
1653
+ process.kill(0, "SIGINT");
1654
+ } catch {
1655
+ process.emit("SIGINT", "SIGINT");
1656
+ }
1657
+ };
1658
+ if (keys) {
1659
+ stdin.setRawMode(true);
1660
+ stdin.setEncoding("utf8");
1661
+ stdin.on("data", onKey);
1662
+ stdin.resume();
1663
+ }
1664
+ return {
1665
+ get state() {
1666
+ return state;
1667
+ },
1668
+ onEvent(event) {
1669
+ if (keys && event.type === "connected" && state.link === "connecting") clack.log.message("Press p to pause or resume, Ctrl-C to go offline.");
1670
+ state = nextState(state, event);
1671
+ const next = titleFor(state, options.machine);
1672
+ if (showTitle && next !== title) stdout.write(titleSequence(next));
1673
+ title = next;
1674
+ },
1675
+ end() {
1676
+ if (ended) return;
1677
+ ended = true;
1678
+ if (showTitle) stdout.write(RESTORE_TITLE);
1679
+ if (keys) {
1680
+ stdin.off("data", onKey);
1681
+ stdin.setRawMode(false);
1682
+ stdin.pause();
1683
+ }
1684
+ }
1685
+ };
1686
+ }
1347
1687
  // login.ts
1348
1688
  const CLIENT_ID = "relayrunner-cli";
1349
1689
  const DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
@@ -1519,6 +1859,14 @@ async function setPaused(options) {
1519
1859
  busy: parsed.data.machine.status?.state === "busy"
1520
1860
  };
1521
1861
  }
1862
+ /** setPaused with the machine's saved token, retrying with a newer one if it was rotated. */
1863
+ function pauseMachine(credentials, paused) {
1864
+ return withCurrentToken(credentials, (token) => setPaused({
1865
+ server: credentials.server,
1866
+ token,
1867
+ paused
1868
+ }));
1869
+ }
1522
1870
  // share.ts
1523
1871
  const SHARE_CHOICES = ["only-me", "anyone"];
1524
1872
  const MachineSharing = z.enum(["only_me", "anyone"]);
@@ -1644,7 +1992,7 @@ const connectCommand = defineCommand({
1644
1992
  },
1645
1993
  name: {
1646
1994
  type: "string",
1647
- description: "Suggested machine name when signing in (default: this computer's hostname)"
1995
+ description: "Suggested machine name when signing in (default: this computer's name)"
1648
1996
  },
1649
1997
  share: {
1650
1998
  type: "string",
@@ -1680,32 +2028,57 @@ async function connectMachine(args) {
1680
2028
  const runner = await ensureRunner({ log: (line) => clack.log.info(line) });
1681
2029
  const device = await detectDevice();
1682
2030
  const stop = new AbortController();
2031
+ const enrolled = credentials;
2032
+ let toggling = false;
2033
+ const live = startLive({
2034
+ machine: enrolled.machine.name,
2035
+ onTogglePause: async ({ paused }) => {
2036
+ if (toggling || stop.signal.aborted) return;
2037
+ toggling = true;
2038
+ const result = await pauseMachine(enrolled, !paused);
2039
+ toggling = false;
2040
+ if (result.status === "failed") clack.log.error(`Couldn't ${paused ? "resume" : "pause"}: ${result.reason}.`);
2041
+ }
2042
+ });
1683
2043
  const onInterrupt = () => {
1684
- if (stop.signal.aborted) process.exit(130);
2044
+ if (stop.signal.aborted) {
2045
+ live.end();
2046
+ process.exit(130);
2047
+ }
1685
2048
  stop.abort();
1686
2049
  };
1687
2050
  process.on("SIGINT", onInterrupt);
1688
2051
  let online = false;
1689
- const end = await connect({
1690
- server: credentials.server,
1691
- token: credentials.token,
1692
- hello: {
1693
- machineId: credentials.machine.id,
1694
- ...platform,
1695
- runnerVersion: runner.version,
1696
- device
1697
- },
1698
- runJob: (run, report) => runJob(run, {
1699
- runner,
1700
- report
1701
- }),
1702
- onEvent: (event) => {
1703
- if (event.type === "connected") online = true;
1704
- show(event);
1705
- },
1706
- signal: stop.signal
1707
- });
1708
- process.off("SIGINT", onInterrupt);
2052
+ let end;
2053
+ try {
2054
+ end = await connect({
2055
+ server: credentials.server,
2056
+ token: credentials.token,
2057
+ hello: {
2058
+ machineId: credentials.machine.id,
2059
+ ...platform,
2060
+ runnerVersion: runner.version,
2061
+ device
2062
+ },
2063
+ runJob: (run, report) => runJob(run, {
2064
+ runner,
2065
+ report,
2066
+ onChecked: (target) => {
2067
+ if (target) clack.log.info(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} Job ${run.routeId} is from ${target}`);
2068
+ }
2069
+ }),
2070
+ saveToken: (token) => saveRotatedToken(credentials, token),
2071
+ onEvent: (event) => {
2072
+ if (event.type === "connected") online = true;
2073
+ show(event);
2074
+ live.onEvent(event);
2075
+ },
2076
+ signal: stop.signal
2077
+ });
2078
+ } finally {
2079
+ live.end();
2080
+ process.off("SIGINT", onInterrupt);
2081
+ }
1709
2082
  switch (end.reason) {
1710
2083
  case "stopped":
1711
2084
  clack.outro("Offline.");
@@ -1713,18 +2086,18 @@ async function connectMachine(args) {
1713
2086
  case "revoked":
1714
2087
  deleteCredentials();
1715
2088
  if (!online) {
1716
- clack.log.warn("This machine was removed from the workspace or its token is no longer valid. Signing in again.");
2089
+ clack.log.warn("This machine was removed from the workspace or its token is no longer valid. If you didn't remove it, another copy of its token may have signed in elsewhere: check the Runners page. Signing in again.");
1717
2090
  return connectMachine({
1718
2091
  ...args,
1719
2092
  server: credentials.server
1720
2093
  });
1721
2094
  }
1722
- clack.log.error("This machine was removed from the workspace or its token is no longer valid.");
2095
+ clack.log.error("This machine was removed from the workspace or its token is no longer valid. If you didn't remove it, another copy of its token may have signed in elsewhere: check the Runners page and revoke it if so.");
1723
2096
  clack.outro("Run `relayrunner connect` again to sign in.");
1724
2097
  process.exitCode = 1;
1725
2098
  break;
1726
2099
  case "replaced":
1727
- clack.log.warn("Another `relayrunner connect` for this machine took over.");
2100
+ clack.log.warn(["Another `relayrunner connect` signed in as this machine and took over.", `If that wasn't you, someone has this machine's token: revoke it at ${credentials.server}/runners, then run \`relayrunner connect\` to sign in again.`].join("\n"));
1728
2101
  clack.outro("Offline here.");
1729
2102
  process.exitCode = 1;
1730
2103
  break;
@@ -1744,7 +2117,7 @@ async function askSharing(workspace) {
1744
2117
  }, {
1745
2118
  value: "anyone",
1746
2119
  label: `Anyone in ${workspace}`,
1747
- hint: "teammates' and bots' jobs too"
2120
+ hint: "teammates' and bots' jobs too, from repos you can open"
1748
2121
  }],
1749
2122
  initialValue: "only-me"
1750
2123
  });
@@ -1755,11 +2128,11 @@ async function askSharing(workspace) {
1755
2128
  return picked;
1756
2129
  }
1757
2130
  async function applySharing(credentials, choice) {
1758
- const result = await setSharing({
2131
+ const result = await withCurrentToken(credentials, (token) => setSharing({
1759
2132
  server: credentials.server,
1760
- token: credentials.token,
2133
+ token,
1761
2134
  sharing: toSharing(choice)
1762
- });
2135
+ }));
1763
2136
  switch (result.status) {
1764
2137
  case "ok":
1765
2138
  clack.log.info(`Sharing: ${describeSharing(result.sharing, credentials.workspace.name)}`);
@@ -1780,7 +2153,7 @@ const loginCommand = defineCommand({
1780
2153
  },
1781
2154
  name: {
1782
2155
  type: "string",
1783
- description: "Suggested machine name (default: this computer's hostname)"
2156
+ description: "Suggested machine name (default: this computer's name)"
1784
2157
  },
1785
2158
  share: {
1786
2159
  type: "string",
@@ -1794,10 +2167,10 @@ const loginCommand = defineCommand({
1794
2167
  const saved = readCredentials();
1795
2168
  const server = serverFor(args.server, saved);
1796
2169
  if (saved && saved.server === server) {
1797
- if ((await whoami({
2170
+ if ((await withCurrentToken(saved, (token) => whoami({
1798
2171
  server,
1799
- token: saved.token
1800
- })).status !== "revoked") {
2172
+ token
2173
+ }))).status !== "revoked") {
1801
2174
  if (share) await applySharing(saved, share);
1802
2175
  clack.outro(`Already signed in as ${saved.machine.name} in ${saved.workspace.name}. Run \`relayrunner connect\` to go online.`);
1803
2176
  return;
@@ -1831,7 +2204,7 @@ function machinePlatform() {
1831
2204
  }
1832
2205
  /** Signs in through the browser, saves the machine token, and settles who can run jobs here. */
1833
2206
  async function enroll(server, name, platform, share) {
1834
- const signedIn = await signIn(server, name || hostname(), platform);
2207
+ const signedIn = await signIn(server, name || await defaultMachineName(), platform);
1835
2208
  const credentials = signedIn.credentials;
1836
2209
  writeCredentials(credentials);
1837
2210
  clack.log.success(`Enrolled as ${credentials.machine.name} in ${credentials.workspace.name}. Token saved to ${credentialsPath()}.`);
@@ -1882,9 +2255,12 @@ function show(event) {
1882
2255
  clack.log.step(`${at} Starting job ${event.routeId}`);
1883
2256
  break;
1884
2257
  case "paused":
1885
- if (event.paused) clack.log.warn(`${at} Paused${event.by ? ` by ${event.by}` : ""}. Staying online, but new jobs skip this machine until it's resumed.`);
2258
+ if (event.paused) clack.log.warn(`${at} Paused${event.by ? ` by ${event.by}` : ""}. Staying online, but new jobs skip this machine until it's resumed.${process.stdin.isTTY ? " Press p to resume." : ""}`);
1886
2259
  else clack.log.success(`${at} Resumed${event.by ? ` by ${event.by}` : ""}. Waiting for jobs.`);
1887
2260
  break;
2261
+ case "token-not-saved":
2262
+ clack.log.warn(`${at} Couldn't save the machine's new token (${event.message}). Keeping the old one.`);
2263
+ break;
1888
2264
  case "run-refused":
1889
2265
  clack.log.warn(`${at} Turned down job ${event.routeId}: already running one.`);
1890
2266
  break;
@@ -1931,10 +2307,10 @@ const whoamiCommand = defineCommand({
1931
2307
  machine: credentials.machine,
1932
2308
  workspace: credentials.workspace
1933
2309
  };
1934
- const result = await whoami({
2310
+ const result = await withCurrentToken(credentials, (token) => whoami({
1935
2311
  server: credentials.server,
1936
- token: credentials.token
1937
- });
2312
+ token
2313
+ }));
1938
2314
  switch (result.status) {
1939
2315
  case "ok":
1940
2316
  print(describeIdentity(credentials.server, result.identity), {
@@ -1978,15 +2354,6 @@ function table(title, rows) {
1978
2354
  const width = Math.max(...rows.map(([label]) => label.length));
1979
2355
  return [title, ...rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`)].join("\n");
1980
2356
  }
1981
- function normalizeServer(value) {
1982
- try {
1983
- const url = new URL(value);
1984
- if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error();
1985
- return url.origin;
1986
- } catch {
1987
- throw new RunnerError("USAGE", `Not a valid RelayRunner URL: ${value}`);
1988
- }
1989
- }
1990
2357
  function pauseCommand(paused) {
1991
2358
  return defineCommand({
1992
2359
  meta: {
@@ -2000,11 +2367,7 @@ function pauseCommand(paused) {
2000
2367
  process.exitCode = 1;
2001
2368
  return;
2002
2369
  }
2003
- const result = await setPaused({
2004
- server: credentials.server,
2005
- token: credentials.token,
2006
- paused
2007
- });
2370
+ const result = await pauseMachine(credentials, paused);
2008
2371
  const name = credentials.machine.name;
2009
2372
  switch (result.status) {
2010
2373
  case "ok":
@@ -2051,11 +2414,11 @@ const shareCommand = defineCommand({
2051
2414
  process.exitCode = 1;
2052
2415
  return;
2053
2416
  }
2054
- const result = await setSharing({
2417
+ const result = await withCurrentToken(credentials, (token) => setSharing({
2055
2418
  server: credentials.server,
2056
- token: credentials.token,
2419
+ token,
2057
2420
  sharing: toSharing(choice)
2058
- });
2421
+ }));
2059
2422
  if (result.status === "revoked") return revoked();
2060
2423
  if (result.status === "failed") {
2061
2424
  console.error(`Couldn't change sharing for ${name}: ${result.reason}.`);
@@ -2065,10 +2428,10 @@ const shareCommand = defineCommand({
2065
2428
  console.log(`${name} now ${sharingMeaning(result.sharing, workspace)}.`);
2066
2429
  return;
2067
2430
  }
2068
- const result = await whoami({
2431
+ const result = await withCurrentToken(credentials, (token) => whoami({
2069
2432
  server: credentials.server,
2070
- token: credentials.token
2071
- });
2433
+ token
2434
+ }));
2072
2435
  if (result.status === "revoked") return revoked();
2073
2436
  if (result.status === "unverified") {
2074
2437
  console.error(`Couldn't check sharing for ${name}: ${result.reason}.`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "relayrunner",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Run GitHub Actions jobs on your machine through the RelayRunner gateway.",
5
5
  "repository": {
6
6
  "type": "git",