relayrunner 0.3.0 → 0.4.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 +22 -4
  2. package/dist/cli.js +386 -172
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -21,14 +21,31 @@ 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.
33
+
34
+ Before it starts a job, `connect` checks the job's runner config: it must hold
35
+ only the files GitHub's do, every server in it must be GitHub's, over https, and
36
+ the runner must be named for that job. Anything else is refused and reported as
37
+ a failed job, so a gateway that was tampered with can't point the runner at a
38
+ server of its own or write files outside the runner. It can't tell a job the
39
+ gateway routed here from a runner it minted on a GitHub repo of its own, so the
40
+ terminal shows which repo each job is from.
41
+
42
+ If another `connect` signs in as this machine while it's online, this one stops
43
+ and says so. When that happens from a different network, the person who
44
+ approved the machine also gets an email, since someone else may have its token.
30
45
 
31
46
  - `--server <url>` or `RELAYRUNNER_URL` points it at another gateway. Changing it signs in again.
47
+ It must be https, except for `localhost` while developing, since the token goes
48
+ out on every connect.
32
49
  - `--name <name>` changes the suggested machine name (default: the hostname).
33
50
  - `--share only-me|anyone` sets who can run jobs on this machine without asking.
34
51
  It works on a machine that's already signed in too.
@@ -149,3 +166,4 @@ shows it too. Exits 1 when not signed in or when the token is no longer valid.
149
166
 
150
167
  `pnpm --filter relayrunner build` bundles the CLI into `dist/cli.js` with
151
168
  tsdown, including the workspace's `@relayrunner/machine-protocol` package.
169
+ Releases go out through changesets; see [.changeset/README.md](../../.changeset/README.md).
package/dist/cli.js CHANGED
@@ -6,11 +6,11 @@ import { z } from "zod";
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 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,124 @@ 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
+ // jit-config.ts
1335
+ const GITHUB_HOSTS = [
1336
+ /^github\.com$/,
1337
+ /\.github\.com$/,
1338
+ /\.githubusercontent\.com$/
1339
+ ];
1340
+ const FILES = [
1341
+ ".runner",
1342
+ ".credentials",
1343
+ ".credentials_rsaparams"
1344
+ ];
1345
+ const URL_FIELDS = /* @__PURE__ */ new Set([
1346
+ "serverurl",
1347
+ "serverurlv2",
1348
+ "githuburl",
1349
+ "authorizationurl"
1350
+ ]);
1351
+ function checkJitConfig(encoded, routeId) {
1352
+ let files;
1353
+ try {
1354
+ files = decodeJson(encoded);
1355
+ if (!files || typeof files !== "object") throw new Error();
1356
+ } catch {
1357
+ return {
1358
+ ok: false,
1359
+ reason: "it isn't a runner config"
1360
+ };
1107
1361
  }
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
1362
+ const names = Object.keys(files);
1363
+ if (names.length !== FILES.length || !FILES.every((name) => names.includes(name))) return {
1364
+ ok: false,
1365
+ reason: `it holds ${names.join(", ") || "nothing"}, not GitHub's files`
1147
1366
  };
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;
1367
+ const decoded = {};
1368
+ for (const [name, value] of Object.entries(files)) {
1369
+ if (typeof value !== "string") return {
1370
+ ok: false,
1371
+ reason: `${name} isn't a file`
1372
+ };
1373
+ try {
1374
+ decoded[name] = decodeJson(value);
1375
+ } catch {
1376
+ return {
1377
+ ok: false,
1378
+ reason: `${name} isn't JSON`
1379
+ };
1181
1380
  }
1182
- throw error;
1183
1381
  }
1184
- const dir = join(root, download.version);
1185
- if (existsSync(join(dir, "run.sh"))) return {
1186
- version: download.version,
1187
- dir
1382
+ const runner = decoded[".runner"];
1383
+ if (!runner || typeof runner !== "object") return {
1384
+ ok: false,
1385
+ reason: "it has no .runner"
1386
+ };
1387
+ const duplicate = duplicateKey(decoded);
1388
+ if (duplicate) return {
1389
+ ok: false,
1390
+ reason: `it has ${duplicate} twice`
1391
+ };
1392
+ for (const url of urls(decoded)) {
1393
+ const parsed = URL.canParse(url) ? new URL(url) : null;
1394
+ if (!parsed) return {
1395
+ ok: false,
1396
+ reason: `it names a URL that doesn't parse: ${url}`
1397
+ };
1398
+ if (parsed.protocol !== "https:" || !GITHUB_HOSTS.some((host) => host.test(parsed.hostname))) return {
1399
+ ok: false,
1400
+ reason: `it points the runner at ${parsed.origin}, not GitHub`
1401
+ };
1402
+ }
1403
+ const field = (key) => {
1404
+ const entry = Object.entries(runner).find(([name]) => name.toLowerCase() === key);
1405
+ return typeof entry?.[1] === "string" ? entry[1] : null;
1406
+ };
1407
+ if (!field("serverurl") && !field("serverurlv2")) return {
1408
+ ok: false,
1409
+ reason: "it doesn't say which GitHub server to use"
1410
+ };
1411
+ const runnerName = field("agentname");
1412
+ if (!runnerName || !isRunnerForRoute(runnerName, routeId)) return {
1413
+ ok: false,
1414
+ reason: `its runner ${runnerName ?? "(no name)"} isn't for job ${routeId}`
1188
1415
  };
1189
- log(`Downloading actions/runner ${download.version}…`);
1190
- await install(root, download);
1191
- log(`Installed actions/runner ${download.version} in ${dir}`);
1192
1416
  return {
1193
- version: download.version,
1194
- dir
1417
+ ok: true,
1418
+ target: target(field("githuburl"))
1195
1419
  };
1196
1420
  }
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;
1421
+ function target(url) {
1422
+ if (!url || !URL.canParse(url)) return null;
1423
+ const path = new URL(url).pathname.split("/").filter(Boolean).slice(0, 2);
1424
+ return path.length ? path.join("/") : null;
1425
+ }
1426
+ function urls(value, found = [], key = "") {
1427
+ if (typeof value === "string") {
1428
+ const text = value.trim();
1429
+ if (text && (URL_FIELDS.has(key.toLowerCase()) || /^[a-z][a-z0-9+.-]*:/i.test(text))) found.push(text);
1430
+ } else if (Array.isArray(value)) for (const item of value) urls(item, found);
1431
+ else if (value && typeof value === "object") for (const [name, item] of Object.entries(value)) urls(item, found, name);
1432
+ return found;
1433
+ }
1434
+ function duplicateKey(value) {
1435
+ if (Array.isArray(value)) for (const item of value) {
1436
+ const found = duplicateKey(item);
1437
+ if (found) return found;
1438
+ }
1439
+ else if (value && typeof value === "object") {
1440
+ const seen = /* @__PURE__ */ new Set();
1441
+ for (const [name, item] of Object.entries(value)) {
1442
+ if (seen.has(name.toLowerCase())) return name;
1443
+ seen.add(name.toLowerCase());
1444
+ const found = duplicateKey(item);
1445
+ if (found) return found;
1229
1446
  }
1230
- } finally {
1231
- rmSync(temp, {
1232
- recursive: true,
1233
- force: true
1234
- });
1235
1447
  }
1448
+ return null;
1236
1449
  }
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
- });
1450
+ function decodeJson(base64) {
1451
+ return JSON.parse(Buffer.from(base64, "base64").toString("utf8").replace(/^/, ""));
1243
1452
  }
