relayrunner 0.2.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.
- package/README.md +111 -6
- package/dist/cli.js +1309 -100
- package/package.json +2 -1
package/dist/cli.js
CHANGED
|
@@ -1,16 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { arch, homedir, hostname, platform } from "node:os";
|
|
2
|
+
import { arch, cpus, homedir, hostname, platform, totalmem } from "node:os";
|
|
3
3
|
import * as clack from "@clack/prompts";
|
|
4
4
|
import { defineCommand, runMain } from "citty";
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import { join, resolve } from "node:path";
|
|
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
|
-
import { spawn } from "node:child_process";
|
|
8
|
+
import { execFile, spawn } from "node:child_process";
|
|
9
9
|
import { createHash } from "node:crypto";
|
|
10
10
|
import { Readable, Transform } from "node:stream";
|
|
11
11
|
import { pipeline } from "node:stream/promises";
|
|
12
|
+
import { styleText } from "node:util";
|
|
13
|
+
import { Scalar, YAMLSeq, isMap, isScalar, isSeq, parseDocument } from "yaml";
|
|
12
14
|
const version = z.literal(1);
|
|
13
15
|
const routeId = z.string().min(1);
|
|
16
|
+
const DeviceKind = z.enum([
|
|
17
|
+
"laptop",
|
|
18
|
+
"desktop",
|
|
19
|
+
"server",
|
|
20
|
+
"vm",
|
|
21
|
+
"unknown"
|
|
22
|
+
]);
|
|
23
|
+
const text = z.string().trim().min(1).max(120);
|
|
24
|
+
const Device = z.object({
|
|
25
|
+
kind: DeviceKind,
|
|
26
|
+
model: text.optional(),
|
|
27
|
+
modelId: text.optional(),
|
|
28
|
+
chip: text.optional(),
|
|
29
|
+
cpuCores: z.number().int().positive().max(1e5).optional(),
|
|
30
|
+
memoryMb: z.number().int().positive().max(1e9).optional(),
|
|
31
|
+
osVersion: text.optional()
|
|
32
|
+
});
|
|
14
33
|
const HelloMessage = z.object({
|
|
15
34
|
v: version,
|
|
16
35
|
type: z.literal("hello"),
|
|
@@ -25,7 +44,9 @@ const HelloMessage = z.object({
|
|
|
25
44
|
"arm64",
|
|
26
45
|
"arm"
|
|
27
46
|
]),
|
|
28
|
-
runnerVersion: z.string().min(1)
|
|
47
|
+
runnerVersion: z.string().min(1),
|
|
48
|
+
device: Device.optional().catch(void 0),
|
|
49
|
+
rotatesToken: z.boolean().optional()
|
|
29
50
|
});
|
|
30
51
|
const StatusMessage = z.object({
|
|
31
52
|
v: version,
|
|
@@ -43,10 +64,15 @@ const JobMessage = z.object({
|
|
|
43
64
|
]),
|
|
44
65
|
message: z.string().optional()
|
|
45
66
|
});
|
|
67
|
+
const TokenSavedMessage = z.object({
|
|
68
|
+
v: version,
|
|
69
|
+
type: z.literal("token_saved")
|
|
70
|
+
});
|
|
46
71
|
z.discriminatedUnion("type", [
|
|
47
72
|
HelloMessage,
|
|
48
73
|
StatusMessage,
|
|
49
|
-
JobMessage
|
|
74
|
+
JobMessage,
|
|
75
|
+
TokenSavedMessage
|
|
50
76
|
]);
|
|
51
77
|
const RunMessage = z.object({
|
|
52
78
|
v: version,
|
|
@@ -66,10 +92,16 @@ const PausedMessage = z.object({
|
|
|
66
92
|
paused: z.boolean(),
|
|
67
93
|
by: z.string().nullable()
|
|
68
94
|
});
|
|
95
|
+
const TokenMessage = z.object({
|
|
96
|
+
v: version,
|
|
97
|
+
type: z.literal("token"),
|
|
98
|
+
token: z.string().min(1)
|
|
99
|
+
});
|
|
69
100
|
const GatewayMessage = z.discriminatedUnion("type", [
|
|
70
101
|
RunMessage,
|
|
71
102
|
ErrorMessage,
|
|
72
|
-
PausedMessage
|
|
103
|
+
PausedMessage,
|
|
104
|
+
TokenMessage
|
|
73
105
|
]);
|
|
74
106
|
function parseGatewayMessage(frame) {
|
|
75
107
|
return parse(GatewayMessage, frame);
|
|
@@ -105,6 +137,11 @@ function parse(schema, frame) {
|
|
|
105
137
|
message: result.data
|
|
106
138
|
};
|
|
107
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
|
+
}
|
|
108
145
|
// paths.ts
|
|
109
146
|
function relayrunnerHome() {
|
|
110
147
|
return resolve(process.env.RELAYRUNNER_HOME || join(homedir(), ".relayrunner"));
|
|
@@ -132,6 +169,7 @@ async function connect(options) {
|
|
|
132
169
|
const signal = options.signal;
|
|
133
170
|
let state = "idle";
|
|
134
171
|
let socket = null;
|
|
172
|
+
let token = options.token;
|
|
135
173
|
const pending = [];
|
|
136
174
|
let gatewayError = "";
|
|
137
175
|
const send = (message) => {
|
|
@@ -143,6 +181,23 @@ async function connect(options) {
|
|
|
143
181
|
type: "status",
|
|
144
182
|
state
|
|
145
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
|
+
};
|
|
146
201
|
const startJob = (run) => {
|
|
147
202
|
if (state === "busy") {
|
|
148
203
|
emit({
|
|
@@ -186,7 +241,7 @@ async function connect(options) {
|
|
|
186
241
|
let opened = false;
|
|
187
242
|
let heartbeat;
|
|
188
243
|
const ws = new NodeWebSocket(connectUrl(options.server), { headers: {
|
|
189
|
-
authorization: `Bearer ${
|
|
244
|
+
authorization: `Bearer ${token}`,
|
|
190
245
|
"user-agent": userAgent
|
|
191
246
|
} });
|
|
192
247
|
socket = ws;
|
|
@@ -211,10 +266,12 @@ async function connect(options) {
|
|
|
211
266
|
ws.addEventListener("open", () => {
|
|
212
267
|
opened = true;
|
|
213
268
|
emit({ type: "connected" });
|
|
269
|
+
const rotatesToken = options.saveToken ? true : void 0;
|
|
214
270
|
ws.send(encodeMessage({
|
|
215
271
|
v: 1,
|
|
216
272
|
type: "hello",
|
|
217
|
-
...options.hello
|
|
273
|
+
...options.hello,
|
|
274
|
+
rotatesToken
|
|
218
275
|
}));
|
|
219
276
|
sendStatus();
|
|
220
277
|
for (const message of pending.splice(0)) send(message);
|
|
@@ -238,6 +295,7 @@ async function connect(options) {
|
|
|
238
295
|
paused: message.paused,
|
|
239
296
|
by: message.by
|
|
240
297
|
});
|
|
298
|
+
else if (message.type === "token") saveToken(message.token);
|
|
241
299
|
else {
|
|
242
300
|
gatewayError = message.message;
|
|
243
301
|
emit({
|
|
@@ -254,7 +312,7 @@ async function connect(options) {
|
|
|
254
312
|
});
|
|
255
313
|
const tokenRejected = () => fetch(new URL("/api/machines/connect", options.server), {
|
|
256
314
|
headers: {
|
|
257
|
-
authorization: `Bearer ${
|
|
315
|
+
authorization: `Bearer ${token}`,
|
|
258
316
|
"user-agent": userAgent
|
|
259
317
|
},
|
|
260
318
|
signal: AbortSignal.timeout(1e4)
|
|
@@ -301,52 +359,6 @@ function delay(ms, signal) {
|
|
|
301
359
|
}
|
|
302
360
|
});
|
|
303
361
|
}
|
|
304
|
-
// credentials.ts
|
|
305
|
-
const Credentials = z.object({
|
|
306
|
-
server: z.url(),
|
|
307
|
-
machine: z.object({
|
|
308
|
-
id: z.string().min(1),
|
|
309
|
-
name: z.string()
|
|
310
|
-
}),
|
|
311
|
-
workspace: z.object({
|
|
312
|
-
id: z.string().min(1),
|
|
313
|
-
name: z.string(),
|
|
314
|
-
slug: z.string().nullish()
|
|
315
|
-
}),
|
|
316
|
-
token: z.string().min(1)
|
|
317
|
-
});
|
|
318
|
-
function credentialsPath(home = relayrunnerHome()) {
|
|
319
|
-
return join(home, "machine.json");
|
|
320
|
-
}
|
|
321
|
-
function readCredentials(path = credentialsPath()) {
|
|
322
|
-
let text;
|
|
323
|
-
try {
|
|
324
|
-
text = readFileSync(path, "utf8");
|
|
325
|
-
} catch (error) {
|
|
326
|
-
if (error.code === "ENOENT") return null;
|
|
327
|
-
throw error;
|
|
328
|
-
}
|
|
329
|
-
try {
|
|
330
|
-
const parsed = Credentials.safeParse(JSON.parse(text));
|
|
331
|
-
return parsed.success ? parsed.data : null;
|
|
332
|
-
} catch {
|
|
333
|
-
return null;
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
function writeCredentials(credentials, path = credentialsPath()) {
|
|
337
|
-
const dir = join(path, "..");
|
|
338
|
-
mkdirSync(dir, {
|
|
339
|
-
recursive: true,
|
|
340
|
-
mode: 448
|
|
341
|
-
});
|
|
342
|
-
const temp = `${path}.${process.pid}.tmp`;
|
|
343
|
-
writeFileSync(temp, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 384 });
|
|
344
|
-
chmodSync(temp, 384);
|
|
345
|
-
renameSync(temp, path);
|
|
346
|
-
}
|
|
347
|
-
function deleteCredentials(path = credentialsPath()) {
|
|
348
|
-
rmSync(path, { force: true });
|
|
349
|
-
}
|
|
350
362
|
// install.ts
|
|
351
363
|
var RunnerError = class extends Error {
|
|
352
364
|
code;
|
|
@@ -490,6 +502,954 @@ function exitCode(command, args) {
|
|
|
490
502
|
child.once("exit", (code) => resolve(code));
|
|
491
503
|
});
|
|
492
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
|
+
}
|
|
528
|
+
// credentials.ts
|
|
529
|
+
const Credentials = z.object({
|
|
530
|
+
server: z.url().refine((server) => sendsTokenSafely(new URL(server))),
|
|
531
|
+
machine: z.object({
|
|
532
|
+
id: z.string().min(1),
|
|
533
|
+
name: z.string()
|
|
534
|
+
}),
|
|
535
|
+
workspace: z.object({
|
|
536
|
+
id: z.string().min(1),
|
|
537
|
+
name: z.string(),
|
|
538
|
+
slug: z.string().nullish()
|
|
539
|
+
}),
|
|
540
|
+
token: z.string().min(1)
|
|
541
|
+
});
|
|
542
|
+
function credentialsPath(home = relayrunnerHome()) {
|
|
543
|
+
return join(home, "machine.json");
|
|
544
|
+
}
|
|
545
|
+
function readCredentials(path = credentialsPath()) {
|
|
546
|
+
let text;
|
|
547
|
+
try {
|
|
548
|
+
text = readFileSync(path, "utf8");
|
|
549
|
+
} catch (error) {
|
|
550
|
+
if (error.code === "ENOENT") return null;
|
|
551
|
+
throw error;
|
|
552
|
+
}
|
|
553
|
+
try {
|
|
554
|
+
const parsed = Credentials.safeParse(JSON.parse(text));
|
|
555
|
+
return parsed.success ? parsed.data : null;
|
|
556
|
+
} catch {
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
function writeCredentials(credentials, path = credentialsPath()) {
|
|
561
|
+
const dir = join(path, "..");
|
|
562
|
+
mkdirSync(dir, {
|
|
563
|
+
recursive: true,
|
|
564
|
+
mode: 448
|
|
565
|
+
});
|
|
566
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
567
|
+
writeFileSync(temp, `${JSON.stringify(credentials, null, 2)}\n`, { mode: 384 });
|
|
568
|
+
chmodSync(temp, 384);
|
|
569
|
+
renameSync(temp, path);
|
|
570
|
+
}
|
|
571
|
+
function deleteCredentials(path = credentialsPath()) {
|
|
572
|
+
rmSync(path, { force: true });
|
|
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
|
+
}
|
|
603
|
+
// device.ts
|
|
604
|
+
const run = (command, args) => new Promise((resolve) => {
|
|
605
|
+
execFile(command, args, {
|
|
606
|
+
timeout: 3e3,
|
|
607
|
+
encoding: "utf8"
|
|
608
|
+
}, (error, stdout) => {
|
|
609
|
+
resolve(error ? null : stdout.trim() || null);
|
|
610
|
+
});
|
|
611
|
+
});
|
|
612
|
+
const read$1 = (path) => {
|
|
613
|
+
try {
|
|
614
|
+
return readFileSync(path, "utf8").replaceAll("\0", "").trim() || null;
|
|
615
|
+
} catch {
|
|
616
|
+
return null;
|
|
617
|
+
}
|
|
618
|
+
};
|
|
619
|
+
function defaultSources() {
|
|
620
|
+
const list = cpus();
|
|
621
|
+
return {
|
|
622
|
+
run,
|
|
623
|
+
read: read$1,
|
|
624
|
+
cpuModel: list[0]?.model,
|
|
625
|
+
cpuCount: list.length,
|
|
626
|
+
totalMemory: totalmem()
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
/** This machine's device, or undefined on a platform it can't read. Never throws. */
|
|
630
|
+
async function detectDevice(sources = defaultSources()) {
|
|
631
|
+
try {
|
|
632
|
+
const system = platform();
|
|
633
|
+
const found = system === "darwin" ? await macDevice(sources) : system === "linux" ? await linuxDevice(sources) : void 0;
|
|
634
|
+
return found && compact(found);
|
|
635
|
+
} catch {
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
/** The specs every platform reads the same way. */
|
|
640
|
+
function commonSpecs(sources) {
|
|
641
|
+
return {
|
|
642
|
+
chip: cleanChip(sources.cpuModel),
|
|
643
|
+
cpuCores: sources.cpuCount > 0 ? sources.cpuCount : void 0,
|
|
644
|
+
memoryMb: sources.totalMemory > 0 ? Math.round(sources.totalMemory / 1024 / 1024) : void 0
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
async function macDevice(sources) {
|
|
648
|
+
const [modelId, profile, virtual, version] = await Promise.all([
|
|
649
|
+
sources.run("sysctl", ["-n", "hw.model"]),
|
|
650
|
+
sources.run("system_profiler", ["SPHardwareDataType", "-json"]),
|
|
651
|
+
sources.run("sysctl", ["-n", "kern.hv_vmm_present"]),
|
|
652
|
+
sources.run("sw_vers", ["-productVersion"])
|
|
653
|
+
]);
|
|
654
|
+
const model = profileModel(profile) ?? macModelFromId(modelId);
|
|
655
|
+
const isVm = virtual === "1" || Boolean(modelId?.startsWith("VirtualMac"));
|
|
656
|
+
return {
|
|
657
|
+
kind: isVm ? "vm" : macKind(model),
|
|
658
|
+
model: isVm ? void 0 : model,
|
|
659
|
+
modelId: modelId ?? void 0,
|
|
660
|
+
...commonSpecs(sources),
|
|
661
|
+
osVersion: version ? `macOS ${version}` : void 0
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
function profileModel(json) {
|
|
665
|
+
if (!json) return void 0;
|
|
666
|
+
try {
|
|
667
|
+
const name = JSON.parse(json).SPHardwareDataType?.[0]?.machine_name;
|
|
668
|
+
return typeof name === "string" && name.trim() ? name.trim() : void 0;
|
|
669
|
+
} catch {
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
const MAC_FAMILIES = [
|
|
674
|
+
["MacBookPro", "MacBook Pro"],
|
|
675
|
+
["MacBookAir", "MacBook Air"],
|
|
676
|
+
["MacBook", "MacBook"],
|
|
677
|
+
["Macmini", "Mac mini"],
|
|
678
|
+
["MacPro", "Mac Pro"],
|
|
679
|
+
["iMacPro", "iMac Pro"],
|
|
680
|
+
["iMac", "iMac"]
|
|
681
|
+
];
|
|
682
|
+
function macModelFromId(modelId) {
|
|
683
|
+
if (!modelId) return void 0;
|
|
684
|
+
return MAC_FAMILIES.find(([prefix]) => modelId.startsWith(prefix))?.[1];
|
|
685
|
+
}
|
|
686
|
+
function macKind(model) {
|
|
687
|
+
if (!model) return "unknown";
|
|
688
|
+
if (model.startsWith("MacBook")) return "laptop";
|
|
689
|
+
if (/^(iMac|Mac mini|Mac Studio|Mac Pro)/.test(model)) return "desktop";
|
|
690
|
+
return "unknown";
|
|
691
|
+
}
|
|
692
|
+
async function linuxDevice(sources) {
|
|
693
|
+
const dmi = (name) => sources.read(`/sys/class/dmi/id/${name}`);
|
|
694
|
+
const vendor = dmi("sys_vendor");
|
|
695
|
+
const product = dmi("product_name");
|
|
696
|
+
const lenovoName = vendor?.toUpperCase() === "LENOVO" ? dmi("product_version") : null;
|
|
697
|
+
const boardModel = sources.read("/proc/device-tree/model");
|
|
698
|
+
const rawModel = realName(lenovoName) ?? realName(product) ?? realName(boardModel);
|
|
699
|
+
return {
|
|
700
|
+
kind: await isLinuxVm(sources, vendor, product) ? "vm" : chassisKind(dmi("chassis_type")),
|
|
701
|
+
model: rawModel,
|
|
702
|
+
modelId: product ?? boardModel ?? void 0,
|
|
703
|
+
...commonSpecs(sources),
|
|
704
|
+
osVersion: osRelease(sources.read("/etc/os-release"))
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
const VM_VENDORS = /qemu|kvm|vmware|virtualbox|innotek|xen|bochs|parallels|amazon ec2|google/i;
|
|
708
|
+
async function isLinuxVm(sources, vendor, product) {
|
|
709
|
+
const virt = await sources.run("systemd-detect-virt", ["--vm"]);
|
|
710
|
+
if (virt && virt !== "none") return true;
|
|
711
|
+
if (vendor && VM_VENDORS.test(vendor)) return true;
|
|
712
|
+
if (product && /virtual machine|vmware|virtualbox|kvm|hvm domu/i.test(product)) return true;
|
|
713
|
+
return /^flags\s*:.*\bhypervisor\b/m.test(sources.read("/proc/cpuinfo") ?? "");
|
|
714
|
+
}
|
|
715
|
+
const CHASSIS = {
|
|
716
|
+
3: "desktop",
|
|
717
|
+
4: "desktop",
|
|
718
|
+
5: "desktop",
|
|
719
|
+
6: "desktop",
|
|
720
|
+
7: "desktop",
|
|
721
|
+
8: "laptop",
|
|
722
|
+
9: "laptop",
|
|
723
|
+
10: "laptop",
|
|
724
|
+
13: "desktop",
|
|
725
|
+
14: "laptop",
|
|
726
|
+
15: "desktop",
|
|
727
|
+
16: "desktop",
|
|
728
|
+
17: "server",
|
|
729
|
+
23: "server",
|
|
730
|
+
24: "desktop",
|
|
731
|
+
25: "server",
|
|
732
|
+
28: "server",
|
|
733
|
+
29: "server",
|
|
734
|
+
31: "laptop",
|
|
735
|
+
32: "laptop",
|
|
736
|
+
35: "desktop",
|
|
737
|
+
36: "desktop"
|
|
738
|
+
};
|
|
739
|
+
function chassisKind(chassisType) {
|
|
740
|
+
return CHASSIS[Number(chassisType)] ?? "unknown";
|
|
741
|
+
}
|
|
742
|
+
const PLACEHOLDERS = [
|
|
743
|
+
/^to be filled by o\.?e\.?m\.?$/i,
|
|
744
|
+
/^system product name$/i,
|
|
745
|
+
/^system version$/i,
|
|
746
|
+
/^default string$/i,
|
|
747
|
+
/^not (specified|applicable)$/i,
|
|
748
|
+
/^o\.?e\.?m\.?$/i,
|
|
749
|
+
/^none$/i,
|
|
750
|
+
/^unknown$/i,
|
|
751
|
+
/^standard pc\b/i,
|
|
752
|
+
/^\d+$/
|
|
753
|
+
];
|
|
754
|
+
/** A model name worth showing, or undefined for a placeholder. */
|
|
755
|
+
function realName(name) {
|
|
756
|
+
const trimmed = name?.trim();
|
|
757
|
+
if (!trimmed || PLACEHOLDERS.some((pattern) => pattern.test(trimmed))) return void 0;
|
|
758
|
+
return trimmed;
|
|
759
|
+
}
|
|
760
|
+
/** "Intel(R) Xeon(R) Gold 6338 CPU @ 2.00GHz" → "Intel Xeon Gold 6338". */
|
|
761
|
+
function cleanChip(model) {
|
|
762
|
+
const cleaned = model?.replace(/\((R|TM|C)\)/gi, "").replace(/\s+CPU\s*@.*$/i, "").replace(/\s+@\s*[\d.]+\s*GHz$/i, "").replace(/\s+\d+-Core Processor$/i, "").replace(/\s+/g, " ").trim();
|
|
763
|
+
return cleaned && cleaned.toLowerCase() !== "unknown" ? cleaned : void 0;
|
|
764
|
+
}
|
|
765
|
+
/** PRETTY_NAME from /etc/os-release, such as "Ubuntu 24.04.1 LTS". */
|
|
766
|
+
function osRelease(text) {
|
|
767
|
+
return (text?.split("\n").find((l) => l.startsWith("PRETTY_NAME=")))?.slice(12).trim().replace(/^["']|["']$/g, "") || void 0;
|
|
768
|
+
}
|
|
769
|
+
function compact(device) {
|
|
770
|
+
const out = {};
|
|
771
|
+
for (const [key, value] of Object.entries(device)) {
|
|
772
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
773
|
+
out[key] = typeof value === "string" ? value.slice(0, 120) : value;
|
|
774
|
+
}
|
|
775
|
+
return out;
|
|
776
|
+
}
|
|
777
|
+
// declined.ts
|
|
778
|
+
function declinedPath(home = relayrunnerHome()) {
|
|
779
|
+
return join(home, "declined-repos.json");
|
|
780
|
+
}
|
|
781
|
+
function read(path) {
|
|
782
|
+
try {
|
|
783
|
+
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
784
|
+
return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
|
|
785
|
+
} catch {
|
|
786
|
+
return [];
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
function isDeclined(repo, path = declinedPath()) {
|
|
790
|
+
return read(path).includes(repo);
|
|
791
|
+
}
|
|
792
|
+
function rememberDeclined(repo, path = declinedPath()) {
|
|
793
|
+
const repos = read(path);
|
|
794
|
+
if (repos.includes(repo)) return;
|
|
795
|
+
mkdirSync(dirname(path), {
|
|
796
|
+
recursive: true,
|
|
797
|
+
mode: 448
|
|
798
|
+
});
|
|
799
|
+
writeFileSync(path, `${JSON.stringify([...repos, repo], null, 2)}\n`);
|
|
800
|
+
}
|
|
801
|
+
// diff.ts
|
|
802
|
+
function unifiedDiff(before, after, file, context = 2) {
|
|
803
|
+
const a = before.split("\n");
|
|
804
|
+
const b = after.split("\n");
|
|
805
|
+
const lcs = Array.from({ length: a.length + 1 }, () => Array.from({ length: b.length + 1 }).fill(0));
|
|
806
|
+
for (let i = a.length - 1; i >= 0; i--) for (let j = b.length - 1; j >= 0; j--) lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
|
|
807
|
+
const lines = [];
|
|
808
|
+
let i = 0;
|
|
809
|
+
let j = 0;
|
|
810
|
+
while (i < a.length || j < b.length) if (i < a.length && j < b.length && a[i] === b[j]) lines.push({
|
|
811
|
+
kind: " ",
|
|
812
|
+
text: a[i],
|
|
813
|
+
a: i++,
|
|
814
|
+
b: j++
|
|
815
|
+
});
|
|
816
|
+
else if (i < a.length && (j >= b.length || lcs[i + 1][j] >= lcs[i][j + 1])) lines.push({
|
|
817
|
+
kind: "-",
|
|
818
|
+
text: a[i],
|
|
819
|
+
a: i++,
|
|
820
|
+
b: j
|
|
821
|
+
});
|
|
822
|
+
else lines.push({
|
|
823
|
+
kind: "+",
|
|
824
|
+
text: b[j],
|
|
825
|
+
a: i,
|
|
826
|
+
b: j++
|
|
827
|
+
});
|
|
828
|
+
const changed = lines.flatMap((line, index) => line.kind === " " ? [] : [index]);
|
|
829
|
+
if (!changed.length) return "";
|
|
830
|
+
const out = [`--- a/${file}`, `+++ b/${file}`];
|
|
831
|
+
let start = 0;
|
|
832
|
+
while (start < changed.length) {
|
|
833
|
+
let end = start;
|
|
834
|
+
while (end + 1 < changed.length && changed[end + 1] - changed[end] <= context * 2 + 1) end++;
|
|
835
|
+
const from = Math.max(0, changed[start] - context);
|
|
836
|
+
const to = Math.min(lines.length - 1, changed[end] + context);
|
|
837
|
+
const hunk = lines.slice(from, to + 1);
|
|
838
|
+
const aCount = hunk.filter((line) => line.kind !== "+").length;
|
|
839
|
+
const bCount = hunk.filter((line) => line.kind !== "-").length;
|
|
840
|
+
out.push(`@@ -${hunk[0].a + 1},${aCount} +${hunk[0].b + 1},${bCount} @@`);
|
|
841
|
+
for (const line of hunk) out.push(`${line.kind}${line.text}`);
|
|
842
|
+
start = end + 1;
|
|
843
|
+
}
|
|
844
|
+
return out.join("\n");
|
|
845
|
+
}
|
|
846
|
+
// repo.ts
|
|
847
|
+
const WORKFLOWS_DIR = ".github/workflows";
|
|
848
|
+
/** The nearest directory at or above `from` that holds a `.git`, or null outside a checkout. */
|
|
849
|
+
function findRepoRoot(from = process.cwd()) {
|
|
850
|
+
let dir = resolve(from);
|
|
851
|
+
for (;;) {
|
|
852
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
853
|
+
const parent = dirname(dir);
|
|
854
|
+
if (parent === dir) return null;
|
|
855
|
+
dir = parent;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
function readWorkflowFiles(root) {
|
|
859
|
+
const dir = join(root, WORKFLOWS_DIR);
|
|
860
|
+
if (!existsSync(dir)) return [];
|
|
861
|
+
return readdirSync(dir).filter((name) => /\.ya?ml$/.test(name)).sort().map((name) => ({
|
|
862
|
+
file: `${WORKFLOWS_DIR}/${name}`,
|
|
863
|
+
source: readFileSync(join(dir, name), "utf8")
|
|
864
|
+
}));
|
|
865
|
+
}
|
|
866
|
+
/** `owner/name` from a GitHub remote URL (https or ssh), or null for anything else. */
|
|
867
|
+
function parseGitHubRemote(url) {
|
|
868
|
+
const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url.trim());
|
|
869
|
+
return match ? `${match[1]}/${match[2]}` : null;
|
|
870
|
+
}
|
|
871
|
+
function originRepo(root) {
|
|
872
|
+
return new Promise((done) => {
|
|
873
|
+
execFile("git", [
|
|
874
|
+
"-C",
|
|
875
|
+
root,
|
|
876
|
+
"remote",
|
|
877
|
+
"get-url",
|
|
878
|
+
"origin"
|
|
879
|
+
], {
|
|
880
|
+
timeout: 3e3,
|
|
881
|
+
encoding: "utf8"
|
|
882
|
+
}, (error, stdout) => done(error ? null : parseGitHubRemote(stdout)));
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* Asks GitHub without signing in. A public repo answers; a private one (or one that doesn't exist)
|
|
887
|
+
* is a 404 to an anonymous caller. Anything else, such as no network or a rate limit, is unknown.
|
|
888
|
+
*/
|
|
889
|
+
async function repoVisibility(repo, fetcher = fetch) {
|
|
890
|
+
try {
|
|
891
|
+
const response = await fetcher(`https://api.github.com/repos/${repo}`, {
|
|
892
|
+
headers: {
|
|
893
|
+
accept: "application/vnd.github+json",
|
|
894
|
+
"user-agent": userAgent
|
|
895
|
+
},
|
|
896
|
+
signal: AbortSignal.timeout(5e3)
|
|
897
|
+
});
|
|
898
|
+
if (response.status === 404) return "private";
|
|
899
|
+
if (!response.ok) return "unknown";
|
|
900
|
+
return (await response.json()).private === false ? "public" : "private";
|
|
901
|
+
} catch {
|
|
902
|
+
return "unknown";
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
// workflows.ts
|
|
906
|
+
/** The relay version `init` writes. Bump it with each relayrunner/actions release. */
|
|
907
|
+
const RELAY_REF = "v1.0.0-beta.4";
|
|
908
|
+
const RELAY_WORKFLOW = "relayrunner/actions/.github/workflows/relay.yml";
|
|
909
|
+
const DEPLOY_SECRET = /\bsecrets\.(?!GITHUB_TOKEN\b)[A-Za-z_][A-Za-z0-9_]*/;
|
|
910
|
+
const LINUX_PACKAGE_MANAGER = /(^|[\s;&|(])(sudo\s+)?(apt-get|apt|yum|dnf|apk)\s+(install|update|add)\b/m;
|
|
911
|
+
function analyzeWorkflows(files, options = {}) {
|
|
912
|
+
const jobs = [];
|
|
913
|
+
const errors = [];
|
|
914
|
+
for (const { file, source } of files) {
|
|
915
|
+
const doc = parseDocument(source);
|
|
916
|
+
if (doc.errors.length) {
|
|
917
|
+
errors.push({
|
|
918
|
+
file,
|
|
919
|
+
message: doc.errors[0].message.split("\n")[0]
|
|
920
|
+
});
|
|
921
|
+
continue;
|
|
922
|
+
}
|
|
923
|
+
const workflow = doc.toJS();
|
|
924
|
+
if (!workflow || typeof workflow !== "object") continue;
|
|
925
|
+
const all = workflow.jobs;
|
|
926
|
+
if (!all || typeof all !== "object") continue;
|
|
927
|
+
const relays = new Set(Object.entries(all).filter(([, job]) => isRelayJob(job)).map(([id]) => id));
|
|
928
|
+
const reusableOnly = onlyWorkflowCall(workflow.on);
|
|
929
|
+
for (const [id, raw] of Object.entries(all)) {
|
|
930
|
+
if (!raw || typeof raw !== "object") continue;
|
|
931
|
+
const job = raw;
|
|
932
|
+
if (relays.has(id)) continue;
|
|
933
|
+
jobs.push(judge(file, id, job, workflow, relays, reusableOnly, options));
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
return {
|
|
937
|
+
jobs,
|
|
938
|
+
errors
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
/** True when any job already runs where a relay sends it. */
|
|
942
|
+
function isSetUp(jobs) {
|
|
943
|
+
return jobs.some((job) => job.verdict === "routed");
|
|
944
|
+
}
|
|
945
|
+
function judge(file, id, job, workflow, relays, reusableOnly, options) {
|
|
946
|
+
const base = {
|
|
947
|
+
file,
|
|
948
|
+
job: id,
|
|
949
|
+
warnings: []
|
|
950
|
+
};
|
|
951
|
+
const skip = (reason) => ({
|
|
952
|
+
...base,
|
|
953
|
+
verdict: "skipped",
|
|
954
|
+
reason
|
|
955
|
+
});
|
|
956
|
+
if (typeof job.uses === "string") return skip("calls a reusable workflow");
|
|
957
|
+
if (reusableOnly) return skip("part of a reusable workflow; it runs wherever the calling workflow sends it");
|
|
958
|
+
const runsOn = job["runs-on"];
|
|
959
|
+
if (runsOn === void 0) return skip("has no runs-on");
|
|
960
|
+
if (typeof runsOn !== "string") return skip("runs-on is a list of labels or a runner group");
|
|
961
|
+
if (runsOn.includes("${{")) {
|
|
962
|
+
const relay = /^\$\{\{\s*needs\.([\w-]+)\.outputs\.runner\s*\}\}$/.exec(runsOn.trim())?.[1];
|
|
963
|
+
if (relay && relays.has(relay)) return {
|
|
964
|
+
...base,
|
|
965
|
+
verdict: "routed"
|
|
966
|
+
};
|
|
967
|
+
return skip("runs-on is an expression");
|
|
968
|
+
}
|
|
969
|
+
if (hasMatrix(job)) return skip("uses a matrix, and one relay can't serve every leg");
|
|
970
|
+
const deploy = deploySignal(job, workflow);
|
|
971
|
+
if (deploy) return skip(`looks like a deploy job (${deploy})`);
|
|
972
|
+
const label = runsOn.trim();
|
|
973
|
+
const lower = label.toLowerCase();
|
|
974
|
+
let provider;
|
|
975
|
+
let machine = "self-hosted";
|
|
976
|
+
if (lower.startsWith("blacksmith-")) provider = "blacksmith";
|
|
977
|
+
else if (/^(ubuntu|macos)-/.test(lower)) {
|
|
978
|
+
provider = "github";
|
|
979
|
+
if (lower.startsWith("macos-")) machine = "macOS";
|
|
980
|
+
} else if (lower.startsWith("windows-")) return skip("Windows jobs can't run on machines yet");
|
|
981
|
+
else if (lower === "relayrunner") return skip("already runs on RelayRunner");
|
|
982
|
+
else if (lower === "self-hosted") return skip("already runs on a self-hosted runner");
|
|
983
|
+
else return skip(`${label} isn't a GitHub-hosted or Blacksmith label`);
|
|
984
|
+
const warnings = jobWarnings(job, options);
|
|
985
|
+
return {
|
|
986
|
+
...base,
|
|
987
|
+
verdict: "ready",
|
|
988
|
+
provider,
|
|
989
|
+
label,
|
|
990
|
+
machine,
|
|
991
|
+
warnings
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
function isRelayJob(job) {
|
|
995
|
+
return typeof job?.uses === "string" && job.uses.split("@")[0] === "relayrunner/actions/.github/workflows/relay.yml";
|
|
996
|
+
}
|
|
997
|
+
function onlyWorkflowCall(on) {
|
|
998
|
+
if (on === "workflow_call") return true;
|
|
999
|
+
if (Array.isArray(on)) return on.length > 0 && on.every((event) => event === "workflow_call");
|
|
1000
|
+
if (on && typeof on === "object") {
|
|
1001
|
+
const events = Object.keys(on);
|
|
1002
|
+
return events.length > 0 && events.every((event) => event === "workflow_call");
|
|
1003
|
+
}
|
|
1004
|
+
return false;
|
|
1005
|
+
}
|
|
1006
|
+
function hasMatrix(job) {
|
|
1007
|
+
const strategy = job.strategy;
|
|
1008
|
+
return !!strategy && typeof strategy === "object" && strategy.matrix !== void 0;
|
|
1009
|
+
}
|
|
1010
|
+
function deploySignal(job, workflow) {
|
|
1011
|
+
if (job.environment !== void 0) return "environment";
|
|
1012
|
+
const permissions = job.permissions ?? workflow.permissions;
|
|
1013
|
+
if (permissions === "write-all") return "write-all permissions";
|
|
1014
|
+
if (permissions && typeof permissions === "object" && permissions["id-token"] === "write") return "id-token: write";
|
|
1015
|
+
const secret = DEPLOY_SECRET.exec(JSON.stringify(job))?.[0];
|
|
1016
|
+
if (secret) return `uses ${secret}`;
|
|
1017
|
+
return null;
|
|
1018
|
+
}
|
|
1019
|
+
function jobWarnings(job, options) {
|
|
1020
|
+
const warnings = [];
|
|
1021
|
+
if (job.services !== void 0) warnings.push("uses services, which need Docker on the machine");
|
|
1022
|
+
if (job.container !== void 0) warnings.push("runs in a container, which needs Docker on the machine");
|
|
1023
|
+
const steps = Array.isArray(job.steps) ? job.steps : [];
|
|
1024
|
+
const providerActions = /* @__PURE__ */ new Set();
|
|
1025
|
+
let packages = false;
|
|
1026
|
+
for (const step of steps) {
|
|
1027
|
+
if (!step || typeof step !== "object") continue;
|
|
1028
|
+
if (typeof step.run === "string" && LINUX_PACKAGE_MANAGER.test(step.run)) packages = true;
|
|
1029
|
+
if (typeof step.uses === "string") {
|
|
1030
|
+
const action = step.uses.split("@")[0];
|
|
1031
|
+
if (action.startsWith("useblacksmith/")) providerActions.add(action);
|
|
1032
|
+
if (action.startsWith("docker://")) warnings.push("runs a Docker action, which needs Docker on the machine");
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
if (packages && options.hostOs !== "linux") warnings.push(options.hostOs === "macos" ? "installs Linux packages (apt-get, yum or apk), which macOS doesn't have" : "installs Linux packages (apt-get, yum or apk)");
|
|
1036
|
+
for (const action of providerActions) warnings.push(`uses ${action}, which is made for Blacksmith runners`);
|
|
1037
|
+
return warnings;
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Routes the given jobs of one workflow file through the relay. Returns the new file contents.
|
|
1041
|
+
* Each job must have come back `ready` from analyzeWorkflows for this same source.
|
|
1042
|
+
*/
|
|
1043
|
+
function routeJobs(source, jobs) {
|
|
1044
|
+
const doc = parseDocument(source);
|
|
1045
|
+
const all = doc.get("jobs");
|
|
1046
|
+
if (!isMap(all)) throw new Error("This workflow has no jobs map.");
|
|
1047
|
+
for (const job of jobs) {
|
|
1048
|
+
if (job.verdict !== "ready" || !job.provider || !job.label) throw new Error(`${job.job} isn't ready to route.`);
|
|
1049
|
+
routeJob(doc, all, job);
|
|
1050
|
+
}
|
|
1051
|
+
return doc.toString({
|
|
1052
|
+
lineWidth: 0,
|
|
1053
|
+
flowCollectionPadding: false
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
function routeJob(doc, all, job) {
|
|
1057
|
+
const index = all.items.findIndex((pair) => isScalar(pair.key) && pair.key.value === job.job);
|
|
1058
|
+
const pair = all.items[index];
|
|
1059
|
+
if (!pair || !isMap(pair.value)) throw new Error(`No job ${job.job} in this workflow.`);
|
|
1060
|
+
const node = pair.value;
|
|
1061
|
+
const relayId = freeId(all, `relay-${job.job}`);
|
|
1062
|
+
const relay = doc.createNode({
|
|
1063
|
+
uses: `${RELAY_WORKFLOW}@${RELAY_REF}`,
|
|
1064
|
+
with: {
|
|
1065
|
+
machine: job.machine ?? "self-hosted",
|
|
1066
|
+
[job.provider]: job.label
|
|
1067
|
+
}
|
|
1068
|
+
});
|
|
1069
|
+
const key = new Scalar(relayId);
|
|
1070
|
+
const jobKey = pair.key;
|
|
1071
|
+
key.spaceBefore = jobKey.spaceBefore;
|
|
1072
|
+
if (key.spaceBefore === void 0 && index > 0) key.spaceBefore = true;
|
|
1073
|
+
key.commentBefore = jobKey.commentBefore;
|
|
1074
|
+
jobKey.commentBefore = void 0;
|
|
1075
|
+
jobKey.spaceBefore = true;
|
|
1076
|
+
all.items.splice(index, 0, doc.createPair(key, relay));
|
|
1077
|
+
const runsOn = node.get("runs-on", true);
|
|
1078
|
+
const target = `\${{ needs.${relayId}.outputs.runner }}`;
|
|
1079
|
+
if (isScalar(runsOn)) {
|
|
1080
|
+
runsOn.value = target;
|
|
1081
|
+
runsOn.type = Scalar.PLAIN;
|
|
1082
|
+
} else node.set("runs-on", target);
|
|
1083
|
+
const needs = node.get("needs", true);
|
|
1084
|
+
if (needs === void 0) {
|
|
1085
|
+
const at = node.items.findIndex((item) => isScalar(item.key) && item.key.value === "runs-on");
|
|
1086
|
+
node.items.splice(Math.max(at, 0), 0, doc.createPair("needs", relayId));
|
|
1087
|
+
} else if (isSeq(needs)) needs.add(doc.createNode(relayId));
|
|
1088
|
+
else if (isScalar(needs)) {
|
|
1089
|
+
const list = new YAMLSeq();
|
|
1090
|
+
list.flow = true;
|
|
1091
|
+
list.add(doc.createNode(needs.value));
|
|
1092
|
+
list.add(doc.createNode(relayId));
|
|
1093
|
+
node.set("needs", list);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
function freeId(all, wanted) {
|
|
1097
|
+
const taken = new Set(all.items.map((pair) => isScalar(pair.key) ? String(pair.key.value) : ""));
|
|
1098
|
+
if (!taken.has(wanted)) return wanted;
|
|
1099
|
+
for (let n = 2;; n++) if (!taken.has(`${wanted}-${n}`)) return `${wanted}-${n}`;
|
|
1100
|
+
}
|
|
1101
|
+
// init.ts
|
|
1102
|
+
var InitError = class extends Error {};
|
|
1103
|
+
async function planInit(cwd = process.cwd(), options = {}) {
|
|
1104
|
+
const root = findRepoRoot(cwd);
|
|
1105
|
+
if (!root) throw new InitError("Not in a git checkout. Run `relayrunner init` inside a repo.");
|
|
1106
|
+
const repo = await originRepo(root);
|
|
1107
|
+
const visibility = repo ? await repoVisibility(repo, options.fetcher) : "unknown";
|
|
1108
|
+
const files = readWorkflowFiles(root);
|
|
1109
|
+
const { jobs, errors } = analyzeWorkflows(files, { hostOs: options.hostOs ?? hostOs() });
|
|
1110
|
+
return {
|
|
1111
|
+
root,
|
|
1112
|
+
repo,
|
|
1113
|
+
visibility,
|
|
1114
|
+
files,
|
|
1115
|
+
jobs,
|
|
1116
|
+
errors
|
|
1117
|
+
};
|
|
1118
|
+
}
|
|
1119
|
+
/** Picks jobs by `job`, `file:job` or `all`. Throws when a name is unknown, ambiguous or not ready. */
|
|
1120
|
+
function selectJobs(jobs, names) {
|
|
1121
|
+
const ready = jobs.filter((job) => job.verdict === "ready");
|
|
1122
|
+
if (names.length === 1 && names[0] === "all") return ready;
|
|
1123
|
+
const picked = /* @__PURE__ */ new Map();
|
|
1124
|
+
for (const name of names) {
|
|
1125
|
+
const [file, id] = name.includes(":") ? name.split(/:(?=[^:]*$)/) : [void 0, name];
|
|
1126
|
+
const matches = jobs.filter((job) => job.job === id && (!file || job.file === file || shortFile(job.file) === file));
|
|
1127
|
+
if (!matches.length) throw new InitError(`No job named ${name}.`);
|
|
1128
|
+
if (matches.length > 1) throw new InitError(`${name} is in more than one workflow. Name it as ${matches.map((job) => `${job.file}:${job.job}`).join(" or ")}.`);
|
|
1129
|
+
const job = matches[0];
|
|
1130
|
+
if (job.verdict === "routed") throw new InitError(`${name} is already routed.`);
|
|
1131
|
+
if (job.verdict === "skipped") throw new InitError(`${name} can't be routed: ${job.reason}.`);
|
|
1132
|
+
picked.set(`${job.file}:${job.job}`, job);
|
|
1133
|
+
}
|
|
1134
|
+
return [...picked.values()];
|
|
1135
|
+
}
|
|
1136
|
+
/** The new contents of each workflow file the chosen jobs live in. */
|
|
1137
|
+
function changesFor(plan, chosen) {
|
|
1138
|
+
const byFile = /* @__PURE__ */ new Map();
|
|
1139
|
+
for (const job of chosen) byFile.set(job.file, [...byFile.get(job.file) ?? [], job]);
|
|
1140
|
+
return [...byFile].map(([file, jobs]) => {
|
|
1141
|
+
const before = plan.files.find((entry) => entry.file === file).source;
|
|
1142
|
+
return {
|
|
1143
|
+
file,
|
|
1144
|
+
jobs,
|
|
1145
|
+
before,
|
|
1146
|
+
after: routeJobs(before, jobs)
|
|
1147
|
+
};
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1150
|
+
function writeChanges(root, changes) {
|
|
1151
|
+
for (const change of changes) writeFileSync(join(root, change.file), change.after);
|
|
1152
|
+
}
|
|
1153
|
+
function hostOs() {
|
|
1154
|
+
if (process.platform === "darwin") return "macos";
|
|
1155
|
+
if (process.platform === "linux") return "linux";
|
|
1156
|
+
}
|
|
1157
|
+
const PUBLIC_REPO = "This repo is public, and machines never take jobs from public repos. There's nothing for init to set up here.";
|
|
1158
|
+
const initCommand = defineCommand({
|
|
1159
|
+
meta: {
|
|
1160
|
+
name: "init",
|
|
1161
|
+
description: "Route this repo's GitHub Actions jobs through RelayRunner, so they run on your machine when it's online. Edits workflow files; never commits."
|
|
1162
|
+
},
|
|
1163
|
+
args: {
|
|
1164
|
+
plan: {
|
|
1165
|
+
type: "boolean",
|
|
1166
|
+
description: "List every job and whether it can be routed. Changes nothing."
|
|
1167
|
+
},
|
|
1168
|
+
apply: {
|
|
1169
|
+
type: "string",
|
|
1170
|
+
description: "Route these jobs without prompting: comma-separated ids or file:job, or `all` for every ready job"
|
|
1171
|
+
},
|
|
1172
|
+
json: {
|
|
1173
|
+
type: "boolean",
|
|
1174
|
+
description: "Print the result as JSON (with --plan or --apply)"
|
|
1175
|
+
}
|
|
1176
|
+
},
|
|
1177
|
+
async run({ args }) {
|
|
1178
|
+
try {
|
|
1179
|
+
const plan = await planInit();
|
|
1180
|
+
if (args.apply !== void 0) return apply(plan, args.apply, !!args.json);
|
|
1181
|
+
if (args.plan || args.json) return printPlan(plan, !!args.json);
|
|
1182
|
+
if (!process.stdin.isTTY) {
|
|
1183
|
+
printPlan(plan, false);
|
|
1184
|
+
console.log("\nRun `relayrunner init --apply <jobs>` to route jobs without prompts.");
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
await interactive(plan);
|
|
1188
|
+
} catch (error) {
|
|
1189
|
+
if (!(error instanceof InitError)) throw error;
|
|
1190
|
+
if (args.json) console.log(JSON.stringify({ error: error.message }, null, 2));
|
|
1191
|
+
else console.error(error.message);
|
|
1192
|
+
process.exitCode = 1;
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
});
|
|
1196
|
+
function planJson(plan) {
|
|
1197
|
+
return {
|
|
1198
|
+
repo: plan.repo,
|
|
1199
|
+
visibility: plan.visibility,
|
|
1200
|
+
relay: RELAY_REF,
|
|
1201
|
+
setUp: isSetUp(plan.jobs),
|
|
1202
|
+
...plan.visibility === "public" ? { refused: "public_repo" } : {},
|
|
1203
|
+
jobs: plan.jobs,
|
|
1204
|
+
errors: plan.errors
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
function printPlan(plan, json) {
|
|
1208
|
+
if (json) return console.log(JSON.stringify(planJson(plan), null, 2));
|
|
1209
|
+
console.log(describeRepo(plan));
|
|
1210
|
+
if (plan.visibility === "public") return console.log(PUBLIC_REPO);
|
|
1211
|
+
if (!plan.files.length) return console.log("No workflows in .github/workflows.");
|
|
1212
|
+
for (const [title, verdict] of [
|
|
1213
|
+
["Ready to route", "ready"],
|
|
1214
|
+
["Already routed", "routed"],
|
|
1215
|
+
["Skipped", "skipped"]
|
|
1216
|
+
]) {
|
|
1217
|
+
const jobs = plan.jobs.filter((job) => job.verdict === verdict);
|
|
1218
|
+
if (!jobs.length) continue;
|
|
1219
|
+
console.log(`\n${title}`);
|
|
1220
|
+
for (const job of jobs) console.log(` ${jobLine(job)}`);
|
|
1221
|
+
}
|
|
1222
|
+
for (const error of plan.errors) console.log(`\nCouldn't read ${error.file}: ${error.message}`);
|
|
1223
|
+
}
|
|
1224
|
+
function apply(plan, list, json) {
|
|
1225
|
+
if (plan.visibility === "public") throw new InitError(PUBLIC_REPO);
|
|
1226
|
+
const names = list.split(",").map((name) => name.trim()).filter(Boolean);
|
|
1227
|
+
if (!names.length) throw new InitError("Name the jobs to route, or `all`.");
|
|
1228
|
+
const chosen = selectJobs(plan.jobs, names);
|
|
1229
|
+
if (!chosen.length) throw new InitError("No jobs are ready to route.");
|
|
1230
|
+
const changes = changesFor(plan, chosen);
|
|
1231
|
+
writeChanges(plan.root, changes);
|
|
1232
|
+
const routed = chosen.map(({ file, job, warnings }) => ({
|
|
1233
|
+
file,
|
|
1234
|
+
job,
|
|
1235
|
+
warnings
|
|
1236
|
+
}));
|
|
1237
|
+
if (json) return console.log(JSON.stringify({
|
|
1238
|
+
relay: RELAY_REF,
|
|
1239
|
+
routed
|
|
1240
|
+
}, null, 2));
|
|
1241
|
+
for (const change of changes) console.log(`Updated ${change.file} (${change.jobs.map((job) => job.job).join(", ")})`);
|
|
1242
|
+
console.log("Commit and push to start routing.");
|
|
1243
|
+
}
|
|
1244
|
+
async function interactive(plan) {
|
|
1245
|
+
clack.intro("RelayRunner init");
|
|
1246
|
+
clack.log.info(describeRepo(plan));
|
|
1247
|
+
if (plan.visibility === "public") return clack.outro(PUBLIC_REPO);
|
|
1248
|
+
if (plan.visibility === "unknown") clack.log.warn("Couldn't check whether this repo is public. Machines only take jobs from private repos.");
|
|
1249
|
+
for (const error of plan.errors) clack.log.warn(`Couldn't read ${error.file}: ${error.message}`);
|
|
1250
|
+
if (!plan.files.length) return clack.outro("No workflows in .github/workflows.");
|
|
1251
|
+
await chooseAndWrite(plan, (message) => clack.outro(message));
|
|
1252
|
+
}
|
|
1253
|
+
/** Lists the jobs, lets the user pick, shows the diff and writes it. `finish` gets the last line. */
|
|
1254
|
+
async function chooseAndWrite(plan, finish) {
|
|
1255
|
+
const routed = plan.jobs.filter((job) => job.verdict === "routed");
|
|
1256
|
+
const skipped = plan.jobs.filter((job) => job.verdict === "skipped");
|
|
1257
|
+
const ready = plan.jobs.filter((job) => job.verdict === "ready");
|
|
1258
|
+
if (routed.length) clack.note(routed.map(jobLine).join("\n"), "Already routed");
|
|
1259
|
+
if (skipped.length) clack.note(skipped.map(jobLine).join("\n"), "Skipped");
|
|
1260
|
+
if (!ready.length) return finish("No other jobs to route.");
|
|
1261
|
+
const picked = await clack.multiselect({
|
|
1262
|
+
message: "Route these jobs through RelayRunner?",
|
|
1263
|
+
options: ready.map((job) => ({
|
|
1264
|
+
value: job,
|
|
1265
|
+
label: `${shortFile(job.file)} › ${job.job}`,
|
|
1266
|
+
hint: [`${job.label} when your machine is offline`, ...job.warnings].join("; ")
|
|
1267
|
+
})),
|
|
1268
|
+
initialValues: ready,
|
|
1269
|
+
required: false
|
|
1270
|
+
});
|
|
1271
|
+
if (clack.isCancel(picked) || !picked.length) return finish("Nothing changed.");
|
|
1272
|
+
const changes = changesFor(plan, picked);
|
|
1273
|
+
for (const change of changes) console.log(`${colorDiff(unifiedDiff(change.before, change.after, change.file))}\n`);
|
|
1274
|
+
const ok = await clack.confirm({ message: `Write ${changes.length === 1 ? "this change" : `these ${changes.length} changes`}?` });
|
|
1275
|
+
if (clack.isCancel(ok) || !ok) return finish("Nothing changed.");
|
|
1276
|
+
writeChanges(plan.root, changes);
|
|
1277
|
+
const warned = picked.filter((job) => job.warnings.length);
|
|
1278
|
+
if (warned.length) clack.note(warned.map((job) => `${job.job}: ${job.warnings.join("; ")}`).join("\n"), "Check before it runs on your machine");
|
|
1279
|
+
finish(`Updated ${changes.map((change) => change.file).join(", ")}. Commit and push to start routing.`);
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* Whether `connect` should offer to set up this checkout: it's not public, nothing in it is routed
|
|
1283
|
+
* yet, and at least one job could be.
|
|
1284
|
+
*/
|
|
1285
|
+
function shouldOfferSetup(plan) {
|
|
1286
|
+
return plan.visibility !== "public" && !isSetUp(plan.jobs) && plan.jobs.some((job) => job.verdict === "ready");
|
|
1287
|
+
}
|
|
1288
|
+
/**
|
|
1289
|
+
* Run by `connect` before it goes online. Inside a repo that could use RelayRunner but doesn't
|
|
1290
|
+
* yet, asks once whether to set it up (default no) and runs the same picker as `init`. A "no" is
|
|
1291
|
+
* remembered for that repo, so later runs don't ask again; `relayrunner init` still works. Never
|
|
1292
|
+
* throws: setup is a convenience, and `connect` goes online either way.
|
|
1293
|
+
*/
|
|
1294
|
+
async function offerSetup(cwd = process.cwd()) {
|
|
1295
|
+
try {
|
|
1296
|
+
const plan = await planInit(cwd).catch((error) => {
|
|
1297
|
+
if (error instanceof InitError) return null;
|
|
1298
|
+
throw error;
|
|
1299
|
+
});
|
|
1300
|
+
if (!plan || !shouldOfferSetup(plan)) return;
|
|
1301
|
+
const key = plan.repo ?? plan.root;
|
|
1302
|
+
if (isDeclined(key)) return;
|
|
1303
|
+
const answer = await clack.confirm({
|
|
1304
|
+
message: `Set up ${plan.repo ?? basename(plan.root)} to run its CI on this machine?`,
|
|
1305
|
+
initialValue: false
|
|
1306
|
+
});
|
|
1307
|
+
if (clack.isCancel(answer)) return;
|
|
1308
|
+
if (!answer) {
|
|
1309
|
+
rememberDeclined(key);
|
|
1310
|
+
clack.log.info("Not now. Run `relayrunner init` in this repo any time to set it up.");
|
|
1311
|
+
return;
|
|
1312
|
+
}
|
|
1313
|
+
await chooseAndWrite(plan, (message) => clack.log.success(message));
|
|
1314
|
+
} catch (error) {
|
|
1315
|
+
clack.log.warn(`Couldn't check this repo's workflows: ${error instanceof Error ? error.message : String(error)}`);
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
function describeRepo(plan) {
|
|
1319
|
+
if (!plan.repo) return `${plan.root} (no GitHub remote named origin)`;
|
|
1320
|
+
return plan.visibility === "unknown" ? plan.repo : `${plan.repo} (${plan.visibility})`;
|
|
1321
|
+
}
|
|
1322
|
+
function jobLine(job) {
|
|
1323
|
+
const name = `${shortFile(job.file)} › ${job.job}`;
|
|
1324
|
+
if (job.verdict === "skipped") return `${name}: ${job.reason}`;
|
|
1325
|
+
if (job.verdict === "routed") return name;
|
|
1326
|
+
return `${name}: ${[`falls back to ${job.label}`, ...job.warnings].join("; ")}`;
|
|
1327
|
+
}
|
|
1328
|
+
function shortFile(file) {
|
|
1329
|
+
return file.replace(/^\.github\/workflows\//, "");
|
|
1330
|
+
}
|
|
1331
|
+
function colorDiff(diff) {
|
|
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");
|
|
1333
|
+
}
|
|
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
|
+
};
|
|
1361
|
+
}
|
|
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`
|
|
1366
|
+
};
|
|
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
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
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}`
|
|
1415
|
+
};
|
|
1416
|
+
return {
|
|
1417
|
+
ok: true,
|
|
1418
|
+
target: target(field("githuburl"))
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
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;
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
return null;
|
|
1449
|
+
}
|
|
1450
|
+
function decodeJson(base64) {
|
|
1451
|
+
return JSON.parse(Buffer.from(base64, "base64").toString("utf8").replace(/^/, ""));
|
|
1452
|
+
}
|
|
493
1453
|
// job.ts
|
|
494
1454
|
const runnerEnv = () => Object.fromEntries([
|
|
495
1455
|
"HOME",
|
|
@@ -514,6 +1474,13 @@ async function runJob(run, options) {
|
|
|
514
1474
|
report(update);
|
|
515
1475
|
return update;
|
|
516
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);
|
|
517
1484
|
const lock = join(runner.dir, "job.lock");
|
|
518
1485
|
if (!takeLock(lock)) return finish({
|
|
519
1486
|
routeId: run.routeId,
|
|
@@ -624,7 +1591,8 @@ const ClaimResponse = z.object({
|
|
|
624
1591
|
workspace: z.object({
|
|
625
1592
|
id: z.string().min(1),
|
|
626
1593
|
name: z.string(),
|
|
627
|
-
slug: z.string().nullish()
|
|
1594
|
+
slug: z.string().nullish(),
|
|
1595
|
+
memberCount: z.number().int().nonnegative().optional()
|
|
628
1596
|
}),
|
|
629
1597
|
token: z.string().min(1)
|
|
630
1598
|
});
|
|
@@ -696,14 +1664,18 @@ async function login(options) {
|
|
|
696
1664
|
}, { authorization: `Bearer ${accessToken}` });
|
|
697
1665
|
if (!claimResponse.ok) throw new LoginError("CLAIM_FAILED", `The gateway approved the sign-in but wouldn't enroll this machine (HTTP ${claimResponse.status}).`);
|
|
698
1666
|
const claimed = ClaimResponse.parse(await claimResponse.json());
|
|
1667
|
+
const { memberCount, ...workspace } = claimed.workspace;
|
|
699
1668
|
return {
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
1669
|
+
credentials: {
|
|
1670
|
+
server: new URL(options.server).origin,
|
|
1671
|
+
machine: {
|
|
1672
|
+
id: claimed.machine.id,
|
|
1673
|
+
name: claimed.machine.name
|
|
1674
|
+
},
|
|
1675
|
+
workspace,
|
|
1676
|
+
token: claimed.token
|
|
704
1677
|
},
|
|
705
|
-
|
|
706
|
-
token: claimed.token
|
|
1678
|
+
memberCount: memberCount ?? null
|
|
707
1679
|
};
|
|
708
1680
|
}
|
|
709
1681
|
function openBrowser(url) {
|
|
@@ -763,6 +1735,60 @@ async function setPaused(options) {
|
|
|
763
1735
|
busy: parsed.data.machine.status?.state === "busy"
|
|
764
1736
|
};
|
|
765
1737
|
}
|
|
1738
|
+
// share.ts
|
|
1739
|
+
const SHARE_CHOICES = ["only-me", "anyone"];
|
|
1740
|
+
const MachineSharing = z.enum(["only_me", "anyone"]);
|
|
1741
|
+
function parseShareChoice(value) {
|
|
1742
|
+
return SHARE_CHOICES.includes(value) ? value : null;
|
|
1743
|
+
}
|
|
1744
|
+
const toSharing = (choice) => choice === "only-me" ? "only_me" : "anyone";
|
|
1745
|
+
const toChoice = (sharing) => sharing === "only_me" ? "only-me" : "anyone";
|
|
1746
|
+
function sharingMeaning(sharing, workspace) {
|
|
1747
|
+
return sharing === "only_me" ? "runs only jobs you started" : `runs any job in ${workspace ?? "the workspace"}, including teammates' and bots'`;
|
|
1748
|
+
}
|
|
1749
|
+
function describeSharing(sharing, workspace) {
|
|
1750
|
+
return `${toChoice(sharing)}: ${sharingMeaning(sharing, workspace)}`;
|
|
1751
|
+
}
|
|
1752
|
+
const SharingResponse = z.object({ machine: z.object({ sharing: MachineSharing }) });
|
|
1753
|
+
async function setSharing(options) {
|
|
1754
|
+
const fetcher = options.fetcher ?? fetch;
|
|
1755
|
+
let response;
|
|
1756
|
+
try {
|
|
1757
|
+
response = await fetcher(new URL("/api/machines/me/sharing", options.server), {
|
|
1758
|
+
method: "PUT",
|
|
1759
|
+
headers: {
|
|
1760
|
+
authorization: `Bearer ${options.token}`,
|
|
1761
|
+
"content-type": "application/json",
|
|
1762
|
+
"user-agent": userAgent
|
|
1763
|
+
},
|
|
1764
|
+
body: JSON.stringify({ sharing: options.sharing })
|
|
1765
|
+
});
|
|
1766
|
+
} catch (error) {
|
|
1767
|
+
const cause = error.cause?.message;
|
|
1768
|
+
return {
|
|
1769
|
+
status: "failed",
|
|
1770
|
+
reason: `couldn't reach ${options.server}${cause ? ` (${cause})` : ""}`
|
|
1771
|
+
};
|
|
1772
|
+
}
|
|
1773
|
+
if (response.status === 401) return { status: "revoked" };
|
|
1774
|
+
if (response.status === 404 || response.status === 405) return {
|
|
1775
|
+
status: "failed",
|
|
1776
|
+
reason: `${options.server} doesn't support sharing yet`
|
|
1777
|
+
};
|
|
1778
|
+
if (!response.ok) return {
|
|
1779
|
+
status: "failed",
|
|
1780
|
+
reason: `${options.server} answered HTTP ${response.status}`
|
|
1781
|
+
};
|
|
1782
|
+
const parsed = SharingResponse.safeParse(await response.json().catch(() => null));
|
|
1783
|
+
if (!parsed.success) return {
|
|
1784
|
+
status: "failed",
|
|
1785
|
+
reason: `${options.server} sent an unexpected response`
|
|
1786
|
+
};
|
|
1787
|
+
return {
|
|
1788
|
+
status: "ok",
|
|
1789
|
+
sharing: parsed.data.machine.sharing
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
766
1792
|
// whoami.ts
|
|
767
1793
|
const WhoamiResponse = z.object({
|
|
768
1794
|
machine: z.object({
|
|
@@ -776,12 +1802,14 @@ const WhoamiResponse = z.object({
|
|
|
776
1802
|
online: z.boolean(),
|
|
777
1803
|
state: z.string().nullable()
|
|
778
1804
|
}),
|
|
779
|
-
paused: z.object({ by: z.string().nullable() }).nullish()
|
|
1805
|
+
paused: z.object({ by: z.string().nullable() }).nullish(),
|
|
1806
|
+
sharing: z.enum(["only_me", "anyone"]).optional()
|
|
780
1807
|
}),
|
|
781
1808
|
workspace: z.object({
|
|
782
1809
|
id: z.string().min(1),
|
|
783
1810
|
name: z.string(),
|
|
784
|
-
slug: z.string().nullish()
|
|
1811
|
+
slug: z.string().nullish(),
|
|
1812
|
+
memberCount: z.number().int().nonnegative().optional()
|
|
785
1813
|
}),
|
|
786
1814
|
enrolledBy: z.object({
|
|
787
1815
|
name: z.string(),
|
|
@@ -819,7 +1847,7 @@ async function whoami(options) {
|
|
|
819
1847
|
};
|
|
820
1848
|
}
|
|
821
1849
|
// cli.ts
|
|
822
|
-
const DEFAULT_SERVER = "https://
|
|
1850
|
+
const DEFAULT_SERVER = "https://app.relayrunner.app";
|
|
823
1851
|
const connectCommand = defineCommand({
|
|
824
1852
|
meta: {
|
|
825
1853
|
name: "connect",
|
|
@@ -833,6 +1861,10 @@ const connectCommand = defineCommand({
|
|
|
833
1861
|
name: {
|
|
834
1862
|
type: "string",
|
|
835
1863
|
description: "Suggested machine name when signing in (default: this computer's hostname)"
|
|
1864
|
+
},
|
|
1865
|
+
share: {
|
|
1866
|
+
type: "string",
|
|
1867
|
+
description: "Who can run jobs on this machine: only-me (jobs you started) or anyone in the workspace. Skips the question."
|
|
836
1868
|
}
|
|
837
1869
|
},
|
|
838
1870
|
async run({ args }) {
|
|
@@ -847,24 +1879,22 @@ const connectCommand = defineCommand({
|
|
|
847
1879
|
}
|
|
848
1880
|
});
|
|
849
1881
|
async function connectMachine(args) {
|
|
850
|
-
const
|
|
851
|
-
const
|
|
852
|
-
const platform = {
|
|
853
|
-
os: target.os === "osx" ? "macos" : "linux",
|
|
854
|
-
arch: target.arch
|
|
855
|
-
};
|
|
1882
|
+
const share = shareArg(args.share);
|
|
1883
|
+
const platform = machinePlatform();
|
|
856
1884
|
let credentials = readCredentials();
|
|
857
|
-
const server =
|
|
1885
|
+
const server = serverFor(args.server, credentials);
|
|
858
1886
|
if (credentials && credentials.server !== server) {
|
|
859
1887
|
clack.log.warn(`This machine is enrolled with ${credentials.server}, not ${server}. Signing in again.`);
|
|
860
1888
|
credentials = null;
|
|
861
1889
|
}
|
|
862
|
-
if (!credentials)
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
}
|
|
1890
|
+
if (!credentials) credentials = await enroll(server, args.name, platform, share);
|
|
1891
|
+
else {
|
|
1892
|
+
clack.log.info(`Machine ${credentials.machine.name} in ${credentials.workspace.name} (${credentials.server})`);
|
|
1893
|
+
if (share) await applySharing(credentials, share);
|
|
1894
|
+
}
|
|
1895
|
+
if (process.stdin.isTTY && process.stdout.isTTY) await offerSetup();
|
|
867
1896
|
const runner = await ensureRunner({ log: (line) => clack.log.info(line) });
|
|
1897
|
+
const device = await detectDevice();
|
|
868
1898
|
const stop = new AbortController();
|
|
869
1899
|
const onInterrupt = () => {
|
|
870
1900
|
if (stop.signal.aborted) process.exit(130);
|
|
@@ -878,12 +1908,17 @@ async function connectMachine(args) {
|
|
|
878
1908
|
hello: {
|
|
879
1909
|
machineId: credentials.machine.id,
|
|
880
1910
|
...platform,
|
|
881
|
-
runnerVersion: runner.version
|
|
1911
|
+
runnerVersion: runner.version,
|
|
1912
|
+
device
|
|
882
1913
|
},
|
|
883
1914
|
runJob: (run, report) => runJob(run, {
|
|
884
1915
|
runner,
|
|
885
|
-
report
|
|
1916
|
+
report,
|
|
1917
|
+
onChecked: (target) => {
|
|
1918
|
+
if (target) clack.log.info(`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} Job ${run.routeId} is from ${target}`);
|
|
1919
|
+
}
|
|
886
1920
|
}),
|
|
1921
|
+
saveToken: (token) => saveRotatedToken(credentials, token),
|
|
887
1922
|
onEvent: (event) => {
|
|
888
1923
|
if (event.type === "connected") online = true;
|
|
889
1924
|
show(event);
|
|
@@ -898,18 +1933,18 @@ async function connectMachine(args) {
|
|
|
898
1933
|
case "revoked":
|
|
899
1934
|
deleteCredentials();
|
|
900
1935
|
if (!online) {
|
|
901
|
-
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.");
|
|
902
1937
|
return connectMachine({
|
|
903
1938
|
...args,
|
|
904
1939
|
server: credentials.server
|
|
905
1940
|
});
|
|
906
1941
|
}
|
|
907
|
-
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.");
|
|
908
1943
|
clack.outro("Run `relayrunner connect` again to sign in.");
|
|
909
1944
|
process.exitCode = 1;
|
|
910
1945
|
break;
|
|
911
1946
|
case "replaced":
|
|
912
|
-
clack.log.warn("Another `relayrunner connect`
|
|
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"));
|
|
913
1948
|
clack.outro("Offline here.");
|
|
914
1949
|
process.exitCode = 1;
|
|
915
1950
|
break;
|
|
@@ -919,6 +1954,115 @@ async function connectMachine(args) {
|
|
|
919
1954
|
process.exitCode = 1;
|
|
920
1955
|
}
|
|
921
1956
|
}
|
|
1957
|
+
async function askSharing(workspace) {
|
|
1958
|
+
const picked = await clack.select({
|
|
1959
|
+
message: "Who can run jobs on this machine?",
|
|
1960
|
+
options: [{
|
|
1961
|
+
value: "only-me",
|
|
1962
|
+
label: "Only me",
|
|
1963
|
+
hint: "jobs you started"
|
|
1964
|
+
}, {
|
|
1965
|
+
value: "anyone",
|
|
1966
|
+
label: `Anyone in ${workspace}`,
|
|
1967
|
+
hint: "teammates' and bots' jobs too, from repos you can open"
|
|
1968
|
+
}],
|
|
1969
|
+
initialValue: "only-me"
|
|
1970
|
+
});
|
|
1971
|
+
if (clack.isCancel(picked)) {
|
|
1972
|
+
clack.log.info("Keeping only-me. Change it any time with `relayrunner share`.");
|
|
1973
|
+
return null;
|
|
1974
|
+
}
|
|
1975
|
+
return picked;
|
|
1976
|
+
}
|
|
1977
|
+
async function applySharing(credentials, choice) {
|
|
1978
|
+
const result = await withCurrentToken(credentials, (token) => setSharing({
|
|
1979
|
+
server: credentials.server,
|
|
1980
|
+
token,
|
|
1981
|
+
sharing: toSharing(choice)
|
|
1982
|
+
}));
|
|
1983
|
+
switch (result.status) {
|
|
1984
|
+
case "ok":
|
|
1985
|
+
clack.log.info(`Sharing: ${describeSharing(result.sharing, credentials.workspace.name)}`);
|
|
1986
|
+
break;
|
|
1987
|
+
case "revoked": break;
|
|
1988
|
+
case "failed": clack.log.warn(`Couldn't set sharing: ${result.reason}. Run \`relayrunner share ${choice}\` to try again.`);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
const loginCommand = defineCommand({
|
|
1992
|
+
meta: {
|
|
1993
|
+
name: "login",
|
|
1994
|
+
description: "Sign this machine in to your workspace without putting it online. Run `relayrunner connect` afterwards to take jobs."
|
|
1995
|
+
},
|
|
1996
|
+
args: {
|
|
1997
|
+
server: {
|
|
1998
|
+
type: "string",
|
|
1999
|
+
description: `RelayRunner URL (default: $RELAYRUNNER_URL or ${DEFAULT_SERVER})`
|
|
2000
|
+
},
|
|
2001
|
+
name: {
|
|
2002
|
+
type: "string",
|
|
2003
|
+
description: "Suggested machine name (default: this computer's hostname)"
|
|
2004
|
+
},
|
|
2005
|
+
share: {
|
|
2006
|
+
type: "string",
|
|
2007
|
+
description: "Who can run jobs on this machine: only-me (jobs you started) or anyone in the workspace. Skips the question."
|
|
2008
|
+
}
|
|
2009
|
+
},
|
|
2010
|
+
async run({ args }) {
|
|
2011
|
+
clack.intro("RelayRunner");
|
|
2012
|
+
try {
|
|
2013
|
+
const share = shareArg(args.share);
|
|
2014
|
+
const saved = readCredentials();
|
|
2015
|
+
const server = serverFor(args.server, saved);
|
|
2016
|
+
if (saved && saved.server === server) {
|
|
2017
|
+
if ((await withCurrentToken(saved, (token) => whoami({
|
|
2018
|
+
server,
|
|
2019
|
+
token
|
|
2020
|
+
}))).status !== "revoked") {
|
|
2021
|
+
if (share) await applySharing(saved, share);
|
|
2022
|
+
clack.outro(`Already signed in as ${saved.machine.name} in ${saved.workspace.name}. Run \`relayrunner connect\` to go online.`);
|
|
2023
|
+
return;
|
|
2024
|
+
}
|
|
2025
|
+
clack.log.warn(`${saved.machine.name} is no longer enrolled in ${saved.workspace.name}. Signing in again.`);
|
|
2026
|
+
} else if (saved) clack.log.warn(`This machine is enrolled with ${saved.server}, not ${server}. Signing in again.`);
|
|
2027
|
+
await enroll(server, args.name, machinePlatform(), share);
|
|
2028
|
+
clack.outro("Run `relayrunner connect` to put this machine online.");
|
|
2029
|
+
} catch (error) {
|
|
2030
|
+
if (!(error instanceof LoginError || error instanceof RunnerError)) throw error;
|
|
2031
|
+
clack.log.error(error.message);
|
|
2032
|
+
process.exitCode = 1;
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
});
|
|
2036
|
+
function shareArg(value) {
|
|
2037
|
+
const share = value ? parseShareChoice(value) : null;
|
|
2038
|
+
if (value && !share) throw new RunnerError("USAGE", `--share takes ${SHARE_CHOICES.join(" or ")}, not ${JSON.stringify(value)}.`);
|
|
2039
|
+
return share;
|
|
2040
|
+
}
|
|
2041
|
+
/** An explicit --server or RELAYRUNNER_URL wins; otherwise the gateway this machine enrolled with. */
|
|
2042
|
+
function serverFor(requested, saved) {
|
|
2043
|
+
return normalizeServer(requested || process.env.RELAYRUNNER_URL || saved?.server || DEFAULT_SERVER);
|
|
2044
|
+
}
|
|
2045
|
+
function machinePlatform() {
|
|
2046
|
+
const target = runnerPlatform();
|
|
2047
|
+
return {
|
|
2048
|
+
os: target.os === "osx" ? "macos" : "linux",
|
|
2049
|
+
arch: target.arch
|
|
2050
|
+
};
|
|
2051
|
+
}
|
|
2052
|
+
/** Signs in through the browser, saves the machine token, and settles who can run jobs here. */
|
|
2053
|
+
async function enroll(server, name, platform, share) {
|
|
2054
|
+
const signedIn = await signIn(server, name || hostname(), platform);
|
|
2055
|
+
const credentials = signedIn.credentials;
|
|
2056
|
+
writeCredentials(credentials);
|
|
2057
|
+
clack.log.success(`Enrolled as ${credentials.machine.name} in ${credentials.workspace.name}. Token saved to ${credentialsPath()}.`);
|
|
2058
|
+
let choice = share;
|
|
2059
|
+
if (!choice && (signedIn.memberCount ?? 0) > 1) {
|
|
2060
|
+
if (process.stdin.isTTY && process.stdout.isTTY) choice = await askSharing(credentials.workspace.name);
|
|
2061
|
+
else clack.log.info("Only jobs you started run here. `relayrunner share anyone` lets teammates' jobs run here too.");
|
|
2062
|
+
}
|
|
2063
|
+
if (choice) await applySharing(credentials, choice);
|
|
2064
|
+
return credentials;
|
|
2065
|
+
}
|
|
922
2066
|
async function signIn(server, name, platform) {
|
|
923
2067
|
const waiting = clack.spinner();
|
|
924
2068
|
try {
|
|
@@ -961,6 +2105,9 @@ function show(event) {
|
|
|
961
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.`);
|
|
962
2106
|
else clack.log.success(`${at} Resumed${event.by ? ` by ${event.by}` : ""}. Waiting for jobs.`);
|
|
963
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;
|
|
964
2111
|
case "run-refused":
|
|
965
2112
|
clack.log.warn(`${at} Turned down job ${event.routeId}: already running one.`);
|
|
966
2113
|
break;
|
|
@@ -995,7 +2142,7 @@ const whoamiCommand = defineCommand({
|
|
|
995
2142
|
const requested = args.server || process.env.RELAYRUNNER_URL;
|
|
996
2143
|
const server = requested ? normalizeServer(requested) : credentials?.server;
|
|
997
2144
|
if (!credentials || credentials.server !== server) {
|
|
998
|
-
print(credentials ? `Not signed in to ${server}. This machine is enrolled with ${credentials.server}.` : "Not signed in. Run `relayrunner connect` to sign in.", {
|
|
2145
|
+
print(credentials ? `Not signed in to ${server}. This machine is enrolled with ${credentials.server}.` : "Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.", {
|
|
999
2146
|
status: "signed_out",
|
|
1000
2147
|
server: server ?? null
|
|
1001
2148
|
});
|
|
@@ -1007,10 +2154,10 @@ const whoamiCommand = defineCommand({
|
|
|
1007
2154
|
machine: credentials.machine,
|
|
1008
2155
|
workspace: credentials.workspace
|
|
1009
2156
|
};
|
|
1010
|
-
const result = await whoami({
|
|
2157
|
+
const result = await withCurrentToken(credentials, (token) => whoami({
|
|
1011
2158
|
server: credentials.server,
|
|
1012
|
-
token
|
|
1013
|
-
});
|
|
2159
|
+
token
|
|
2160
|
+
}));
|
|
1014
2161
|
switch (result.status) {
|
|
1015
2162
|
case "ok":
|
|
1016
2163
|
print(describeIdentity(credentials.server, result.identity), {
|
|
@@ -1043,6 +2190,7 @@ function describeIdentity(server, identity) {
|
|
|
1043
2190
|
["Platform", [machine.os, machine.arch].filter(Boolean).join(" ") || "unknown"],
|
|
1044
2191
|
["Enrolled", enrolled],
|
|
1045
2192
|
["Status", status],
|
|
2193
|
+
...machine.sharing ? [["Sharing", describeSharing(machine.sharing, workspace.name)]] : [],
|
|
1046
2194
|
["Gateway", server]
|
|
1047
2195
|
]);
|
|
1048
2196
|
}
|
|
@@ -1053,15 +2201,6 @@ function table(title, rows) {
|
|
|
1053
2201
|
const width = Math.max(...rows.map(([label]) => label.length));
|
|
1054
2202
|
return [title, ...rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`)].join("\n");
|
|
1055
2203
|
}
|
|
1056
|
-
function normalizeServer(value) {
|
|
1057
|
-
try {
|
|
1058
|
-
const url = new URL(value);
|
|
1059
|
-
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error();
|
|
1060
|
-
return url.origin;
|
|
1061
|
-
} catch {
|
|
1062
|
-
throw new RunnerError("USAGE", `Not a valid RelayRunner URL: ${value}`);
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
2204
|
function pauseCommand(paused) {
|
|
1066
2205
|
return defineCommand({
|
|
1067
2206
|
meta: {
|
|
@@ -1071,15 +2210,15 @@ function pauseCommand(paused) {
|
|
|
1071
2210
|
async run() {
|
|
1072
2211
|
const credentials = readCredentials();
|
|
1073
2212
|
if (!credentials) {
|
|
1074
|
-
console.error("Not signed in. Run `relayrunner connect` to sign in.");
|
|
2213
|
+
console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
|
|
1075
2214
|
process.exitCode = 1;
|
|
1076
2215
|
return;
|
|
1077
2216
|
}
|
|
1078
|
-
const result = await setPaused({
|
|
2217
|
+
const result = await withCurrentToken(credentials, (token) => setPaused({
|
|
1079
2218
|
server: credentials.server,
|
|
1080
|
-
token
|
|
2219
|
+
token,
|
|
1081
2220
|
paused
|
|
1082
|
-
});
|
|
2221
|
+
}));
|
|
1083
2222
|
const name = credentials.machine.name;
|
|
1084
2223
|
switch (result.status) {
|
|
1085
2224
|
case "ok":
|
|
@@ -1096,6 +2235,73 @@ function pauseCommand(paused) {
|
|
|
1096
2235
|
}
|
|
1097
2236
|
});
|
|
1098
2237
|
}
|
|
2238
|
+
const shareCommand = defineCommand({
|
|
2239
|
+
meta: {
|
|
2240
|
+
name: "share",
|
|
2241
|
+
description: "Show or change who can run jobs on this machine: only-me (jobs you started) or anyone in the workspace."
|
|
2242
|
+
},
|
|
2243
|
+
args: { who: {
|
|
2244
|
+
type: "positional",
|
|
2245
|
+
required: false,
|
|
2246
|
+
description: `${SHARE_CHOICES.join(" or ")}; leave out to show the current setting`
|
|
2247
|
+
} },
|
|
2248
|
+
async run({ args }) {
|
|
2249
|
+
const credentials = readCredentials();
|
|
2250
|
+
if (!credentials) {
|
|
2251
|
+
console.error("Not signed in. Run `relayrunner login` or `relayrunner connect` to sign in.");
|
|
2252
|
+
process.exitCode = 1;
|
|
2253
|
+
return;
|
|
2254
|
+
}
|
|
2255
|
+
const { name } = credentials.machine;
|
|
2256
|
+
const workspace = credentials.workspace.name;
|
|
2257
|
+
const revoked = () => {
|
|
2258
|
+
console.error(`${name} was removed from ${workspace} or its token is no longer valid.\nRun \`relayrunner connect\` to sign in again.`);
|
|
2259
|
+
process.exitCode = 1;
|
|
2260
|
+
};
|
|
2261
|
+
if (args.who) {
|
|
2262
|
+
const choice = parseShareChoice(args.who);
|
|
2263
|
+
if (!choice) {
|
|
2264
|
+
console.error(`Use \`relayrunner share ${SHARE_CHOICES.join("` or `relayrunner share ")}\`.`);
|
|
2265
|
+
process.exitCode = 1;
|
|
2266
|
+
return;
|
|
2267
|
+
}
|
|
2268
|
+
const result = await withCurrentToken(credentials, (token) => setSharing({
|
|
2269
|
+
server: credentials.server,
|
|
2270
|
+
token,
|
|
2271
|
+
sharing: toSharing(choice)
|
|
2272
|
+
}));
|
|
2273
|
+
if (result.status === "revoked") return revoked();
|
|
2274
|
+
if (result.status === "failed") {
|
|
2275
|
+
console.error(`Couldn't change sharing for ${name}: ${result.reason}.`);
|
|
2276
|
+
process.exitCode = 1;
|
|
2277
|
+
return;
|
|
2278
|
+
}
|
|
2279
|
+
console.log(`${name} now ${sharingMeaning(result.sharing, workspace)}.`);
|
|
2280
|
+
return;
|
|
2281
|
+
}
|
|
2282
|
+
const result = await withCurrentToken(credentials, (token) => whoami({
|
|
2283
|
+
server: credentials.server,
|
|
2284
|
+
token
|
|
2285
|
+
}));
|
|
2286
|
+
if (result.status === "revoked") return revoked();
|
|
2287
|
+
if (result.status === "unverified") {
|
|
2288
|
+
console.error(`Couldn't check sharing for ${name}: ${result.reason}.`);
|
|
2289
|
+
process.exitCode = 1;
|
|
2290
|
+
return;
|
|
2291
|
+
}
|
|
2292
|
+
const { sharing } = result.identity.machine;
|
|
2293
|
+
if (!sharing) {
|
|
2294
|
+
console.error(`${credentials.server} doesn't support sharing yet.`);
|
|
2295
|
+
process.exitCode = 1;
|
|
2296
|
+
return;
|
|
2297
|
+
}
|
|
2298
|
+
const other = sharing === "only_me" ? "anyone" : "only-me";
|
|
2299
|
+
const lines = [`${name} ${sharingMeaning(sharing, workspace)} (${toChoice(sharing)}).`];
|
|
2300
|
+
if (result.identity.workspace.memberCount === 1) lines.push(`Nobody else is in ${workspace} yet, so this matters once a teammate joins.`);
|
|
2301
|
+
lines.push(`Change it with \`relayrunner share ${other}\`.`);
|
|
2302
|
+
console.log(lines.join("\n"));
|
|
2303
|
+
}
|
|
2304
|
+
});
|
|
1099
2305
|
const main = defineCommand({
|
|
1100
2306
|
meta: {
|
|
1101
2307
|
name: "relayrunner",
|
|
@@ -1103,9 +2309,12 @@ const main = defineCommand({
|
|
|
1103
2309
|
},
|
|
1104
2310
|
subCommands: {
|
|
1105
2311
|
connect: connectCommand,
|
|
2312
|
+
login: loginCommand,
|
|
1106
2313
|
whoami: whoamiCommand,
|
|
2314
|
+
init: initCommand,
|
|
1107
2315
|
pause: pauseCommand(true),
|
|
1108
|
-
resume: pauseCommand(false)
|
|
2316
|
+
resume: pauseCommand(false),
|
|
2317
|
+
share: shareCommand
|
|
1109
2318
|
}
|
|
1110
2319
|
});
|
|
1111
2320
|
runMain(main);
|