@capybara-hq/device 0.1.0-rc.1 → 0.1.0-rc.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +205 -44
  2. package/dist/api.d.ts +6 -1
  3. package/dist/args.d.ts +14 -3
  4. package/dist/args.js +74 -10
  5. package/dist/cli.d.ts +27 -4
  6. package/dist/cli.js +81 -11
  7. package/dist/client.d.ts +19 -6
  8. package/dist/client.js +93 -19
  9. package/dist/command-log.d.ts +8 -0
  10. package/dist/commands/drain.d.ts +14 -1
  11. package/dist/commands/drain.js +31 -2
  12. package/dist/commands/login.d.ts +3 -0
  13. package/dist/commands/login.js +96 -11
  14. package/dist/commands/logout.d.ts +2 -0
  15. package/dist/commands/logout.js +1 -1
  16. package/dist/commands/mode.d.ts +69 -0
  17. package/dist/commands/mode.js +129 -0
  18. package/dist/commands/policy.d.ts +13 -4
  19. package/dist/commands/policy.js +162 -33
  20. package/dist/commands/service.d.ts +26 -4
  21. package/dist/commands/service.js +242 -19
  22. package/dist/commands/signal.d.ts +6 -2
  23. package/dist/commands/signal.js +7 -4
  24. package/dist/commands/start.d.ts +18 -3
  25. package/dist/commands/start.js +46 -7
  26. package/dist/commands/status.js +12 -4
  27. package/dist/commands/stop.d.ts +20 -2
  28. package/dist/commands/stop.js +26 -3
  29. package/dist/exec/docker.d.ts +41 -13
  30. package/dist/exec/docker.js +123 -57
  31. package/dist/exec/fs-helper.d.ts +13 -8
  32. package/dist/exec/fs-helper.js +31 -13
  33. package/dist/exec/groups.d.ts +42 -0
  34. package/dist/exec/groups.js +100 -0
  35. package/dist/exec/host.d.ts +53 -0
  36. package/dist/exec/host.js +183 -0
  37. package/dist/exec/os.d.ts +85 -15
  38. package/dist/exec/os.js +208 -36
  39. package/dist/exec/reap.d.ts +41 -0
  40. package/dist/exec/reap.js +89 -0
  41. package/dist/exec/sandbox-messages.d.ts +14 -0
  42. package/dist/exec/sandbox-messages.js +21 -0
  43. package/dist/exec/shared.d.ts +42 -13
  44. package/dist/exec/shared.js +94 -16
  45. package/dist/exec/switch.d.ts +98 -0
  46. package/dist/exec/switch.js +175 -0
  47. package/dist/exec/types.d.ts +28 -4
  48. package/dist/index.d.ts +1 -1
  49. package/dist/network.d.ts +45 -0
  50. package/dist/network.js +154 -0
  51. package/dist/pid.d.ts +44 -3
  52. package/dist/pid.js +110 -7
  53. package/dist/policy-ops.d.ts +47 -0
  54. package/dist/policy-ops.js +90 -0
  55. package/dist/policy-store.d.ts +43 -0
  56. package/dist/policy-store.js +94 -0
  57. package/dist/policy.d.ts +36 -16
  58. package/dist/policy.js +77 -19
  59. package/dist/public-suffix.d.ts +6 -0
  60. package/dist/public-suffix.js +79 -0
  61. package/dist/server-ops.d.ts +48 -7
  62. package/dist/server-ops.js +287 -29
  63. package/dist/service/installed.d.ts +5 -0
  64. package/dist/service/installed.js +14 -0
  65. package/dist/service/launchd.d.ts +14 -1
  66. package/dist/service/launchd.js +25 -1
  67. package/dist/service/manager.d.ts +41 -0
  68. package/dist/service/manager.js +91 -0
  69. package/dist/service/systemd.d.ts +2 -0
  70. package/dist/service/systemd.js +8 -0
  71. package/dist/state.d.ts +50 -6
  72. package/dist/state.js +195 -16
  73. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -1,28 +1,62 @@
1
1
  import { homedir } from "node:os";
2
2
  import { parseCommandLine, USAGE, UsageError } from "./args.js";
3
- import { drain } from "./commands/drain.js";
3
+ import { drain, drainAndWait } from "./commands/drain.js";
4
4
  import { login } from "./commands/login.js";
5
5
  import { logout } from "./commands/logout.js";
6
+ import { modeCommand } from "./commands/mode.js";
6
7
  import { policyCommand } from "./commands/policy.js";
7
8
  import { serviceCommand } from "./commands/service.js";
8
9
  import { start } from "./commands/start.js";
9
10
  import { status } from "./commands/status.js";
10
11
  import { stop } from "./commands/stop.js";
