@capybara-hq/device 0.1.0-rc.1 → 0.1.0-rc.10
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 +187 -44
- package/dist/api.d.ts +6 -1
- package/dist/args.d.ts +14 -3
- package/dist/args.js +74 -10
- package/dist/cli.d.ts +14 -2
- package/dist/cli.js +59 -10
- package/dist/client.d.ts +14 -3
- package/dist/client.js +92 -18
- package/dist/command-log.d.ts +8 -0
- package/dist/commands/drain.d.ts +13 -0
- package/dist/commands/drain.js +28 -0
- package/dist/commands/login.js +68 -11
- package/dist/commands/mode.d.ts +52 -0
- package/dist/commands/mode.js +108 -0
- package/dist/commands/policy.d.ts +13 -4
- package/dist/commands/policy.js +162 -33
- package/dist/commands/service.d.ts +18 -3
- package/dist/commands/service.js +175 -9
- package/dist/commands/start.d.ts +14 -3
- package/dist/commands/start.js +37 -5
- package/dist/commands/status.js +12 -4
- package/dist/commands/stop.d.ts +9 -2
- package/dist/commands/stop.js +13 -2
- package/dist/exec/docker.d.ts +41 -13
- package/dist/exec/docker.js +123 -57
- package/dist/exec/fs-helper.d.ts +13 -8
- package/dist/exec/fs-helper.js +31 -13
- package/dist/exec/groups.d.ts +42 -0
- package/dist/exec/groups.js +100 -0
- package/dist/exec/host.d.ts +53 -0
- package/dist/exec/host.js +183 -0
- package/dist/exec/os.d.ts +85 -15
- package/dist/exec/os.js +208 -36
- package/dist/exec/reap.d.ts +41 -0
- package/dist/exec/reap.js +89 -0
- package/dist/exec/sandbox-messages.d.ts +14 -0
- package/dist/exec/sandbox-messages.js +21 -0
- package/dist/exec/shared.d.ts +42 -13
- package/dist/exec/shared.js +94 -16
- package/dist/exec/switch.d.ts +91 -0
- package/dist/exec/switch.js +164 -0
- package/dist/exec/types.d.ts +28 -4
- package/dist/index.d.ts +1 -1
- package/dist/network.d.ts +45 -0
- package/dist/network.js +154 -0
- package/dist/pid.d.ts +13 -1
- package/dist/pid.js +54 -7
- package/dist/policy-ops.d.ts +47 -0
- package/dist/policy-ops.js +90 -0
- package/dist/policy-store.d.ts +43 -0
- package/dist/policy-store.js +94 -0
- package/dist/policy.d.ts +36 -16
- package/dist/policy.js +77 -19
- package/dist/public-suffix.d.ts +6 -0
- package/dist/public-suffix.js +79 -0
- package/dist/server-ops.d.ts +46 -7
- package/dist/server-ops.js +285 -29
- package/dist/service/installed.d.ts +5 -0
- package/dist/service/installed.js +14 -0
- package/dist/service/launchd.d.ts +11 -1
- package/dist/service/launchd.js +14 -5
- package/dist/state.d.ts +50 -6
- package/dist/state.js +195 -16
- package/package.json +3 -3
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
|
|
7
|
-
export declare const DELETED_MESSAGE = "The
|
|
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,6 +26,11 @@ 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
36
|
* A running connection. `done` resolves with the exit code once the program should end: 0 for the
|
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,
|
|
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
|
|
8
|
-
export const DELETED_MESSAGE = "The
|
|
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 ...`), or an
|
|
82
|
+
* exec brought a new mode ceiling. Without it the deployment would learn the change only at the
|
|
83
|
+
* next connect.
|
|
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
|
|
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,7 +192,13 @@ 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);
|
|
200
|
+
// an exec may have changed the ceiling (the effective mode)
|
|
201
|
+
pushPolicy();
|
|
165
202
|
}
|
|
166
203
|
maybeFinishDrain();
|
|
167
204
|
});
|
|
@@ -200,25 +237,55 @@ export function connect(cred, executor, opts = {}) {
|
|
|
200
237
|
else if (frame.type === "cancel")
|
|
201
238
|
handleCancel(frame.id);
|
|
202
239
|
};
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
240
|
+
/**
|
|
241
|
+
* The hello, built at each (re)connect: the OS mode reports blocked hosts per command (Docker
|
|
242
|
+
* mode has no per-host view); the device applies `limits.mode` / `limits.network` (`mode`); the
|
|
243
|
+
* policy summary is the store's policy now, with the effective mode and the latest ceiling seen;
|
|
244
|
+
* then the outcomes of the latest policy ops by op id.
|
|
245
|
+
*/
|
|
246
|
+
const hello = () => {
|
|
247
|
+
const summary = summaryNow();
|
|
248
|
+
sentPolicy = summary === undefined ? undefined : JSON.stringify(summary);
|
|
249
|
+
const features = [];
|
|
250
|
+
if (executor.mode === "os")
|
|
251
|
+
features.push("networkReport");
|
|
252
|
+
// the policy op, logged by its op id (policy-ops.json next to the policy)
|
|
253
|
+
if (opts.policy !== undefined)
|
|
254
|
+
features.push("policyOp", "policyOpId");
|
|
255
|
+
features.push("mode");
|
|
256
|
+
return {
|
|
257
|
+
type: "hello",
|
|
258
|
+
protocol: DEVICE_PROTOCOL_VERSION,
|
|
259
|
+
programVersion: opts.programVersion ?? PROGRAM_VERSION,
|
|
260
|
+
os: process.platform === "darwin" ? "darwin" : "linux",
|
|
261
|
+
arch: process.arch,
|
|
262
|
+
mode: executor.mode,
|
|
263
|
+
roots: executor.roots,
|
|
264
|
+
sessionIsolation: false,
|
|
265
|
+
features,
|
|
266
|
+
...(summary !== undefined && { policy: summary }),
|
|
267
|
+
// what became of the latest policy ops, so an answer lost with a connection is not lost
|
|
268
|
+
...(opts.policy !== undefined && { recentOps: opts.policy.ops.recent() }),
|
|
269
|
+
};
|
|
270
|
+
};
|
|
213
271
|
let attempt = 0;
|
|
214
272
|
/** When a failing connection was last reported; reset once a connection stays up. */
|
|
215
273
|
let lastReport;
|
|
216
|
-
/**
|
|
274
|
+
/** The failure last reported: a different failure is reported at once, not after the interval. */
|
|
275
|
+
let lastReportText;
|
|
276
|
+
/**
|
|
277
|
+
* Reports why connecting keeps failing: a failure different from the last one is reported at
|
|
278
|
+
* once, the same one at most once a minute. A long outage therefore does not flood the log.
|
|
279
|
+
*/
|
|
217
280
|
const reportFailure = (why) => {
|
|
218
281
|
const t = now();
|
|
219
|
-
if (
|
|
282
|
+
if (why === lastReportText &&
|
|
283
|
+
lastReport !== undefined &&
|
|
284
|
+
t - lastReport < FAILURE_REPORT_INTERVAL_MS) {
|
|
220
285
|
return;
|
|
286
|
+
}
|
|
221
287
|
lastReport = t;
|
|
288
|
+
lastReportText = why;
|
|
222
289
|
err(`${why} Retrying.`);
|
|
223
290
|
};
|
|
224
291
|
const runSession = () => new Promise((resolve) => {
|
|
@@ -232,6 +299,7 @@ export function connect(cred, executor, opts = {}) {
|
|
|
232
299
|
ws = sock;
|
|
233
300
|
let liveness;
|
|
234
301
|
let stable;
|
|
302
|
+
let policyCheck;
|
|
235
303
|
let opened = false;
|
|
236
304
|
/** The deployment answered the upgrade with an HTTP status (already handled). */
|
|
237
305
|
let answered = false;
|
|
@@ -244,10 +312,15 @@ export function connect(cred, executor, opts = {}) {
|
|
|
244
312
|
opened = true;
|
|
245
313
|
heard();
|
|
246
314
|
stable = setTimeout(() => {
|
|
315
|
+
// A connection that stayed up enough is a success: the next failure starts at the
|
|
316
|
+
// base delay, and is reported again even if it is the same message as before.
|
|
247
317
|
attempt = 0;
|
|
248
318
|
lastReport = undefined;
|
|
319
|
+
lastReportText = undefined;
|
|
249
320
|
}, stableMs);
|
|
250
321
|
sock.send(JSON.stringify(hello()));
|
|
322
|
+
if (opts.policy !== undefined)
|
|
323
|
+
policyCheck = setInterval(pushPolicy, policyCheckMs);
|
|
251
324
|
prune();
|
|
252
325
|
for (const [id, p] of pending) {
|
|
253
326
|
pending.delete(id);
|
|
@@ -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)
|
package/dist/command-log.d.ts
CHANGED
|
@@ -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 {
|
package/dist/commands/drain.d.ts
CHANGED
|
@@ -1,2 +1,15 @@
|
|
|
1
|
+
/** How often `drain --wait` checks whether the program has exited. */
|
|
2
|
+
export declare const DRAIN_POLL_MS = 500;
|
|
3
|
+
/** How long `drain --wait` waits by default (commands may run long). */
|
|
4
|
+
export declare const DRAIN_WAIT_DEFAULT_SECONDS = 600;
|
|
1
5
|
/** `drain`: SIGUSR2 to the running program: no new commands, stop when the running ones finish. */
|
|
2
6
|
export declare function drain(stateDir: string, out: (line: string) => void, err: (line: string) => void, kill?: typeof process.kill): number;
|
|
7
|
+
/**
|
|
8
|
+
* `drain --wait`: {@link drain}, then waits until the program has exited (its running commands
|
|
9
|
+
* finished), at most `timeoutMs`. Exit code 1 when it still runs then.
|
|
10
|
+
*/
|
|
11
|
+
export declare function drainAndWait(stateDir: string, out: (line: string) => void, err: (line: string) => void, o?: {
|
|
12
|
+
kill?: typeof process.kill;
|
|
13
|
+
sleep?: (ms: number) => Promise<void>;
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
}): Promise<number>;
|
package/dist/commands/drain.js
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
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
8
|
export function drain(stateDir, out, err, kill) {
|
|
4
9
|
return signalRunning(stateDir, "SIGUSR2", "Draining capybara-device.", out, err, kill);
|
|
5
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 pid = readRunningPid(stateDir, kill);
|
|
20
|
+
const code = drain(stateDir, out, err, kill);
|
|
21
|
+
if (code !== 0 || pid === undefined)
|
|
22
|
+
return code;
|
|
23
|
+
for (let waited = 0; isAlive(pid, kill); waited += DRAIN_POLL_MS) {
|
|
24
|
+
if (waited >= timeoutMs) {
|
|
25
|
+
err(`capybara-device (pid ${pid}) is still draining after ${Math.round(timeoutMs / 1000)} s: ` +
|
|
26
|
+
"commands are still running. Wait longer with drain --wait, or stop it now with stop.");
|
|
27
|
+
return 1;
|
|
28
|
+
}
|
|
29
|
+
await sleep(Math.min(DRAIN_POLL_MS, timeoutMs - waited));
|
|
30
|
+
}
|
|
31
|
+
out("capybara-device has stopped.");
|
|
32
|
+
return 0;
|
|
33
|
+
}
|
package/dist/commands/login.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
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 {
|
|
6
|
-
import { DEFAULT_MAX_FRAME_BYTES, defaultWorkDir, readCredential, writeCredential, } from "../state.js";
|
|
6
|
+
import { prepareDeviceDir } from "../exec/shared.js";
|
|
7
|
+
import { DEFAULT_MAX_FRAME_BYTES, DEFAULT_POLICY, defaultWorkDir, policyPath, readCredential, readPolicy, withPolicyLock, writeCredential, writePolicy, } from "../state.js";
|
|
8
|
+
import { AUTO_MODE_LOGIN_LINE, AUTO_MODE_RISK_TEXT, AUTO_POLICY_REFUSED_LOGIN_LINE, SANDBOX_MODE_LOGIN_LINE, SANDBOX_POLICY_LOGIN_LINE, } from "./mode.js";
|
|
7
9
|
const SLOW_DOWN_STEP_SECONDS = 5;
|
|
8
10
|
function defaultOpen(platform) {
|
|
9
11
|
return (url) => {
|
|
@@ -18,6 +20,24 @@ function defaultOpen(platform) {
|
|
|
18
20
|
}
|
|
19
21
|
};
|
|
20
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* A fresh device in an organization that forbids auto mode starts in sandbox mode (auto mode
|
|
25
|
+
* spec §4.1): the default policy is auto, which the kernel refuses at every exec, so the login
|
|
26
|
+
* line would otherwise describe a mode the machine does not run. Written under the policy lock,
|
|
27
|
+
* and only while no policy file exists: an existing policy is the owner's choice and is never
|
|
28
|
+
* changed here. Returns whether this call created the file.
|
|
29
|
+
*/
|
|
30
|
+
function persistSandboxPolicy(stateDir) {
|
|
31
|
+
const file = policyPath(stateDir);
|
|
32
|
+
if (existsSync(file))
|
|
33
|
+
return false;
|
|
34
|
+
return withPolicyLock(stateDir, () => {
|
|
35
|
+
if (existsSync(file))
|
|
36
|
+
return false;
|
|
37
|
+
writePolicy(stateDir, { ...DEFAULT_POLICY, mode: "sandbox" });
|
|
38
|
+
return true;
|
|
39
|
+
});
|
|
40
|
+
}
|
|
21
41
|
/** Normalises the deployment URL: http(s) origin plus optional path prefix, no trailing slash. */
|
|
22
42
|
export function normalizeUrl(raw) {
|
|
23
43
|
let u;
|
|
@@ -80,39 +100,76 @@ export async function login(cmd, deps) {
|
|
|
80
100
|
try {
|
|
81
101
|
const granted = await token(fetchFn, baseUrl, auth.deviceCode);
|
|
82
102
|
const dir = cmd.dir === undefined
|
|
83
|
-
? defaultWorkDir(granted.
|
|
103
|
+
? defaultWorkDir(granted.deviceId, deps.home)
|
|
84
104
|
: isAbsolute(cmd.dir)
|
|
85
105
|
? cmd.dir
|
|
86
106
|
: resolve(cmd.dir);
|
|
87
|
-
// Recreates a lost directory, marker or root: the
|
|
88
|
-
|
|
107
|
+
// Recreates a lost directory, marker or root: the device starts afresh.
|
|
108
|
+
prepareDeviceDir(dir);
|
|
109
|
+
// The printed line follows this machine's persisted policy in both branches, not the
|
|
110
|
+
// organization's allowance: sandbox mode is also the state an earlier login in an
|
|
111
|
+
// auto-forbidden organization left behind. The default mode is auto; an organization that
|
|
112
|
+
// forbids it gets sandbox mode written as this device's policy before the credential makes
|
|
113
|
+
// the login final. An existing policy is the owner's choice: the kernel refuses auto mode
|
|
114
|
+
// at every command if the organization forbids it and the owner keeps auto.
|
|
115
|
+
let mode = "auto";
|
|
116
|
+
if (granted.autoMode === "off") {
|
|
117
|
+
try {
|
|
118
|
+
mode = persistSandboxPolicy(deps.stateDir) ? "sandbox" : readPolicy(deps.stateDir).mode;
|
|
119
|
+
}
|
|
120
|
+
catch (e) {
|
|
121
|
+
err(`Cannot set the local policy in ${deps.stateDir}: ${e.message}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
try {
|
|
126
|
+
mode = readPolicy(deps.stateDir).mode;
|
|
127
|
+
}
|
|
128
|
+
catch (e) {
|
|
129
|
+
err(`Cannot read the local policy in ${deps.stateDir}: ${e.message}`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
89
132
|
writeCredential(deps.stateDir, {
|
|
90
133
|
url: baseUrl,
|
|
91
134
|
connectUrl: granted.connectUrl,
|
|
92
135
|
credential: granted.credential,
|
|
93
136
|
orgId: granted.orgId,
|
|
94
|
-
|
|
137
|
+
deviceId: granted.deviceId,
|
|
95
138
|
dir,
|
|
96
139
|
mode: cmd.mode,
|
|
97
140
|
reconnectGraceSeconds: granted.reconnectGraceSeconds,
|
|
98
141
|
maxFrameBytes: granted.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES,
|
|
99
142
|
});
|
|
100
|
-
out(`Logged in.
|
|
143
|
+
out(`Logged in. Device ${granted.deviceId}, working directory ${dir}`);
|
|
144
|
+
// The risk text is shown once at login (spec §8), and only when this machine runs auto.
|
|
145
|
+
if (granted.autoMode === "off") {
|
|
146
|
+
out(mode === "sandbox" ? SANDBOX_MODE_LOGIN_LINE : AUTO_POLICY_REFUSED_LOGIN_LINE);
|
|
147
|
+
}
|
|
148
|
+
else if (mode === "sandbox") {
|
|
149
|
+
out(SANDBOX_POLICY_LOGIN_LINE);
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
out(AUTO_MODE_LOGIN_LINE);
|
|
153
|
+
out(AUTO_MODE_RISK_TEXT);
|
|
154
|
+
}
|
|
155
|
+
out("Run `capybara-device start` to bring it online (or `capybara-device service install` to connect at login).");
|
|
101
156
|
return 0;
|
|
102
157
|
}
|
|
103
158
|
catch (e) {
|
|
104
159
|
if (!(e instanceof ApiError))
|
|
105
160
|
throw e;
|
|
106
|
-
if (e.code === "
|
|
161
|
+
if (e.code === "device_sign_in.slow_down")
|
|
107
162
|
interval += SLOW_DOWN_STEP_SECONDS;
|
|
108
|
-
else if (e.code === "
|
|
163
|
+
else if (e.code === "device_sign_in.authorization_pending" ||
|
|
164
|
+
e.status === 0 ||
|
|
165
|
+
e.status >= 500) {
|
|
109
166
|
// Keep polling at the normal interval: pending, a network blip or a server error.
|
|
110
167
|
}
|
|
111
|
-
else if (e.code === "
|
|
168
|
+
else if (e.code === "device_sign_in.expired") {
|
|
112
169
|
err("The code expired before it was approved. Run `capybara-device login` again.");
|
|
113
170
|
return 1;
|
|
114
171
|
}
|
|
115
|
-
else if (e.code === "
|
|
172
|
+
else if (e.code === "device_sign_in.denied") {
|
|
116
173
|
err("The login was denied in the browser.");
|
|
117
174
|
return 1;
|
|
118
175
|
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Command } from "../args.js";
|
|
2
|
+
/**
|
|
3
|
+
* Shown once before auto mode is turned on, and once at login in an organization that allows it
|
|
4
|
+
* (spec §8): the trust model is command review, not the OS sandbox.
|
|
5
|
+
*/
|
|
6
|
+
export declare const AUTO_MODE_RISK_TEXT: string;
|
|
7
|
+
/** The refusal of `capybara-device mode auto` without `--yes` or a `y` at the prompt. */
|
|
8
|
+
export declare const MODE_AUTO_NEEDS_YES = "Nothing changed. To run commands in auto mode, run: capybara-device mode auto --yes";
|
|
9
|
+
/** Printed before the question `capybara-device mode auto` asks on a terminal. */
|
|
10
|
+
export declare const MODE_AUTO_PROMPT = "Run agent commands on this computer as you, in auto mode? [y/N] ";
|
|
11
|
+
/**
|
|
12
|
+
* The line `login` prints when the organization allows auto mode and this machine's policy is
|
|
13
|
+
* auto (the default).
|
|
14
|
+
*/
|
|
15
|
+
export declare const AUTO_MODE_LOGIN_LINE: string;
|
|
16
|
+
/**
|
|
17
|
+
* The line `login` prints when the organization allows auto mode but this machine's persisted
|
|
18
|
+
* policy is sandbox mode (an earlier login in an auto-forbidden organization, or the owner's
|
|
19
|
+
* switch): the line follows the machine, not the allowance.
|
|
20
|
+
*/
|
|
21
|
+
export declare const SANDBOX_POLICY_LOGIN_LINE: string;
|
|
22
|
+
/** The line `login` prints when the organization forbids auto mode and the policy now says so. */
|
|
23
|
+
export declare const SANDBOX_MODE_LOGIN_LINE: string;
|
|
24
|
+
/**
|
|
25
|
+
* The line `login` prints when the organization forbids auto mode but the machine keeps its own
|
|
26
|
+
* auto policy: the kernel refuses every command until the owner switches the machine.
|
|
27
|
+
*/
|
|
28
|
+
export declare const AUTO_POLICY_REFUSED_LOGIN_LINE: string;
|
|
29
|
+
export interface ModeDeps {
|
|
30
|
+
stateDir: string;
|
|
31
|
+
out: (line: string) => void;
|
|
32
|
+
err: (line: string) => void;
|
|
33
|
+
/**
|
|
34
|
+
* Asks the question on a terminal (only when standard input is one). Without it and without
|
|
35
|
+
* `--yes`, `mode auto` changes nothing.
|
|
36
|
+
*/
|
|
37
|
+
ask?: (question: string) => Promise<string>;
|
|
38
|
+
/**
|
|
39
|
+
* Whether the OS sandbox can run here (default: the runtime's check). `mode sandbox` is refused
|
|
40
|
+
* when it cannot; injectable for tests.
|
|
41
|
+
*/
|
|
42
|
+
sandboxAvailable?: () => {
|
|
43
|
+
ok: true;
|
|
44
|
+
} | {
|
|
45
|
+
ok: false;
|
|
46
|
+
reason: string;
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** `mode` prints the current mode; `mode auto|sandbox` sets it (auto asks first). */
|
|
50
|
+
export declare function modeCommand(cmd: Extract<Command, {
|
|
51
|
+
command: "mode";
|
|
52
|
+
}>, deps: ModeDeps): Promise<number>;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { sandboxUnavailableSwitchRefusal } from "../exec/sandbox-messages.js";
|
|
2
|
+
import { PolicyStore } from "../policy-store.js";
|
|
3
|
+
import { policyPath, readCredential } from "../state.js";
|
|
4
|
+
/**
|
|
5
|
+
* Shown once before auto mode is turned on, and once at login in an organization that allows it
|
|
6
|
+
* (spec §8): the trust model is command review, not the OS sandbox.
|
|
7
|
+
*/
|
|
8
|
+
export const AUTO_MODE_RISK_TEXT = "In auto mode, agent commands run on this computer as you: they can read and write all your " +
|
|
9
|
+
"files, use your credentials (SSH keys, cloud accounts, keychain), Docker and any network, and " +
|
|
10
|
+
"the deployment reviews every command before it runs. Prompt injection can make an agent try " +
|
|
11
|
+
"to delete files or send your credentials away; the review blocks or asks about the dangerous " +
|
|
12
|
+
"ones. Such commands can also read this program's own credential: if you suspect misuse, run " +
|
|
13
|
+
"capybara-device logout and log in again.";
|
|
14
|
+
/** The refusal of `capybara-device mode auto` without `--yes` or a `y` at the prompt. */
|
|
15
|
+
export const MODE_AUTO_NEEDS_YES = "Nothing changed. To run commands in auto mode, run: capybara-device mode auto --yes";
|
|
16
|
+
/** Printed before the question `capybara-device mode auto` asks on a terminal. */
|
|
17
|
+
export const MODE_AUTO_PROMPT = "Run agent commands on this computer as you, in auto mode? [y/N] ";
|
|
18
|
+
/**
|
|
19
|
+
* The line `login` prints when the organization allows auto mode and this machine's policy is
|
|
20
|
+
* auto (the default).
|
|
21
|
+
*/
|
|
22
|
+
export const AUTO_MODE_LOGIN_LINE = "New logins start in auto mode: agent commands run as you on this machine, and the deployment " +
|
|
23
|
+
"reviews every command. Switch with `capybara-device mode sandbox`.";
|
|
24
|
+
/**
|
|
25
|
+
* The line `login` prints when the organization allows auto mode but this machine's persisted
|
|
26
|
+
* policy is sandbox mode (an earlier login in an auto-forbidden organization, or the owner's
|
|
27
|
+
* switch): the line follows the machine, not the allowance.
|
|
28
|
+
*/
|
|
29
|
+
export const SANDBOX_POLICY_LOGIN_LINE = "This organization allows auto mode, but this machine's local policy is sandbox mode: agent " +
|
|
30
|
+
"commands run inside the OS sandbox here. Switch with `capybara-device mode auto`.";
|
|
31
|
+
/** The line `login` prints when the organization forbids auto mode and the policy now says so. */
|
|
32
|
+
export const SANDBOX_MODE_LOGIN_LINE = "This organization does not allow auto mode, so this device runs in sandbox mode: agent " +
|
|
33
|
+
"commands run inside the OS sandbox on this machine.";
|
|
34
|
+
/**
|
|
35
|
+
* The line `login` prints when the organization forbids auto mode but the machine keeps its own
|
|
36
|
+
* auto policy: the kernel refuses every command until the owner switches the machine.
|
|
37
|
+
*/
|
|
38
|
+
export const AUTO_POLICY_REFUSED_LOGIN_LINE = "This organization does not allow auto mode, but this machine's local policy is auto mode: the " +
|
|
39
|
+
"deployment refuses every command until you run `capybara-device mode sandbox`.";
|
|
40
|
+
/** Whether this machine is logged in in Docker mode (false when unknown). */
|
|
41
|
+
function dockerRunMode(stateDir) {
|
|
42
|
+
try {
|
|
43
|
+
return readCredential(stateDir)?.mode === "docker";
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** `mode` prints the current mode; `mode auto|sandbox` sets it (auto asks first). */
|
|
50
|
+
export async function modeCommand(cmd, deps) {
|
|
51
|
+
const { stateDir, out, err } = deps;
|
|
52
|
+
let store;
|
|
53
|
+
try {
|
|
54
|
+
store = new PolicyStore(stateDir);
|
|
55
|
+
}
|
|
56
|
+
catch (e) {
|
|
57
|
+
err(`Cannot read ${policyPath(stateDir)}: ${e.message}`);
|
|
58
|
+
return 1;
|
|
59
|
+
}
|
|
60
|
+
const mode = cmd.mode;
|
|
61
|
+
if (mode === undefined) {
|
|
62
|
+
const now = store.current().mode;
|
|
63
|
+
out(`Mode: ${now}.`);
|
|
64
|
+
out(now === "auto"
|
|
65
|
+
? "Commands run as you on this machine; the deployment reviews every command."
|
|
66
|
+
: "Commands run in the OS sandbox; only the workspace, skills and temporary files are " +
|
|
67
|
+
"writable and the network reaches the allowed hosts.");
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
if (mode === "auto") {
|
|
71
|
+
// The risk text is printed once, whether --yes was given or the question is asked.
|
|
72
|
+
out(AUTO_MODE_RISK_TEXT);
|
|
73
|
+
if (cmd.yes !== true) {
|
|
74
|
+
if (deps.ask === undefined) {
|
|
75
|
+
err(MODE_AUTO_NEEDS_YES);
|
|
76
|
+
return 2;
|
|
77
|
+
}
|
|
78
|
+
const answer = (await deps.ask(MODE_AUTO_PROMPT)).trim().toLowerCase();
|
|
79
|
+
if (answer !== "y" && answer !== "yes") {
|
|
80
|
+
err("Nothing changed.");
|
|
81
|
+
return 1;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
let next;
|
|
86
|
+
if (mode === "sandbox" && !dockerRunMode(stateDir)) {
|
|
87
|
+
// Sandbox mode cannot run a command without the OS sandbox; refuse the switch on such a
|
|
88
|
+
// machine and leave the policy as it is (auto mode keeps working).
|
|
89
|
+
const os = await import("../exec/os.js");
|
|
90
|
+
const available = deps.sandboxAvailable?.() ?? os.sandboxAvailability();
|
|
91
|
+
if (!available.ok) {
|
|
92
|
+
err(sandboxUnavailableSwitchRefusal(available.reason));
|
|
93
|
+
return 1;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
next = store.update((p) => ({ ...p, mode })).mode;
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
err(`Cannot change ${policyPath(stateDir)}: ${e.message}`);
|
|
101
|
+
return 1;
|
|
102
|
+
}
|
|
103
|
+
out(next === "auto"
|
|
104
|
+
? "This machine's local policy is now auto mode (from the next command); the deployment's " +
|
|
105
|
+
"ceiling still applies."
|
|
106
|
+
: "This machine's local policy is now sandbox mode (from the next command).");
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
@@ -1,15 +1,24 @@
|
|
|
1
1
|
import type { Command } from "../args.js";
|
|
2
|
+
import { type Policy } from "../state.js";
|
|
2
3
|
export interface PolicyDeps {
|
|
3
4
|
stateDir: string;
|
|
4
5
|
out: (line: string) => void;
|
|
5
6
|
err: (line: string) => void;
|
|
6
7
|
}
|
|
7
|
-
/** What
|
|
8
|
+
/** What OS mode does not enforce yet, shown with `show` and with a limits change. */
|
|
8
9
|
export declare const NOT_ENFORCED_NOTE: string;
|
|
10
|
+
/** Shown when a Docker-mode device's policy is shown or given allowed domains. */
|
|
11
|
+
export declare const DOCKER_DOMAIN_NOTE: string;
|
|
12
|
+
/** What `policy show` says the mode gives on this machine (English, one line each). */
|
|
13
|
+
export declare function describeMode(policy: Policy, runMode?: "os" | "docker"): string[];
|
|
9
14
|
/**
|
|
10
|
-
* `policy show` prints the local policy
|
|
11
|
-
*
|
|
15
|
+
* `policy show` prints the local policy and what its mode gives on this machine;
|
|
16
|
+
* `policy set <key> <value>` replaces one field; `policy add|remove <key> <value>` adds or removes
|
|
17
|
+
* entries of a list field. The mode is set with `capybara-device mode`. The machine's user edits
|
|
18
|
+
* this file; the deployment changes it only through the `policy` op (narrowing only: hosts and
|
|
19
|
+
* `mode: "sandbox"`, never auto). Writes take policy.json.lock, and a running program applies the
|
|
20
|
+
* change at its next command.
|
|
12
21
|
*/
|
|
13
22
|
export declare function policyCommand(cmd: Extract<Command, {
|
|
14
23
|
command: "policy";
|
|
15
|
-
}>, deps: PolicyDeps): number
|
|
24
|
+
}>, deps: PolicyDeps): Promise<number>;
|