@capybara-hq/device 0.0.0-stage → 0.1.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +2 -0
- package/README.md +103 -2
- package/bin/capybara-device.mjs +11 -0
- package/dist/api.d.ts +33 -0
- package/dist/api.js +48 -0
- package/dist/args.d.ts +39 -0
- package/dist/args.js +93 -0
- package/dist/cli.d.ts +18 -0
- package/dist/cli.js +93 -0
- package/dist/client.d.ts +39 -0
- package/dist/client.js +340 -0
- package/dist/command-log.d.ts +17 -0
- package/dist/command-log.js +28 -0
- package/dist/commands/drain.d.ts +2 -0
- package/dist/commands/drain.js +5 -0
- package/dist/commands/login.d.ts +20 -0
- package/dist/commands/login.js +132 -0
- package/dist/commands/logout.d.ts +13 -0
- package/dist/commands/logout.js +36 -0
- package/dist/commands/policy.d.ts +15 -0
- package/dist/commands/policy.js +74 -0
- package/dist/commands/service.d.ts +17 -0
- package/dist/commands/service.js +97 -0
- package/dist/commands/signal.d.ts +2 -0
- package/dist/commands/signal.js +18 -0
- package/dist/commands/start.d.ts +16 -0
- package/dist/commands/start.js +73 -0
- package/dist/commands/status.d.ts +2 -0
- package/dist/commands/status.js +32 -0
- package/dist/commands/stop.d.ts +2 -0
- package/dist/commands/stop.js +5 -0
- package/dist/exec/docker.d.ts +120 -0
- package/dist/exec/docker.js +673 -0
- package/dist/exec/fs-helper.d.ts +12 -0
- package/dist/exec/fs-helper.js +85 -0
- package/dist/exec/os.d.ts +80 -0
- package/dist/exec/os.js +398 -0
- package/dist/exec/procs.d.ts +11 -0
- package/dist/exec/procs.js +67 -0
- package/dist/exec/shared.d.ts +71 -0
- package/dist/exec/shared.js +240 -0
- package/dist/exec/types.d.ts +34 -0
- package/dist/exec/types.js +9 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/pid.d.ts +6 -0
- package/dist/pid.js +36 -0
- package/dist/policy.d.ts +42 -0
- package/dist/policy.js +97 -0
- package/dist/server-ops.d.ts +10 -0
- package/dist/server-ops.js +74 -0
- package/dist/service/launchd.d.ts +17 -0
- package/dist/service/launchd.js +59 -0
- package/dist/service/systemd.d.ts +5 -0
- package/dist/service/systemd.js +28 -0
- package/dist/state.d.ts +40 -0
- package/dist/state.js +117 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +11 -0
- package/package.json +42 -3
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { CommandLog } from "./command-log.js";
|
|
2
|
+
import type { Executor } from "./exec/types.js";
|
|
3
|
+
import type { Credential } from "./state.js";
|
|
4
|
+
export declare const OUTDATED_MESSAGE = "This capybara-device is too old for the deployment. Upgrade it: npm install -g @capybara-hq/device";
|
|
5
|
+
export declare const DISCONNECTED_MESSAGE = "This machine was disconnected from the deployment. Run capybara-device logout, then capybara-device login.";
|
|
6
|
+
export declare const REPLACED_MESSAGE = "This machine connected elsewhere: a newer connection to this environment replaced this one.";
|
|
7
|
+
export declare const DELETED_MESSAGE = "The environment was deleted on the deployment. The files on this machine stay where they are.";
|
|
8
|
+
/** The answer sent instead of a result whose frame would exceed the connection's frame limit. */
|
|
9
|
+
export declare const TOO_LARGE_MESSAGE = "result larger than the connection's frame limit";
|
|
10
|
+
export interface ConnectOptions {
|
|
11
|
+
log?: CommandLog;
|
|
12
|
+
err?: (line: string) => void;
|
|
13
|
+
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
14
|
+
random?: () => number;
|
|
15
|
+
now?: () => number;
|
|
16
|
+
programVersion?: string;
|
|
17
|
+
/** A connection must stay up this long before the backoff resets (default 10 s). */
|
|
18
|
+
stableMs?: number;
|
|
19
|
+
/** Terminate a socket that heard nothing from the server for this long (default 60 s). */
|
|
20
|
+
livenessMs?: number;
|
|
21
|
+
/** Terminate a socket still closing this long after we asked it to close (default 2 s). */
|
|
22
|
+
closeTimeoutMs?: number;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* A running connection. `done` resolves with the exit code once the program should end: 0 for the
|
|
26
|
+
* terminal conditions (revoked, outdated, replaced, deleted, stopped, drained), so a service
|
|
27
|
+
* manager that restarts on failure leaves it stopped.
|
|
28
|
+
*/
|
|
29
|
+
export interface Connection {
|
|
30
|
+
readonly done: Promise<number>;
|
|
31
|
+
/** Accept no new operations; end when the running ones have finished. */
|
|
32
|
+
drain(): void;
|
|
33
|
+
/** Close the socket and end. */
|
|
34
|
+
stop(): void;
|
|
35
|
+
}
|
|
36
|
+
/** Backoff before reconnect attempt `attempt` (0-based): 1 s doubling to 60 s, with jitter. */
|
|
37
|
+
export declare function backoffMs(attempt: number, random: () => number): number;
|
|
38
|
+
/** Connects this machine to the deployment and serves operations until told to stop. */
|
|
39
|
+
export declare function connect(cred: Credential, executor: Executor, opts?: ConnectOptions): Connection;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import WebSocket from "ws";
|
|
3
|
+
import { logEntryFor, runOp } from "./server-ops.js";
|
|
4
|
+
import { PROGRAM_VERSION } from "./version.js";
|
|
5
|
+
export const OUTDATED_MESSAGE = "This capybara-device is too old for the deployment. Upgrade it: npm install -g @capybara-hq/device";
|
|
6
|
+
export const DISCONNECTED_MESSAGE = "This machine was disconnected from the deployment. Run capybara-device logout, then capybara-device login.";
|
|
7
|
+
export const REPLACED_MESSAGE = "This machine connected elsewhere: a newer connection to this environment replaced this one.";
|
|
8
|
+
export const DELETED_MESSAGE = "The environment was deleted on the deployment. The files on this machine stay where they are.";
|
|
9
|
+
/** The answer sent instead of a result whose frame would exceed the connection's frame limit. */
|
|
10
|
+
export const TOO_LARGE_MESSAGE = "result larger than the connection's frame limit";
|
|
11
|
+
/** A failing connection is reported at most this often. */
|
|
12
|
+
const FAILURE_REPORT_INTERVAL_MS = 60_000;
|
|
13
|
+
const BACKOFF_BASE_MS = 1000;
|
|
14
|
+
const BACKOFF_MAX_MS = 60_000;
|
|
15
|
+
/** Backoff before reconnect attempt `attempt` (0-based): 1 s doubling to 60 s, with jitter. */
|
|
16
|
+
export function backoffMs(attempt, random) {
|
|
17
|
+
const ceiling = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** attempt);
|
|
18
|
+
return Math.round(ceiling * (0.5 + random() * 0.5));
|
|
19
|
+
}
|
|
20
|
+
function defaultSleep(ms, signal) {
|
|
21
|
+
return new Promise((resolve) => {
|
|
22
|
+
if (signal.aborted)
|
|
23
|
+
return resolve();
|
|
24
|
+
const t = setTimeout(resolve, ms);
|
|
25
|
+
signal.addEventListener("abort", () => {
|
|
26
|
+
clearTimeout(t);
|
|
27
|
+
resolve();
|
|
28
|
+
}, { once: true });
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/** Connects this machine to the deployment and serves operations until told to stop. */
|
|
32
|
+
export function connect(cred, executor, opts = {}) {
|
|
33
|
+
const err = opts.err ?? ((l) => console.error(l));
|
|
34
|
+
const sleep = opts.sleep ?? defaultSleep;
|
|
35
|
+
const random = opts.random ?? Math.random;
|
|
36
|
+
const now = opts.now ?? Date.now;
|
|
37
|
+
const graceMs = cred.reconnectGraceSeconds * 1000;
|
|
38
|
+
const stableMs = opts.stableMs ?? 10_000;
|
|
39
|
+
const livenessMs = opts.livenessMs ?? 60_000;
|
|
40
|
+
const closeTimeoutMs = opts.closeTimeoutMs ?? 2000;
|
|
41
|
+
const lifetime = new AbortController();
|
|
42
|
+
let ws;
|
|
43
|
+
let draining = false;
|
|
44
|
+
let stopping = false;
|
|
45
|
+
let exitAfterStop;
|
|
46
|
+
let session;
|
|
47
|
+
let drainTimer;
|
|
48
|
+
const running = new Map();
|
|
49
|
+
/** Requests the kernel gave up on: never started, or their result is dropped. */
|
|
50
|
+
const cancelled = new Map();
|
|
51
|
+
/** Requests already seen (running, answered): a repeated req is ignored. */
|
|
52
|
+
const known = new Map();
|
|
53
|
+
/** Answers produced while no socket was open, with their expiry. */
|
|
54
|
+
const pending = new Map();
|
|
55
|
+
const prune = () => {
|
|
56
|
+
const t = now();
|
|
57
|
+
for (const m of [cancelled, known])
|
|
58
|
+
for (const [k, exp] of m)
|
|
59
|
+
if (exp <= t)
|
|
60
|
+
m.delete(k);
|
|
61
|
+
for (const [k, v] of pending)
|
|
62
|
+
if (v.expires <= t)
|
|
63
|
+
pending.delete(k);
|
|
64
|
+
};
|
|
65
|
+
const isOpen = () => ws !== undefined && ws.readyState === WebSocket.OPEN;
|
|
66
|
+
/** `res`, or an error answer when its frame would exceed the deployment's frame limit. */
|
|
67
|
+
const fit = (res) => Buffer.byteLength(JSON.stringify(res)) <= cred.maxFrameBytes
|
|
68
|
+
? res
|
|
69
|
+
: {
|
|
70
|
+
type: "res",
|
|
71
|
+
id: res.id,
|
|
72
|
+
ok: false,
|
|
73
|
+
error: { kind: "error", message: TOO_LARGE_MESSAGE },
|
|
74
|
+
};
|
|
75
|
+
const deliver = (answer) => {
|
|
76
|
+
const res = fit(answer);
|
|
77
|
+
if (isOpen()) {
|
|
78
|
+
ws?.send(JSON.stringify(res), (e) => {
|
|
79
|
+
if (e)
|
|
80
|
+
pending.set(res.id, { res, expires: now() + graceMs });
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
pending.set(res.id, { res, expires: now() + graceMs });
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
const endSession = (end) => {
|
|
88
|
+
const s = session;
|
|
89
|
+
session = undefined;
|
|
90
|
+
s?.(end);
|
|
91
|
+
};
|
|
92
|
+
/** Ends the loop: no more reconnects, and a backoff sleep in progress wakes up. */
|
|
93
|
+
const halt = () => {
|
|
94
|
+
stopping = true;
|
|
95
|
+
lifetime.abort();
|
|
96
|
+
};
|
|
97
|
+
/** Asks the socket to close; terminates it if the close handshake does not finish. */
|
|
98
|
+
const closeSocket = (sock) => {
|
|
99
|
+
if (!sock)
|
|
100
|
+
return;
|
|
101
|
+
sock.close(1000);
|
|
102
|
+
setTimeout(() => sock.terminate(), closeTimeoutMs).unref();
|
|
103
|
+
};
|
|
104
|
+
const finishDrain = () => {
|
|
105
|
+
clearTimeout(drainTimer);
|
|
106
|
+
exitAfterStop = { exit: 0 };
|
|
107
|
+
halt();
|
|
108
|
+
closeSocket(ws);
|
|
109
|
+
if (!isOpen())
|
|
110
|
+
endSession({ exit: 0 });
|
|
111
|
+
};
|
|
112
|
+
const maybeFinishDrain = () => {
|
|
113
|
+
if (!draining || running.size > 0 || stopping)
|
|
114
|
+
return;
|
|
115
|
+
prune();
|
|
116
|
+
if (pending.size > 0 && !isOpen()) {
|
|
117
|
+
// Results wait for a reconnect, at most the grace.
|
|
118
|
+
drainTimer ??= setTimeout(finishDrain, graceMs);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
finishDrain();
|
|
122
|
+
};
|
|
123
|
+
const handleReq = (req) => {
|
|
124
|
+
prune();
|
|
125
|
+
if (cancelled.has(req.id))
|
|
126
|
+
return; // the kernel gave up before it started: never start it
|
|
127
|
+
if (running.has(req.id) || known.has(req.id))
|
|
128
|
+
return;
|
|
129
|
+
known.set(req.id, now() + graceMs + req.deadlineMs);
|
|
130
|
+
if (draining && req.op !== "stop") {
|
|
131
|
+
deliver({
|
|
132
|
+
type: "res",
|
|
133
|
+
id: req.id,
|
|
134
|
+
ok: false,
|
|
135
|
+
error: { kind: "error", message: "draining" },
|
|
136
|
+
});
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const ctl = new AbortController();
|
|
140
|
+
running.set(req.id, ctl);
|
|
141
|
+
void runOp(executor, req, ctl.signal).then((res) => {
|
|
142
|
+
running.delete(req.id);
|
|
143
|
+
opts.log?.append(logEntryFor(req, res, new Date(now())));
|
|
144
|
+
if (cancelled.has(req.id)) {
|
|
145
|
+
// The kernel is no longer waiting for this one.
|
|
146
|
+
}
|
|
147
|
+
else if (req.op === "stop") {
|
|
148
|
+
const reason = req.args.reason;
|
|
149
|
+
exitAfterStop =
|
|
150
|
+
reason === "revoked"
|
|
151
|
+
? { exit: 0, message: DISCONNECTED_MESSAGE }
|
|
152
|
+
: { exit: 0, message: DELETED_MESSAGE };
|
|
153
|
+
halt();
|
|
154
|
+
const sock = ws;
|
|
155
|
+
if (isOpen() && sock) {
|
|
156
|
+
sock.send(JSON.stringify(res), () => closeSocket(sock));
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
endSession(exitAfterStop);
|
|
160
|
+
}
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
deliver(res);
|
|
165
|
+
}
|
|
166
|
+
maybeFinishDrain();
|
|
167
|
+
});
|
|
168
|
+
};
|
|
169
|
+
const handleCancel = (id) => {
|
|
170
|
+
prune();
|
|
171
|
+
cancelled.set(id, now() + graceMs);
|
|
172
|
+
pending.delete(id);
|
|
173
|
+
running.get(id)?.abort();
|
|
174
|
+
};
|
|
175
|
+
const onMessage = (raw) => {
|
|
176
|
+
let frame;
|
|
177
|
+
try {
|
|
178
|
+
frame = parseDeviceFrame(raw, "kernel");
|
|
179
|
+
}
|
|
180
|
+
catch (e) {
|
|
181
|
+
// Best effort: tell the kernel a request it sent was unusable.
|
|
182
|
+
try {
|
|
183
|
+
const o = JSON.parse(raw);
|
|
184
|
+
if (o.type === "req" && typeof o.id === "string" && o.id !== "") {
|
|
185
|
+
deliver({
|
|
186
|
+
type: "res",
|
|
187
|
+
id: o.id,
|
|
188
|
+
ok: false,
|
|
189
|
+
error: { kind: "error", message: `invalid request: ${e.message}` },
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
// not JSON: ignore
|
|
195
|
+
}
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (frame.type === "req")
|
|
199
|
+
handleReq(frame);
|
|
200
|
+
else if (frame.type === "cancel")
|
|
201
|
+
handleCancel(frame.id);
|
|
202
|
+
};
|
|
203
|
+
const hello = () => ({
|
|
204
|
+
type: "hello",
|
|
205
|
+
protocol: DEVICE_PROTOCOL_VERSION,
|
|
206
|
+
programVersion: opts.programVersion ?? PROGRAM_VERSION,
|
|
207
|
+
os: process.platform === "darwin" ? "darwin" : "linux",
|
|
208
|
+
arch: process.arch,
|
|
209
|
+
mode: executor.mode,
|
|
210
|
+
roots: executor.roots,
|
|
211
|
+
sessionIsolation: false,
|
|
212
|
+
});
|
|
213
|
+
let attempt = 0;
|
|
214
|
+
/** When a failing connection was last reported; reset once a connection stays up. */
|
|
215
|
+
let lastReport;
|
|
216
|
+
/** Reports why connecting keeps failing, at most once a minute. */
|
|
217
|
+
const reportFailure = (why) => {
|
|
218
|
+
const t = now();
|
|
219
|
+
if (lastReport !== undefined && t - lastReport < FAILURE_REPORT_INTERVAL_MS)
|
|
220
|
+
return;
|
|
221
|
+
lastReport = t;
|
|
222
|
+
err(`${why} Retrying.`);
|
|
223
|
+
};
|
|
224
|
+
const runSession = () => new Promise((resolve) => {
|
|
225
|
+
session = resolve;
|
|
226
|
+
const sock = new WebSocket(cred.connectUrl, {
|
|
227
|
+
headers: {
|
|
228
|
+
Authorization: `Bearer ${cred.credential}`,
|
|
229
|
+
"X-Capybara-Device-Protocol": String(DEVICE_PROTOCOL_VERSION),
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
ws = sock;
|
|
233
|
+
let liveness;
|
|
234
|
+
let stable;
|
|
235
|
+
let opened = false;
|
|
236
|
+
/** The deployment answered the upgrade with an HTTP status (already handled). */
|
|
237
|
+
let answered = false;
|
|
238
|
+
const heard = () => {
|
|
239
|
+
clearTimeout(liveness);
|
|
240
|
+
liveness = setTimeout(() => sock.terminate(), livenessMs);
|
|
241
|
+
};
|
|
242
|
+
sock.on("ping", heard);
|
|
243
|
+
sock.on("open", () => {
|
|
244
|
+
opened = true;
|
|
245
|
+
heard();
|
|
246
|
+
stable = setTimeout(() => {
|
|
247
|
+
attempt = 0;
|
|
248
|
+
lastReport = undefined;
|
|
249
|
+
}, stableMs);
|
|
250
|
+
sock.send(JSON.stringify(hello()));
|
|
251
|
+
prune();
|
|
252
|
+
for (const [id, p] of pending) {
|
|
253
|
+
pending.delete(id);
|
|
254
|
+
deliver(p.res);
|
|
255
|
+
}
|
|
256
|
+
maybeFinishDrain();
|
|
257
|
+
});
|
|
258
|
+
sock.on("message", (data, isBinary) => {
|
|
259
|
+
heard();
|
|
260
|
+
if (isBinary)
|
|
261
|
+
return;
|
|
262
|
+
onMessage(data.toString("utf8"));
|
|
263
|
+
});
|
|
264
|
+
sock.on("unexpected-response", (_req, res) => {
|
|
265
|
+
answered = true;
|
|
266
|
+
const status = res.statusCode ?? 0;
|
|
267
|
+
res.resume();
|
|
268
|
+
sock.terminate();
|
|
269
|
+
if (status === 401)
|
|
270
|
+
return endSession({ exit: 0, message: DISCONNECTED_MESSAGE });
|
|
271
|
+
if (status === 426)
|
|
272
|
+
return endSession({ exit: 0, message: OUTDATED_MESSAGE });
|
|
273
|
+
reportFailure(status === 404
|
|
274
|
+
? `Connecting to ${cred.connectUrl} failed: HTTP 404. The deployment must route ` +
|
|
275
|
+
"/device/connect to its gateway (see the deployment docs)."
|
|
276
|
+
: `Connecting to ${cred.connectUrl} failed: HTTP ${status}.`);
|
|
277
|
+
endSession({ reconnect: true });
|
|
278
|
+
});
|
|
279
|
+
sock.on("error", (e) => {
|
|
280
|
+
// 'close' follows; the reason is decided there. A failure before the socket opened is a
|
|
281
|
+
// connection attempt that did not reach the deployment.
|
|
282
|
+
if (!opened && !answered && !stopping) {
|
|
283
|
+
reportFailure(`Cannot reach ${cred.connectUrl}: ${e.message}.`);
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
sock.on("close", (code, reason) => {
|
|
287
|
+
clearTimeout(liveness);
|
|
288
|
+
clearTimeout(stable);
|
|
289
|
+
if (ws === sock)
|
|
290
|
+
ws = undefined;
|
|
291
|
+
if (exitAfterStop)
|
|
292
|
+
return endSession(exitAfterStop);
|
|
293
|
+
if (code === 4002)
|
|
294
|
+
return endSession({ exit: 0, message: REPLACED_MESSAGE });
|
|
295
|
+
if (code === 4003)
|
|
296
|
+
return endSession({ exit: 0, message: DISCONNECTED_MESSAGE });
|
|
297
|
+
if (code === 4400) {
|
|
298
|
+
const why = reason.toString("utf8");
|
|
299
|
+
reportFailure(`The deployment closed the connection: 4400${why ? ` ${why}` : ""}.`);
|
|
300
|
+
}
|
|
301
|
+
endSession({ reconnect: true });
|
|
302
|
+
});
|
|
303
|
+
});
|
|
304
|
+
const loop = async () => {
|
|
305
|
+
while (!stopping) {
|
|
306
|
+
const end = await runSession();
|
|
307
|
+
if ("exit" in end) {
|
|
308
|
+
if (end.message)
|
|
309
|
+
err(end.message);
|
|
310
|
+
return end.exit;
|
|
311
|
+
}
|
|
312
|
+
if (stopping)
|
|
313
|
+
break;
|
|
314
|
+
await sleep(backoffMs(attempt++, random), lifetime.signal);
|
|
315
|
+
}
|
|
316
|
+
if (exitAfterStop?.message)
|
|
317
|
+
err(exitAfterStop.message);
|
|
318
|
+
return exitAfterStop?.exit ?? 0;
|
|
319
|
+
};
|
|
320
|
+
const done = loop().finally(() => {
|
|
321
|
+
clearTimeout(drainTimer);
|
|
322
|
+
lifetime.abort();
|
|
323
|
+
for (const ctl of running.values())
|
|
324
|
+
ctl.abort();
|
|
325
|
+
});
|
|
326
|
+
return {
|
|
327
|
+
done,
|
|
328
|
+
drain() {
|
|
329
|
+
draining = true;
|
|
330
|
+
maybeFinishDrain();
|
|
331
|
+
},
|
|
332
|
+
stop() {
|
|
333
|
+
halt();
|
|
334
|
+
if (ws)
|
|
335
|
+
closeSocket(ws);
|
|
336
|
+
else
|
|
337
|
+
endSession({ exit: 0 });
|
|
338
|
+
},
|
|
339
|
+
};
|
|
340
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export declare const COMMAND_LOG_MAX_BYTES: number;
|
|
2
|
+
export interface CommandLogEntry {
|
|
3
|
+
time: string;
|
|
4
|
+
op: string;
|
|
5
|
+
tag: string | null;
|
|
6
|
+
actor: {
|
|
7
|
+
accountId: string;
|
|
8
|
+
} | null;
|
|
9
|
+
exitCode: number | null;
|
|
10
|
+
}
|
|
11
|
+
/** One JSON line per operation in `<stateDir>/commands.log`; rotated to `commands.log.1` at 10 MiB. */
|
|
12
|
+
export declare class CommandLog {
|
|
13
|
+
private readonly maxBytes;
|
|
14
|
+
private readonly file;
|
|
15
|
+
constructor(stateDir: string, maxBytes?: number);
|
|
16
|
+
append(entry: CommandLogEntry): void;
|
|
17
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
export const COMMAND_LOG_MAX_BYTES = 10 * 1024 * 1024;
|
|
4
|
+
/** One JSON line per operation in `<stateDir>/commands.log`; rotated to `commands.log.1` at 10 MiB. */
|
|
5
|
+
export class CommandLog {
|
|
6
|
+
maxBytes;
|
|
7
|
+
file;
|
|
8
|
+
constructor(stateDir, maxBytes = COMMAND_LOG_MAX_BYTES) {
|
|
9
|
+
this.maxBytes = maxBytes;
|
|
10
|
+
this.file = join(stateDir, "commands.log");
|
|
11
|
+
}
|
|
12
|
+
append(entry) {
|
|
13
|
+
try {
|
|
14
|
+
mkdirSync(join(this.file, ".."), { recursive: true, mode: 0o700 });
|
|
15
|
+
try {
|
|
16
|
+
if (statSync(this.file).size >= this.maxBytes)
|
|
17
|
+
renameSync(this.file, `${this.file}.1`);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
// no file yet
|
|
21
|
+
}
|
|
22
|
+
appendFileSync(this.file, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
// The local log never fails an operation.
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { signalRunning } from "./signal.js";
|
|
2
|
+
/** `drain`: SIGUSR2 to the running program: no new commands, stop when the running ones finish. */
|
|
3
|
+
export function drain(stateDir, out, err, kill) {
|
|
4
|
+
return signalRunning(stateDir, "SIGUSR2", "Draining capybara-device.", out, err, kill);
|
|
5
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type FetchFn } from "../api.js";
|
|
2
|
+
import type { Command } from "../args.js";
|
|
3
|
+
export interface LoginDeps {
|
|
4
|
+
stateDir: string;
|
|
5
|
+
home: string;
|
|
6
|
+
fetch?: FetchFn;
|
|
7
|
+
sleep?: (ms: number) => Promise<void>;
|
|
8
|
+
openBrowser?: (url: string) => void;
|
|
9
|
+
out?: (line: string) => void;
|
|
10
|
+
err?: (line: string) => void;
|
|
11
|
+
platform?: NodeJS.Platform;
|
|
12
|
+
arch?: string;
|
|
13
|
+
hostname?: string;
|
|
14
|
+
}
|
|
15
|
+
/** Normalises the deployment URL: http(s) origin plus optional path prefix, no trailing slash. */
|
|
16
|
+
export declare function normalizeUrl(raw: string): string;
|
|
17
|
+
/** `login`: the device authorization flow. Returns the exit code. */
|
|
18
|
+
export declare function login(cmd: Extract<Command, {
|
|
19
|
+
command: "login";
|
|
20
|
+
}>, deps: LoginDeps): Promise<number>;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { hostname } from "node:os";
|
|
3
|
+
import { isAbsolute, resolve } from "node:path";
|
|
4
|
+
import { ApiError, authorize, programVersion, token } from "../api.js";
|
|
5
|
+
import { prepareEnvironmentDir } from "../exec/shared.js";
|
|
6
|
+
import { DEFAULT_MAX_FRAME_BYTES, defaultWorkDir, readCredential, writeCredential, } from "../state.js";
|
|
7
|
+
const SLOW_DOWN_STEP_SECONDS = 5;
|
|
8
|
+
function defaultOpen(platform) {
|
|
9
|
+
return (url) => {
|
|
10
|
+
const bin = platform === "darwin" ? "open" : "xdg-open";
|
|
11
|
+
try {
|
|
12
|
+
const child = spawn(bin, [url], { stdio: "ignore", detached: true });
|
|
13
|
+
child.on("error", () => { });
|
|
14
|
+
child.unref();
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// The URL is printed anyway.
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** Normalises the deployment URL: http(s) origin plus optional path prefix, no trailing slash. */
|
|
22
|
+
export function normalizeUrl(raw) {
|
|
23
|
+
let u;
|
|
24
|
+
try {
|
|
25
|
+
u = new URL(raw);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new Error(`--url is not a valid URL: ${raw}`);
|
|
29
|
+
}
|
|
30
|
+
if (u.protocol !== "https:" && u.protocol !== "http:") {
|
|
31
|
+
throw new Error("--url must start with https:// or http://");
|
|
32
|
+
}
|
|
33
|
+
return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
|
|
34
|
+
}
|
|
35
|
+
/** `login`: the device authorization flow. Returns the exit code. */
|
|
36
|
+
export async function login(cmd, deps) {
|
|
37
|
+
const out = deps.out ?? ((l) => console.log(l));
|
|
38
|
+
const err = deps.err ?? ((l) => console.error(l));
|
|
39
|
+
const fetchFn = deps.fetch ?? fetch;
|
|
40
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
41
|
+
const platform = deps.platform ?? process.platform;
|
|
42
|
+
const arch = deps.arch ?? process.arch;
|
|
43
|
+
let baseUrl;
|
|
44
|
+
try {
|
|
45
|
+
baseUrl = normalizeUrl(cmd.url);
|
|
46
|
+
}
|
|
47
|
+
catch (e) {
|
|
48
|
+
err(e.message);
|
|
49
|
+
return 2;
|
|
50
|
+
}
|
|
51
|
+
if (platform !== "darwin" && platform !== "linux") {
|
|
52
|
+
err("capybara-device runs on macOS and Linux. On Windows use WSL or Docker.");
|
|
53
|
+
return 1;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
if (readCredential(deps.stateDir) !== undefined) {
|
|
57
|
+
err("This machine is already logged in. Run `capybara-device logout` first.");
|
|
58
|
+
return 1;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
err(`Replacing the unusable credential file: ${e.message}`);
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
const auth = await authorize(fetchFn, baseUrl, {
|
|
66
|
+
name: (deps.hostname ?? hostname()).slice(0, 64) || "device",
|
|
67
|
+
os: platform,
|
|
68
|
+
arch,
|
|
69
|
+
programVersion: programVersion(),
|
|
70
|
+
});
|
|
71
|
+
out(`Open ${auth.verificationUriComplete} and confirm the code ${auth.userCode}`);
|
|
72
|
+
if (cmd.browser)
|
|
73
|
+
(deps.openBrowser ?? defaultOpen(platform))(auth.verificationUriComplete);
|
|
74
|
+
let interval = Number.isFinite(auth.interval) && auth.interval >= 1 ? auth.interval : 5;
|
|
75
|
+
const expiresIn = Number.isFinite(auth.expiresIn) && auth.expiresIn > 0 ? auth.expiresIn : 600;
|
|
76
|
+
let waited = 0;
|
|
77
|
+
for (;;) {
|
|
78
|
+
await sleep(interval * 1000);
|
|
79
|
+
waited += interval;
|
|
80
|
+
try {
|
|
81
|
+
const granted = await token(fetchFn, baseUrl, auth.deviceCode);
|
|
82
|
+
const dir = cmd.dir === undefined
|
|
83
|
+
? defaultWorkDir(granted.environmentId, deps.home)
|
|
84
|
+
: isAbsolute(cmd.dir)
|
|
85
|
+
? cmd.dir
|
|
86
|
+
: resolve(cmd.dir);
|
|
87
|
+
// Recreates a lost directory, marker or root: the environment starts afresh.
|
|
88
|
+
prepareEnvironmentDir(dir);
|
|
89
|
+
writeCredential(deps.stateDir, {
|
|
90
|
+
url: baseUrl,
|
|
91
|
+
connectUrl: granted.connectUrl,
|
|
92
|
+
credential: granted.credential,
|
|
93
|
+
orgId: granted.orgId,
|
|
94
|
+
environmentId: granted.environmentId,
|
|
95
|
+
dir,
|
|
96
|
+
mode: cmd.mode,
|
|
97
|
+
reconnectGraceSeconds: granted.reconnectGraceSeconds,
|
|
98
|
+
maxFrameBytes: granted.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES,
|
|
99
|
+
});
|
|
100
|
+
out(`Logged in. Environment ${granted.environmentId}, working directory ${dir}`);
|
|
101
|
+
return 0;
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
if (!(e instanceof ApiError))
|
|
105
|
+
throw e;
|
|
106
|
+
if (e.code === "device.slow_down")
|
|
107
|
+
interval += SLOW_DOWN_STEP_SECONDS;
|
|
108
|
+
else if (e.code === "device.authorization_pending" || e.status === 0 || e.status >= 500) {
|
|
109
|
+
// Keep polling at the normal interval: pending, a network blip or a server error.
|
|
110
|
+
}
|
|
111
|
+
else if (e.code === "device.expired") {
|
|
112
|
+
err("The code expired before it was approved. Run `capybara-device login` again.");
|
|
113
|
+
return 1;
|
|
114
|
+
}
|
|
115
|
+
else if (e.code === "device.denied") {
|
|
116
|
+
err("The login was denied in the browser.");
|
|
117
|
+
return 1;
|
|
118
|
+
}
|
|
119
|
+
else
|
|
120
|
+
throw e;
|
|
121
|
+
if (waited >= expiresIn) {
|
|
122
|
+
err("The code expired before it was approved. Run `capybara-device login` again.");
|
|
123
|
+
return 1;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
err(`login failed: ${e.message}`);
|
|
130
|
+
return 1;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface LogoutDeps {
|
|
2
|
+
out: (line: string) => void;
|
|
3
|
+
err?: (line: string) => void;
|
|
4
|
+
kill?: typeof process.kill;
|
|
5
|
+
sleep?: (ms: number) => Promise<void>;
|
|
6
|
+
/** How long to wait for a running program to exit (default 5 s). */
|
|
7
|
+
waitMs?: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* `logout`: stops a running program, then forgets the credential on this machine. Revoking it on
|
|
11
|
+
* the platform is done there.
|
|
12
|
+
*/
|
|
13
|
+
export declare function logout(stateDir: string, deps: LogoutDeps): Promise<number>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { isAlive, readRunningPid } from "../pid.js";
|
|
2
|
+
import { removeCredential } from "../state.js";
|
|
3
|
+
const POLL_MS = 100;
|
|
4
|
+
/**
|
|
5
|
+
* `logout`: stops a running program, then forgets the credential on this machine. Revoking it on
|
|
6
|
+
* the platform is done there.
|
|
7
|
+
*/
|
|
8
|
+
export async function logout(stateDir, deps) {
|
|
9
|
+
const { out } = deps;
|
|
10
|
+
const err = deps.err ?? out;
|
|
11
|
+
const kill = deps.kill ?? process.kill;
|
|
12
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
13
|
+
const pid = readRunningPid(stateDir, kill);
|
|
14
|
+
if (pid !== undefined && pid !== process.pid) {
|
|
15
|
+
out(`Stopping the running capybara-device (pid ${pid}).`);
|
|
16
|
+
try {
|
|
17
|
+
kill(pid, "SIGTERM");
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
// It exited in between.
|
|
21
|
+
}
|
|
22
|
+
const waitMs = deps.waitMs ?? 5000;
|
|
23
|
+
let waited = 0;
|
|
24
|
+
while (isAlive(pid, kill) && waited < waitMs) {
|
|
25
|
+
await sleep(POLL_MS);
|
|
26
|
+
waited += POLL_MS;
|
|
27
|
+
}
|
|
28
|
+
if (isAlive(pid, kill)) {
|
|
29
|
+
err(`capybara-device (pid ${pid}) is still running; it keeps its connection until it exits.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
out(removeCredential(stateDir)
|
|
33
|
+
? "Logged out. The working directory was left in place."
|
|
34
|
+
: "Not logged in.");
|
|
35
|
+
return 0;
|
|
36
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Command } from "../args.js";
|
|
2
|
+
export interface PolicyDeps {
|
|
3
|
+
stateDir: string;
|
|
4
|
+
out: (line: string) => void;
|
|
5
|
+
err: (line: string) => void;
|
|
6
|
+
}
|
|
7
|
+
/** What the OS mode does not enforce yet, shown with every `show` and `set`. */
|
|
8
|
+
export declare const NOT_ENFORCED_NOTE: string;
|
|
9
|
+
/**
|
|
10
|
+
* `policy show` prints the local policy; `policy set <key> <value>` changes one field. Only the
|
|
11
|
+
* machine's user edits this file: the cloud never writes it. Changes apply at the next start.
|
|
12
|
+
*/
|
|
13
|
+
export declare function policyCommand(cmd: Extract<Command, {
|
|
14
|
+
command: "policy";
|
|
15
|
+
}>, deps: PolicyDeps): number;
|