11
12
  import { stateDir } from "./state.js";
12
- /** The executor for the credential's mode; the program's state directory is unreadable to commands. */
13
- function defaultCreateExecutor(stateDir, home) {
14
- return async (cred, policy) => {
13
+ /** Asks one question on the process's terminal. */
14
+ async function askOnTerminal(question) {
15
+ const { createInterface } = await import("node:readline/promises");
16
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
17
+ try {
18
+ return await rl.question(question);
19
+ }
20
+ finally {
21
+ rl.close();
22
+ }
23
+ }
24
+ /**
25
+ * Logged when the local policy switches between auto and sandbox. It names the local choice, not
26
+ * the effective mode: the organization's ceiling still cuts it (a device whose org forbids auto
27
+ * runs in the sandbox even with this policy).
28
+ */
29
+ export const AUTO_MODE_ON = "This machine's local policy is auto mode; the deployment's ceiling applies.";
30
+ export const AUTO_MODE_OFF = "This machine's local policy is sandbox mode; commands still running in auto mode were stopped.";
31
+ /**
32
+ * The executor for the credential's mode; the program's state directory is unreadable to
33
+ * sandboxed commands. OS mode serves a {@link SwitchingExecutor}: the host (auto mode) or the OS
34
+ * sandbox (sandbox mode), chosen per command from the policy and the kernel's ceiling (spec §4.1).
35
+ */
36
+ function defaultCreateExecutor(stateDir, home, err) {
37
+ return async (cred, store) => {
38
+ const policy = () => store.current();
15
39
  if (cred.mode === "docker") {
16
40
  const { createDockerExecutor } = await import("./exec/docker.js");
17
41
  return createDockerExecutor({
18
42
  dir: cred.dir,
19
- environmentId: cred.environmentId,
43
+ deviceId: cred.deviceId,
20
44
  policy,
21
45
  });
22
46
  }
23
47
  // Loaded on demand: the sandbox runtime is only needed by start.
24
- const { createOsExecutor } = await import("./exec/os.js");
25
- return createOsExecutor({ dir: cred.dir, policy, home, denyRead: [stateDir] });
48
+ const [{ createOsExecutor }, { HostExecutor }, { SwitchingExecutor }] = await Promise.all([
49
+ import("./exec/os.js"),
50
+ import("./exec/host.js"),
51
+ import("./exec/switch.js"),
52
+ ]);
53
+ const sandboxed = await createOsExecutor({
54
+ dir: cred.dir,
55
+ policy,
56
+ home,
57
+ denyRead: [stateDir],
58
+ });
59
+ return new SwitchingExecutor(sandboxed, new HostExecutor({ dir: cred.dir }), policy, (mode) => err(mode === "auto" ? AUTO_MODE_ON : AUTO_MODE_OFF));
26
60
  };
27
61
  }
28
62
  /** Runs one command line and returns the exit code. */
@@ -60,25 +94,58 @@ export async function runCli(argv, io = {}) {
60
94
  ...(io.fetch && { fetch: io.fetch }),
61
95
  ...(io.sleep && { sleep: io.sleep }),
62
96
  ...(io.openBrowser && { openBrowser: io.openBrowser }),
97
+ ...(io.sandboxAvailable && { sandboxAvailable: io.sandboxAvailable }),
63
98
  });
64
99
  case "logout":
65
- return logout(dir, { out, err, ...(io.kill && { kill: io.kill }) });
100
+ return logout(dir, {
101
+ out,
102
+ err,
103
+ ...(io.kill && { kill: io.kill }),
104
+ ...(io.ps && { ps: io.ps }),
105
+ });
66
106
  case "status":
67
107
  return status(dir, cmd.json, out, err);
68
108
  case "start":
69
109
  return start({
110
+ service: { home, platform },
70
111
  stateDir: dir,
71
112
  out,
72
113
  err,
73
- createExecutor: io.createExecutor ?? defaultCreateExecutor(dir, home),
114
+ createExecutor: io.createExecutor ?? defaultCreateExecutor(dir, home, err),
115
+ ...(io.env && { env: io.env }),
74
116
  ...(io.kill && { kill: io.kill }),
117
+ ...(io.ps && { ps: io.ps }),
75
118
  });
76
119
  case "stop":
77
- return stop(dir, out, err, io.kill);
120
+ return stop(dir, out, err, {
121
+ service: { home, platform },
122
+ ...(io.kill && { kill: io.kill }),
123
+ ...(io.ps && { ps: io.ps }),
124
+ ...(io.runSystem && { run: io.runSystem }),
125
+ });
78
126
  case "drain":
79
- return drain(dir, out, err, io.kill);
127
+ if (cmd.wait !== true) {
128
+ return drain(dir, out, err, {
129
+ ...(io.kill && { kill: io.kill }),
130
+ ...(io.ps && { ps: io.ps }),
131
+ });
132
+ }
133
+ return drainAndWait(dir, out, err, {
134
+ ...(io.kill && { kill: io.kill }),
135
+ ...(io.ps && { ps: io.ps }),
136
+ ...(io.sleep && { sleep: io.sleep }),
137
+ ...(cmd.timeoutSeconds !== undefined && { timeoutMs: cmd.timeoutSeconds * 1000 }),
138
+ });
80
139
  case "policy":
81
140
  return policyCommand(cmd, { stateDir: dir, out, err });
141
+ case "mode":
142
+ return modeCommand(cmd, {
143
+ stateDir: dir,
144
+ out,
145
+ err,
146
+ ...(io.sandboxAvailable && { sandboxAvailable: io.sandboxAvailable }),
147
+ ...((io.stdinIsTTY ?? process.stdin.isTTY === true) && { ask: io.ask ?? askOnTerminal }),
148
+ });
82
149
  case "service":
83
150
  return serviceCommand(cmd.action, {
84
151
  stateDir: dir,
@@ -88,6 +155,9 @@ export async function runCli(argv, io = {}) {
88
155
  out,
89
156
  err,
90
157
  ...(io.runSystem && { run: io.runSystem }),
158
+ ...(io.sleep && { sleep: io.sleep }),
159
+ ...(io.kill && { kill: io.kill }),
160
+ ...(io.ps && { ps: io.ps }),
91
161
  });
92
162
  }
93
163
  }