1244
1453
  // job.ts
1245
1454
  const runnerEnv = () => Object.fromEntries([
@@ -1265,6 +1474,13 @@ async function runJob(run, options) {
1265
1474
  report(update);
1266
1475
  return update;
1267
1476
  };
1477
+ const checked = checkJitConfig(run.jitConfig, run.routeId);
1478
+ if (!checked.ok) return finish({
1479
+ routeId: run.routeId,
1480
+ state: "failed",
1481
+ message: `Refused the job's runner config: ${checked.reason}.`
1482
+ });
1483
+ options.onChecked?.(checked.target);
1268
1484
  const lock = join(runner.dir, "job.lock");
1269
1485
  if (!takeLock(lock)) return finish({
1270
1486
  routeId: run.routeId,
@@ -1697,8 +1913,12 @@ async function connectMachine(args) {
1697
1913
  },
1698
1914
  runJob: (run, report) => runJob(run, {
1699
1915
  runner,
1700
- report
1916
+ report,
1917
+ onChecked: (target) => {
1918
+ if (target) clack.log.info(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} Job ${run.routeId} is from ${target}`);
1919
+ }
1701
1920
  }),
1921
+ saveToken: (token) => saveRotatedToken(credentials, token),
1702
1922
  onEvent: (event) => {
1703
1923
  if (event.type === "connected") online = true;
1704
1924
  show(event);
@@ -1713,18 +1933,18 @@ async function connectMachine(args) {
1713
1933
  case "revoked":
1714
1934
  deleteCredentials();
1715
1935
  if (!online) {
1716
- clack.log.warn("This machine was removed from the workspace or its token is no longer valid. Signing in again.");
1936
+ 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
1937
  return connectMachine({
1718
1938
  ...args,
1719
1939
  server: credentials.server
1720
1940
  });
1721
1941
  }
1722
- clack.log.error("This machine was removed from the workspace or its token is no longer valid.");
1942
+ 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
1943
  clack.outro("Run `relayrunner connect` again to sign in.");
1724
1944
  process.exitCode = 1;
1725
1945
  break;
1726
1946
  case "replaced":
1727
- clack.log.warn("Another `relayrunner connect` for this machine took over.");
1947
+ 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
1948
  clack.outro("Offline here.");
1729
1949
  process.exitCode = 1;
1730
1950
  break;
@@ -1744,7 +1964,7 @@ async function askSharing(workspace) {
1744
1964
  }, {
1745
1965
  value: "anyone",
1746
1966
  label: `Anyone in ${workspace}`,
1747
- hint: "teammates' and bots' jobs too"
1967
+ hint: "teammates' and bots' jobs too, from repos you can open"
1748
1968
  }],
1749
1969
  initialValue: "only-me"
1750
1970
  });
@@ -1755,11 +1975,11 @@ async function askSharing(workspace) {
1755
1975
  return picked;
1756
1976
  }
1757
1977
  async function applySharing(credentials, choice) {
1758
- const result = await setSharing({
1978
+ const result = await withCurrentToken(credentials, (token) => setSharing({
1759
1979
  server: credentials.server,
1760
- token: credentials.token,
1980
+ token,
1761
1981
  sharing: toSharing(choice)
1762
- });
1982
+ }));
1763
1983
  switch (result.status) {
1764
1984
  case "ok":
1765
1985
  clack.log.info(`Sharing: ${describeSharing(result.sharing, credentials.workspace.name)}`);
@@ -1794,10 +2014,10 @@ const loginCommand = defineCommand({
1794
2014
  const saved = readCredentials();
1795
2015
  const server = serverFor(args.server, saved);
1796
2016
  if (saved && saved.server === server) {
1797
- if ((await whoami({
2017
+ if ((await withCurrentToken(saved, (token) => whoami({
1798
2018
  server,
1799
- token: saved.token
1800
- })).status !== "revoked") {
2019
+ token
2020
+ }))).status !== "revoked") {
1801
2021
  if (share) await applySharing(saved, share);
1802
2022
  clack.outro(`Already signed in as ${saved.machine.name} in ${saved.workspace.name}. Run \`relayrunner connect\` to go online.`);
1803
2023
  return;
@@ -1885,6 +2105,9 @@ function show(event) {
1885
2105
  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.`);
1886
2106
  else clack.log.success(`${at} Resumed${event.by ? ` by ${event.by}` : ""}. Waiting for jobs.`);
1887
2107
  break;
2108
+ case "token-not-saved":
2109
+ clack.log.warn(`${at} Couldn't save the machine's new token (${event.message}). Keeping the old one.`);
2110
+ break;
1888
2111
  case "run-refused":
1889
2112
  clack.log.warn(`${at} Turned down job ${event.routeId}: already running one.`);
1890
2113
  break;
@@ -1931,10 +2154,10 @@ const whoamiCommand = defineCommand({
1931
2154
  machine: credentials.machine,
1932
2155
  workspace: credentials.workspace
1933
2156
  };
1934
- const result = await whoami({
2157
+ const result = await withCurrentToken(credentials, (token) => whoami({
1935
2158
  server: credentials.server,
1936
- token: credentials.token
1937
- });
2159
+ token
2160
+ }));
1938
2161
  switch (result.status) {
1939
2162
  case "ok":
1940
2163
  print(describeIdentity(credentials.server, result.identity), {
@@ -1978,15 +2201,6 @@ function table(title, rows) {
1978
2201
  const width = Math.max(...rows.map(([label]) => label.length));
1979
2202
  return [title, ...rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`)].join("\n");
1980
2203
  }
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
2204
  function pauseCommand(paused) {
1991
2205
  return defineCommand({
1992
2206
  meta: {
@@ -2000,11 +2214,11 @@ function pauseCommand(paused) {
2000
2214
  process.exitCode = 1;
2001
2215
  return;
2002
2216
  }
2003
- const result = await setPaused({
2217
+ const result = await withCurrentToken(credentials, (token) => setPaused({
2004
2218
  server: credentials.server,
2005
- token: credentials.token,
2219
+ token,
2006
2220
  paused
2007
- });
2221
+ }));
2008
2222
  const name = credentials.machine.name;
2009
2223
  switch (result.status) {
2010
2224
  case "ok":
@@ -2051,11 +2265,11 @@ const shareCommand = defineCommand({
2051
2265
  process.exitCode = 1;
2052
2266
  return;
2053
2267
  }
2054
- const result = await setSharing({
2268
+ const result = await withCurrentToken(credentials, (token) => setSharing({
2055
2269
  server: credentials.server,
2056
- token: credentials.token,
2270
+ token,
2057
2271
  sharing: toSharing(choice)
2058
- });
2272
+ }));
2059
2273
  if (result.status === "revoked") return revoked();
2060
2274
  if (result.status === "failed") {
2061
2275
  console.error(`Couldn't change sharing for ${name}: ${result.reason}.`);
@@ -2065,10 +2279,10 @@ const shareCommand = defineCommand({
2065
2279
  console.log(`${name} now ${sharingMeaning(result.sharing, workspace)}.`);
2066
2280
  return;
2067
2281
  }
2068
- const result = await whoami({
2282
+ const result = await withCurrentToken(credentials, (token) => whoami({
2069
2283
  server: credentials.server,
2070
- token: credentials.token
2071
- });
2284
+ token
2285
+ }));
2072
2286
  if (result.status === "revoked") return revoked();
2073
2287
  if (result.status === "unverified") {
2074
2288
  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.4.0",
4
4
  "description": "Run GitHub Actions jobs on your machine through the RelayRunner gateway.",
5
5
  "repository": {
6
6
  "type": "git",