package/dist/client.d.ts CHANGED
@@ -1,14 +1,20 @@
1
1
  import type { CommandLog } from "./command-log.js";
2
2
  import type { Executor } from "./exec/types.js";
3
+ import type { PolicyStore } from "./policy-store.js";
3
4
  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 OUTDATED_MESSAGE = "This capybara-device is too old for the deployment. Upgrade it: npm install -g @capybara-hq/device@next";
5
6
  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.";
7
+ export declare const REPLACED_MESSAGE = "This machine connected elsewhere: a newer connection to this device replaced this one.";
8
+ export declare const DELETED_MESSAGE = "The device was deleted on the deployment. The files on this machine stay where they are.";
8
9
  /** The answer sent instead of a result whose frame would exceed the connection's frame limit. */
9
10
  export declare const TOO_LARGE_MESSAGE = "result larger than the connection's frame limit";
10
11
  export interface ConnectOptions {
11
12
  log?: CommandLog;
13
+ /**
14
+ * The local policy the executor reads: its summary goes in each hello, and the `policy` op
15
+ * edits it. Without it the device does not offer the `policy` op.
16
+ */
17
+ policy?: PolicyStore;
12
18
  err?: (line: string) => void;
13
19
  sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
14
20
  random?: () => number;
@@ -20,11 +26,18 @@ export interface ConnectOptions {
20
26
  livenessMs?: number;
21
27
  /** Terminate a socket still closing this long after we asked it to close (default 2 s). */
22
28
  closeTimeoutMs?: number;
29
+ /**
30
+ * How often a connected program checks its policy summary for a change made on the machine
31
+ * (default 2 s); a change is pushed to the deployment as a `policy` frame.
32
+ */
33
+ policyCheckMs?: number;
23
34
  }
24
35
  /**
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.
36
+ * A running connection. `done` resolves with the exit code once the program should end: 0 for a
37
+ * deliberate stop (revoked, replaced by a newer connection of this device, deleted, stopped,
38
+ * drained), which a service manager that restarts on failure leaves stopped; 1 when the deployment
39
+ * needs a newer program (426), which an upgrade in place recovers once the service starts it again.
40
+ * Connection failures never end it: they reconnect with backoff.
28
41
  */
29
42
  export interface Connection {
30
43
  readonly done: Promise<number>;
package/dist/client.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { DEVICE_PROTOCOL_VERSION, parseDeviceFrame, } from "@capybara-hq/plugin-sdk";
2
2
  import WebSocket from "ws";
3
- import { logEntryFor, runOp } from "./server-ops.js";
3
+ import { logEntryFor, policySummary, serveOp, summaryFacts, } from "./server-ops.js";
4
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";
5
+ export const OUTDATED_MESSAGE = "This capybara-device is too old for the deployment. Upgrade it: npm install -g @capybara-hq/device@next";
6
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.";
7
+ export const REPLACED_MESSAGE = "This machine connected elsewhere: a newer connection to this device replaced this one.";
8
+ export const DELETED_MESSAGE = "The device was deleted on the deployment. The files on this machine stay where they are.";
9
9
  /** The answer sent instead of a result whose frame would exceed the connection's frame limit. */
10
10
  export const TOO_LARGE_MESSAGE = "result larger than the connection's frame limit";
11
11
  /** A failing connection is reported at most this often. */
@@ -38,6 +38,7 @@ export function connect(cred, executor, opts = {}) {
38
38
  const stableMs = opts.stableMs ?? 10_000;
39
39
  const livenessMs = opts.livenessMs ?? 60_000;
40
40
  const closeTimeoutMs = opts.closeTimeoutMs ?? 2000;
41
+ const policyCheckMs = opts.policyCheckMs ?? 2000;
41
42
  const lifetime = new AbortController();
42
43
  let ws;
43
44
  let draining = false;
@@ -45,6 +46,12 @@ export function connect(cred, executor, opts = {}) {
45
46
  let exitAfterStop;
46
47
  let session;
47
48
  let drainTimer;
49
+ /** What the requests of this run have seen (the latest exec's mode), over reconnects. */
50
+ const seen = {};
51
+ const ctx = {
52
+ seen,
53
+ ...(opts.policy !== undefined && { policy: opts.policy }),
54
+ };
48
55
  const running = new Map();
49
56
  /** Requests the kernel gave up on: never started, or their result is dropped. */
50
57
  const cancelled = new Map();
@@ -63,6 +70,30 @@ export function connect(cred, executor, opts = {}) {
63
70
  pending.delete(k);
64
71
  };
65
72
  const isOpen = () => ws !== undefined && ws.readyState === WebSocket.OPEN;
73
+ /** The policy summary now: the store's policy (re-read when its file changed) and the facts. */
74
+ const summaryNow = () => opts.policy === undefined
75
+ ? undefined
76
+ : policySummary(opts.policy.current(), summaryFacts(executor, ctx));
77
+ /** The summary the deployment last got on this connection (hello, `policy` op, `policy` frame). */
78
+ let sentPolicy;
79
+ /**
80
+ * Pushes the policy summary when it differs from the one the deployment last got: the owner
81
+ * changed the mode or the policy on the machine (`capybara-device mode` / `policy ...`). Without
82
+ * it the deployment would learn the change only at the next connect. An exec's ceiling changes
83
+ * nothing here: the summary reports the owner's mode, which the kernel cuts itself.
84
+ */
85
+ const pushPolicy = () => {
86
+ if (!isOpen())
87
+ return;
88
+ const summary = summaryNow();
89
+ if (summary === undefined)
90
+ return;
91
+ const json = JSON.stringify(summary);
92
+ if (json === sentPolicy)
93
+ return;
94
+ sentPolicy = json;
95
+ ws?.send(JSON.stringify({ type: "policy", policy: summary }));
96
+ };
66
97
  /** `res`, or an error answer when its frame would exceed the deployment's frame limit. */
67
98
  const fit = (res) => Buffer.byteLength(JSON.stringify(res)) <= cred.maxFrameBytes
68
99
  ? res
@@ -138,9 +169,9 @@ export function connect(cred, executor, opts = {}) {
138
169
  }
139
170
  const ctl = new AbortController();
140
171
  running.set(req.id, ctl);
141
- void runOp(executor, req, ctl.signal).then((res) => {
172
+ void serveOp(executor, req, ctl.signal, ctx).then(({ res, detail, run }) => {
142
173
  running.delete(req.id);
143
- opts.log?.append(logEntryFor(req, res, new Date(now())));
174
+ opts.log?.append(logEntryFor(req, res, new Date(now()), detail, run));
144
175
  if (cancelled.has(req.id)) {
145
176
  // The kernel is no longer waiting for this one.
146
177
  }
@@ -161,6 +192,10 @@ export function connect(cred, executor, opts = {}) {
161
192
  return;
162
193
  }
163
194
  else {
195
+ // a policy op's answer carries the summary the deployment stores
196
+ if (req.op === "policy" && res.ok) {
197
+ sentPolicy = JSON.stringify(res.result.policy);
198
+ }
164
199
  deliver(res);
165
200
  }
166
201
  maybeFinishDrain();
@@ -200,25 +235,55 @@ export function connect(cred, executor, opts = {}) {
200
235
  else if (frame.type === "cancel")
201
236
  handleCancel(frame.id);
202
237
  };
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
- });
238
+ /**
239
+ * The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
240
+ * mode has no per-host view); the device applies `limits.mode` / `limits.network` (`mode`); the
241
+ * policy summary is the store's policy now (the owner's mode, not cut by any ceiling);
242
+ * then the outcomes of the latest policy ops by op id.
243
+ */
244
+ const hello = () => {
245
+ const summary = summaryNow();
246
+ sentPolicy = summary === undefined ? undefined : JSON.stringify(summary);
247
+ const features = [];
248
+ if (executor.mode === "os")
249
+ features.push("networkReport");
250
+ // the policy op, logged by its op id (policy-ops.json next to the policy)
251
+ if (opts.policy !== undefined)
252
+ features.push("policyOp", "policyOpId");
253
+ features.push("mode");
254
+ return {
255
+ type: "hello",
256
+ protocol: DEVICE_PROTOCOL_VERSION,
257
+ programVersion: opts.programVersion ?? PROGRAM_VERSION,
258
+ os: process.platform === "darwin" ? "darwin" : "linux",
259
+ arch: process.arch,
260
+ mode: executor.mode,
261
+ roots: executor.roots,
262
+ sessionIsolation: false,
263
+ features,
264
+ ...(summary !== undefined && { policy: summary }),
265
+ // what became of the latest policy ops, so an answer lost with a connection is not lost
266
+ ...(opts.policy !== undefined && { recentOps: opts.policy.ops.recent() }),
267
+ };
268
+ };
213
269
  let attempt = 0;
214
270
  /** When a failing connection was last reported; reset once a connection stays up. */
215
271
  let lastReport;
216
- /** Reports why connecting keeps failing, at most once a minute. */
272
+ /** The failure last reported: a different failure is reported at once, not after the interval. */
273
+ let lastReportText;
274
+ /**
275
+ * Reports why connecting keeps failing: a failure different from the last one is reported at
276
+ * once, the same one at most once a minute. A long outage therefore does not flood the log.
277
+ */
217
278
  const reportFailure = (why) => {
218
279
  const t = now();
219
- if (lastReport !== undefined && t - lastReport < FAILURE_REPORT_INTERVAL_MS)
280
+ if (why === lastReportText &&
281
+ lastReport !== undefined &&
282
+ t - lastReport < FAILURE_REPORT_INTERVAL_MS) {
220
283
  return;
284
+ }
221
285
  lastReport = t;
286
+ lastReportText = why;
222
287
  err(`${why} Retrying.`);
223
288
  };
224
289
  const runSession = () => new Promise((resolve) => {
@@ -232,6 +297,7 @@ export function connect(cred, executor, opts = {}) {
232
297
  ws = sock;
233
298
  let liveness;
234
299
  let stable;
300
+ let policyCheck;
235
301
  let opened = false;
236
302
  /** The deployment answered the upgrade with an HTTP status (already handled). */
237
303
  let answered = false;
@@ -244,10 +310,15 @@ export function connect(cred, executor, opts = {}) {
244
310
  opened = true;
245
311
  heard();
246
312
  stable = setTimeout(() => {
313
+ // A connection that stayed up enough is a success: the next failure starts at the
314
+ // base delay, and is reported again even if it is the same message as before.
247
315
  attempt = 0;
248
316
  lastReport = undefined;
317
+ lastReportText = undefined;
249
318
  }, stableMs);
250
319
  sock.send(JSON.stringify(hello()));
320
+ if (opts.policy !== undefined)
321
+ policyCheck = setInterval(pushPolicy, policyCheckMs);
251
322
  prune();
252
323
  for (const [id, p] of pending) {
253
324
  pending.delete(id);
@@ -268,8 +339,10 @@ export function connect(cred, executor, opts = {}) {
268
339
  sock.terminate();
269
340
  if (status === 401)
270
341
  return endSession({ exit: 0, message: DISCONNECTED_MESSAGE });
342
+ // Not a deliberate stop: upgrading the package in place recovers it, so the exit is
343
+ // non-zero and the service manager starts the (new) program again.
271
344
  if (status === 426)
272
- return endSession({ exit: 0, message: OUTDATED_MESSAGE });
345
+ return endSession({ exit: 1, message: OUTDATED_MESSAGE });
273
346
  reportFailure(status === 404
274
347
  ? `Connecting to ${cred.connectUrl} failed: HTTP 404. The deployment must route ` +
275
348
  "/device/connect to its gateway (see the deployment docs)."
@@ -286,6 +359,7 @@ export function connect(cred, executor, opts = {}) {
286
359
  sock.on("close", (code, reason) => {
287
360
  clearTimeout(liveness);
288
361
  clearTimeout(stable);
362
+ clearInterval(policyCheck);
289
363
  if (ws === sock)
290
364
  ws = undefined;
291
365
  if (exitAfterStop)
@@ -1,3 +1,4 @@
1
+ import type { SandboxMode } from "./state.js";
1
2
  export declare const COMMAND_LOG_MAX_BYTES: number;
2
3
  export interface CommandLogEntry {
3
4
  time: string;
@@ -7,6 +8,13 @@ export interface CommandLogEntry {
7
8
  accountId: string;
8
9
  } | null;
9
10
  exitCode: number | null;
11
+ /** An exec's mode: auto (no OS sandbox) or sandbox. */
12
+ mode?: SandboxMode;
13
+ /**
14
+ * An audit line: a policy change from the deployment (`policy add a.com by <name> (<id>) via
15
+ * web, approval <id>`) or the grants an exec was given (`grants run <id> by <id>: a.com`).
16
+ */
17
+ detail?: string;
10
18
  }
11
19
  /** One JSON line per operation in `<stateDir>/commands.log`; rotated to `commands.log.1` at 10 MiB. */
12
20
  export declare class CommandLog {
@@ -1,2 +1,15 @@
1
+ import { type ProcessChecks } from "../pid.js";
2
+ /** How often `drain --wait` checks whether the program has exited. */
3
+ export declare const DRAIN_POLL_MS = 500;
4
+ /** How long `drain --wait` waits by default (commands may run long). */
5
+ export declare const DRAIN_WAIT_DEFAULT_SECONDS = 600;
1
6
  /** `drain`: SIGUSR2 to the running program: no new commands, stop when the running ones finish. */
2
- export declare function drain(stateDir: string, out: (line: string) => void, err: (line: string) => void, kill?: typeof process.kill): number;
7
+ export declare function drain(stateDir: string, out: (line: string) => void, err: (line: string) => void, checks?: ProcessChecks): number;
8
+ /**
9
+ * `drain --wait`: {@link drain}, then waits until the program has exited (its running commands
10
+ * finished), at most `timeoutMs`. Exit code 1 when it still runs then.
11
+ */
12
+ export declare function drainAndWait(stateDir: string, out: (line: string) => void, err: (line: string) => void, o?: ProcessChecks & {
13
+ sleep?: (ms: number) => Promise<void>;
14
+ timeoutMs?: number;
15
+ }): Promise<number>;
@@ -1,5 +1,34 @@
1
+ import { isAlive, readRunningPid } from "../pid.js";
1
2
  import { signalRunning } from "./signal.js";
3
+ /** How often `drain --wait` checks whether the program has exited. */
4
+ export const DRAIN_POLL_MS = 500;
5
+ /** How long `drain --wait` waits by default (commands may run long). */
6
+ export const DRAIN_WAIT_DEFAULT_SECONDS = 600;
2
7
  /** `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);
8
+ export function drain(stateDir, out, err, checks = {}) {
9
+ return signalRunning(stateDir, "SIGUSR2", "Draining capybara-device.", out, err, checks);
10
+ }
11
+ /**
12
+ * `drain --wait`: {@link drain}, then waits until the program has exited (its running commands
13
+ * finished), at most `timeoutMs`. Exit code 1 when it still runs then.
14
+ */
15
+ export async function drainAndWait(stateDir, out, err, o = {}) {
16
+ const kill = o.kill ?? process.kill;
17
+ const sleep = o.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
18
+ const timeoutMs = o.timeoutMs ?? DRAIN_WAIT_DEFAULT_SECONDS * 1000;
19
+ const checks = { kill, ...(o.ps && { ps: o.ps }) };
20
+ const pid = readRunningPid(stateDir, checks);
21
+ const code = drain(stateDir, out, err, checks);
22
+ if (code !== 0 || pid === undefined)
23
+ return code;
24
+ for (let waited = 0; isAlive(pid, kill); waited += DRAIN_POLL_MS) {
25
+ if (waited >= timeoutMs) {
26
+ err(`capybara-device (pid ${pid}) is still draining after ${Math.round(timeoutMs / 1000)} s: ` +
27
+ "commands are still running. Wait longer with drain --wait, or stop it now with stop.");
28
+ return 1;
29
+ }
30
+ await sleep(Math.min(DRAIN_POLL_MS, timeoutMs - waited));
31
+ }
32
+ out("capybara-device has stopped.");
33
+ return 0;
5
34
  }
@@ -1,5 +1,6 @@
1
1
  import { type FetchFn } from "../api.js";
2
2
  import type { Command } from "../args.js";
3
+ import { type SandboxCheck } from "./mode.js";
3
4
  export interface LoginDeps {
4
5
  stateDir: string;
5
6
  home: string;
@@ -11,6 +12,8 @@ export interface LoginDeps {
11
12
  platform?: NodeJS.Platform;
12
13
  arch?: string;
13
14
  hostname?: string;
15
+ /** Whether the OS sandbox can run here (default: the runtime's check); injectable for tests. */
16
+ sandboxAvailable?: SandboxCheck;
14
17
  }
15
18
  /** Normalises the deployment URL: http(s) origin plus optional path prefix, no trailing slash. */
16
19
  export declare function normalizeUrl(raw: string): string;
@@ -1,9 +1,12 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
2
3
  import { hostname } from "node:os";
3
4
  import { isAbsolute, resolve } from "node:path";
4
5
  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";
6
+ import { prepareDeviceDir } from "../exec/shared.js";
7
+ import { hasLoginService } from "../service/installed.js";
8
+ import { DEFAULT_MAX_FRAME_BYTES, DEFAULT_POLICY, defaultWorkDir, policyPath, readCredential, readPolicy, withPolicyLock, writeCredential, writePolicy, } from "../state.js";
9
+ import { AUTO_MODE_LOGIN_LINE, AUTO_MODE_RISK_TEXT, AUTO_POLICY_REFUSED_LOGIN_LINE, checkSandbox, DOCKER_AUTO_MODE_LOGIN_LINE, DOCKER_SANDBOX_MODE_LOGIN_LINE, SANDBOX_MODE_LOGIN_LINE, SANDBOX_POLICY_LOGIN_LINE, sandboxUnavailableLoginLine, } from "./mode.js";
7
10
  const SLOW_DOWN_STEP_SECONDS = 5;
8
11
  function defaultOpen(platform) {
9
12
  return (url) => {
@@ -18,6 +21,24 @@ function defaultOpen(platform) {
18
21
  }
19
22
  };
20
23
  }
24
+ /**
25
+ * A fresh device in an organization that forbids auto mode starts in sandbox mode (auto mode
26
+ * spec §4.1): the default policy is auto, which the kernel refuses at every exec, so the login
27
+ * line would otherwise describe a mode the machine does not run. Written under the policy lock,
28
+ * and only while no policy file exists: an existing policy is the owner's choice and is never
29
+ * changed here. Returns whether this call created the file.
30
+ */
31
+ function persistSandboxPolicy(stateDir) {
32
+ const file = policyPath(stateDir);
33
+ if (existsSync(file))
34
+ return false;
35
+ return withPolicyLock(stateDir, () => {
36
+ if (existsSync(file))
37
+ return false;
38
+ writePolicy(stateDir, { ...DEFAULT_POLICY, mode: "sandbox" });
39
+ return true;
40
+ });
41
+ }
21
42
  /** Normalises the deployment URL: http(s) origin plus optional path prefix, no trailing slash. */
22
43
  export function normalizeUrl(raw) {
23
44
  let u;
@@ -80,39 +101,103 @@ export async function login(cmd, deps) {
80
101
  try {
81
102
  const granted = await token(fetchFn, baseUrl, auth.deviceCode);
82
103
  const dir = cmd.dir === undefined
83
- ? defaultWorkDir(granted.environmentId, deps.home)
104
+ ? defaultWorkDir(granted.deviceId, deps.home)
84
105
  : isAbsolute(cmd.dir)
85
106
  ? cmd.dir
86
107
  : resolve(cmd.dir);
87
- // Recreates a lost directory, marker or root: the environment starts afresh.
88
- prepareEnvironmentDir(dir);
108
+ // Recreates a lost directory, marker or root: the device starts afresh.
109
+ prepareDeviceDir(dir);
110
+ // The printed line follows this machine's persisted policy in both branches, not the
111
+ // organization's allowance: sandbox mode is also the state an earlier login in an
112
+ // auto-forbidden organization left behind. The default mode is auto; an organization that
113
+ // forbids it gets sandbox mode written as this device's policy before the credential makes
114
+ // the login final. An existing policy is the owner's choice: the kernel refuses auto mode
115
+ // at every command if the organization forbids it and the owner keeps auto.
116
+ let mode = "auto";
117
+ /** Why no sandbox policy was written: the OS sandbox cannot run here (OS mode only). */
118
+ let noSandbox;
119
+ if (granted.autoMode === "off") {
120
+ try {
121
+ // A sandbox policy on a machine without the OS sandbox could not run a command either:
122
+ // it is not written, and the line says what to install (Docker needs no OS sandbox).
123
+ if (cmd.mode !== "docker" && !existsSync(policyPath(deps.stateDir))) {
124
+ const available = await checkSandbox(deps.sandboxAvailable);
125
+ if (!available.ok)
126
+ noSandbox = available.reason;
127
+ }
128
+ if (noSandbox === undefined) {
129
+ mode = persistSandboxPolicy(deps.stateDir)
130
+ ? "sandbox"
131
+ : readPolicy(deps.stateDir).mode;
132
+ }
133
+ }
134
+ catch (e) {
135
+ err(`Cannot set the local policy in ${deps.stateDir}: ${e.message}`);
136
+ }
137
+ }
138
+ else {
139
+ try {
140
+ mode = readPolicy(deps.stateDir).mode;
141
+ }
142
+ catch (e) {
143
+ err(`Cannot read the local policy in ${deps.stateDir}: ${e.message}`);
144
+ }
145
+ }
89
146
  writeCredential(deps.stateDir, {
90
147
  url: baseUrl,
91
148
  connectUrl: granted.connectUrl,
92
149
  credential: granted.credential,
93
150
  orgId: granted.orgId,
94
- environmentId: granted.environmentId,
151
+ deviceId: granted.deviceId,
95
152
  dir,
96
153
  mode: cmd.mode,
97
154
  reconnectGraceSeconds: granted.reconnectGraceSeconds,
98
155
  maxFrameBytes: granted.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES,
99
156
  });
100
- out(`Logged in. Environment ${granted.environmentId}, working directory ${dir}`);
157
+ out(`Logged in. Device ${granted.deviceId}, working directory ${dir}`);
158
+ // The risk text is shown once at login (spec §8), and only when commands run on this
159
+ // machine as the owner (auto mode outside Docker).
160
+ if (cmd.mode === "docker") {
161
+ if (granted.autoMode === "off" && mode !== "sandbox")
162
+ out(AUTO_POLICY_REFUSED_LOGIN_LINE);
163
+ else
164
+ out(mode === "sandbox" ? DOCKER_SANDBOX_MODE_LOGIN_LINE : DOCKER_AUTO_MODE_LOGIN_LINE);
165
+ }
166
+ else if (noSandbox !== undefined) {
167
+ out(sandboxUnavailableLoginLine(noSandbox));
168
+ }
169
+ else if (granted.autoMode === "off") {
170
+ out(mode === "sandbox" ? SANDBOX_MODE_LOGIN_LINE : AUTO_POLICY_REFUSED_LOGIN_LINE);
171
+ }
172
+ else if (mode === "sandbox") {
173
+ out(SANDBOX_POLICY_LOGIN_LINE);
174
+ }
175
+ else {
176
+ out(AUTO_MODE_LOGIN_LINE);
177
+ out(AUTO_MODE_RISK_TEXT);
178
+ }
179
+ // An installed service stays stopped after a deliberate exit (not logged in, logged out):
180
+ // it needs starting again, not a second program.
181
+ out(hasLoginService(deps.home, platform)
182
+ ? "The login service is installed: bring it online with `capybara-device service restart`."
183
+ : "Run `capybara-device start` to bring it online (or `capybara-device service install` to connect at login).");
101
184
  return 0;
102
185
  }
103
186
  catch (e) {
104
187
  if (!(e instanceof ApiError))
105
188
  throw e;
106
- if (e.code === "device.slow_down")
189
+ if (e.code === "device_sign_in.slow_down")
107
190
  interval += SLOW_DOWN_STEP_SECONDS;
108
- else if (e.code === "device.authorization_pending" || e.status === 0 || e.status >= 500) {
191
+ else if (e.code === "device_sign_in.authorization_pending" ||
192
+ e.status === 0 ||
193
+ e.status >= 500) {
109
194
  // Keep polling at the normal interval: pending, a network blip or a server error.
110
195
  }
111
- else if (e.code === "device.expired") {
196
+ else if (e.code === "device_sign_in.expired") {
112
197
  err("The code expired before it was approved. Run `capybara-device login` again.");
113
198
  return 1;
114
199
  }
115
- else if (e.code === "device.denied") {
200
+ else if (e.code === "device_sign_in.denied") {
116
201
  err("The login was denied in the browser.");
117
202
  return 1;
118
203
  }
@@ -1,7 +1,9 @@
1
+ import { type ProcessLookup } from "../pid.js";
1
2
  export interface LogoutDeps {
2
3
  out: (line: string) => void;
3
4
  err?: (line: string) => void;
4
5
  kill?: typeof process.kill;
6
+ ps?: ProcessLookup;
5
7
  sleep?: (ms: number) => Promise<void>;
6
8
  /** How long to wait for a running program to exit (default 5 s). */
7
9
  waitMs?: number;
@@ -10,7 +10,7 @@ export async function logout(stateDir, deps) {
10
10
  const err = deps.err ?? out;
11
11
  const kill = deps.kill ?? process.kill;
12
12
  const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
13
- const pid = readRunningPid(stateDir, kill);
13
+ const pid = readRunningPid(stateDir, { kill, ...(deps.ps && { ps: deps.ps }) });
14
14
  if (pid !== undefined && pid !== process.pid) {
15
15
  out(`Stopping the running capybara-device (pid ${pid}).`);
16
16
  try {