Public: anyone can read this; the crew can change it.

Crew runs can SSH to a device the repository names: an owner-granted host:22 plus a key from the repo's secrets (the arm's Pi) #16673

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/3470-crew-runs-can-ssh-to-a-device-the-reposi → main 0 commits fork

  • Merged. scout/3470-crew-runs-can-ssh-to-a-device-the-reposi was merged into main as 927e520.

Review

Sign in to review this change.
31 files changed +1775 −5
docs/APPS.md +7
@@ -758,6 +758,13 @@ destination under the cursor. The terminal is stricter than the page on
758758 purpose: a repository admin who is no site admin sees the list read-only on the
759759 page, and nothing on the terminal screen (no rows, no `g`/`x`).
760760
761 ### Devices the crew may reach (#3470)
762
763 A repository admin lists a device (`user@IPv4:port`) and the repo secret holding its key; a site admin grants it,
764 pinning the host key; a run then reaches exactly that `host:port`. Settings › Devices, the terminal's *Devices* screen
765 and `…/crew-devices` do the same. How it works, what it records and what it does not enforce:
766 `docs/features/crew-devices.md`.
767
761768 A release that turns egress on must not break an app whose writers have
762769 not declared what it uses yet, so an admin can set it reported:
763770 `cells.egress` = `report` on /settings/capacity (or the API's
docs/features/crew-devices.md added +32
@@ -0,0 +1,32 @@
1 ---
2 topic: Every setting, by topic
3 row: Devices the crew may SSH to
4 ---
5 # Devices the crew may SSH to
6
7 A crew run's shell reaches the forge and the registry only, unless its repository lists a granted device.
8
9 1. A repository admin lists one: `POST /api/v1/repos/:owner/:name/crew-devices` with
10 `{"device":"[email protected]:22","secret":"ARM_PI_SSH_KEY"}`. Exact `user@host:port`, no range; the key is a
11 secret at the repository's own scope.
12 2. A site admin grants it: `POST …/crew-devices/grant` with `{"device":"…"}`. The forge reads the host key the device
13 shows right then and pins it (or take `host_key` from the admin). A device is named by its IPv4 address: a name is refused (ssh would resolve it again
14 at run time), and so is an IPv6 or mapped address.
15 3. A run on that repository then has exactly that `host:port` in its sandbox, the key in a 0600 file, a pinned
16 `known_hosts` and an `ssh <alias>` config, all in its own temp directory and removed at the run's end. The brief
17 names the device and the rules (read and test freely, restart only what sudo allows, never change users, keys or
18 network).
19 4. `GET …/crew-devices` lists the devices and the sessions (`crew.device.session` events: who, when, arguments). The
20 session note is the run's own report, not an audit; the device's logs are.
21
22 `DELETE …/crew-devices` (the device in the body) unlists; changing the secret drops the grant.
23
24 Both doors: Settings › Devices (`src/web/pages/crew_devices.ts`) and the terminal screen (`src/tui/screens/crewdevices.ts`,
25 palette entry *Devices* in a repository you administer: `a` lists, `g` grants, `x` unlists, `s` flips to the sessions)
26 use the same actions. A repository admin lists, unlists and reads; only a site admin grants; anyone else sees nothing.
27 Each write is an event, so an open page or screen follows.
28
29 The `ssh` wrapper refuses a run's own `-o`, `-F` and `-J` so the pinned host key and the forwarding bans stand against
30 `ssh <alias>`; but a run can still start the real `ssh` by its path, so the pin is not enforced against a hostile run.
31 What bounds it is the sandbox: it reaches only that `host:port`. If `nc` is missing the device is *not reachable* and
32 named so in the run's log.
src/actions/crew_devices.ts added +161
@@ -0,0 +1,161 @@
1 /**
2 * The devices a repository's crew may SSH to (#3470). A repository admin
3 * lists a device and the repo secret holding its key; a site admin grants it,
4 * which pins the host key it shows right then. Every change is an event, and
5 * so is every ssh session a run made, so who, when and which commands are on
6 * the repository for its owner.
7 */
8
9 import type { App } from "../app.ts";
10 import {
11 addDevice,
12 grantDevice,
13 isHostKey,
14 listDevices,
15 parseDevice,
16 removeDevice,
17 type Device,
18 } from "../core/crew_devices.ts";
19 import { listEvents } from "../core/events.ts";
20 import type { Repo } from "../core/repos.ts";
21 import { getUserById, type User } from "../core/users.ts";
22 import { scanHostKey, type HostKeyScan } from "../crew/hostkey.ts";
23 import { err, ok, type Result } from "../kernel/result.ts";
24 import { requireRepoAdmin } from "./access.ts";
25
26 export type DeviceError = "not_found" | "forbidden" | "invalid" | "no_host_key" | "no_such_device";
27
28 export interface DeviceRow {
29 readonly entry: string;
30 readonly secret: string;
31 readonly granted: boolean;
32 readonly grantedBy: string | null;
33 readonly grantedAt: string | null;
34 readonly hostKey: string | null;
35 }
36
37 export interface DeviceSession {
38 readonly run: string;
39 readonly by: string;
40 readonly device: string;
41 readonly at: string;
42 readonly command: string;
43 }
44
45 const SESSIONS_SHOWN = 50;
46
47 const nameOf = (app: App, id: string | null): string | null =>
48 id === null ? null : (getUserById(app.db, id)?.username ?? "someone");
49
50 const row = (app: App, d: Device): DeviceRow => ({
51 entry: d.entry,
52 secret: d.secretName,
53 granted: d.grantedBy !== null && d.hostKey !== null,
54 grantedBy: nameOf(app, d.grantedBy),
55 grantedAt: d.grantedAt,
56 hostKey: d.hostKey,
57 });
58
59 function admin(app: App, actor: User | undefined, repo: Repo): Result<User, "not_found"> {
60 const checked = requireRepoAdmin(app, actor, repo);
61 return checked.ok ? ok(checked.value) : err("not_found");
62 }
63
64 /** The listed devices and the sessions the crew made on them; admin only. */
65 export function devicesView(
66 app: App,
67 actor: User | undefined,
68 repo: Repo,
69 ): Result<{ devices: DeviceRow[]; sessions: DeviceSession[]; canGrant: boolean }, "not_found"> {
70 const who = admin(app, actor, repo);
71 if (!who.ok) return who;
72 const sessions = listEvents(app.db, {
73 repoId: repo.id,
74 kind: "crew.device.session",
75 limit: SESSIONS_SHOWN,
76 }).map((e) => ({
77 run: String(e.payload["run"] ?? ""),
78 by: nameOf(app, e.actorId) ?? "someone",
79 device: String(e.payload["device"] ?? ""),
80 at: String(e.payload["at"] ?? e.createdAt),
81 command: String(e.payload["args"] ?? ""),
82 }));
83 return ok({
84 devices: listDevices(app.db, repo.id).map((d) => row(app, d)),
85 sessions,
86 canGrant: who.value.isAdmin && who.value.kind !== "agent",
87 });
88 }
89
90 /** List a device and its key's secret name (not yet granted). */
91 export function addCrewDevice(
92 app: App,
93 actor: User | undefined,
94 repo: Repo,
95 entry: string,
96 secret: string,
97 ): Result<DeviceRow, DeviceError> {
98 const who = admin(app, actor, repo);
99 if (!who.ok) return who;
100 if (who.value.kind === "agent") return err("forbidden");
101 const added = addDevice(app.db, repo.id, entry, secret.trim(), who.value);
102 if (!added.ok) return err("invalid");
103 app.bus.append({
104 kind: "crew.device.listed",
105 repoId: repo.id,
106 actorId: who.value.id,
107 payload: { device: added.value.entry, secret: added.value.secretName },
108 });
109 return ok(row(app, added.value));
110 }
111
112 /** A site admin's grant: pins `hostKey` when given, else the key the device shows now. */
113 export async function grantCrewDevice(
114 app: App,
115 actor: User | undefined,
116 repo: Repo,
117 entry: string,
118 hostKey: string,
119 scan: HostKeyScan = scanHostKey,
120 ): Promise<Result<DeviceRow, DeviceError>> {
121 const who = admin(app, actor, repo);
122 if (!who.ok) return who;
123 if (!who.value.isAdmin || who.value.kind === "agent") return err("forbidden");
124 const parsed = parseDevice(entry.trim());
125 if (!parsed.ok) return err("invalid");
126 if (!listDevices(app.db, repo.id).some((d) => d.entry === parsed.value.entry))
127 return err("no_such_device");
128 const key = hostKey.trim() !== "" ? hostKey.trim() : await scan(parsed.value.host, parsed.value.port);
129 if (key === undefined || !isHostKey(key)) return err("no_host_key");
130 const granted = grantDevice(app.db, repo.id, parsed.value.entry, key, who.value);
131 if (!granted.ok) return err("invalid");
132 app.bus.append({
133 kind: "crew.device.granted",
134 repoId: repo.id,
135 actorId: who.value.id,
136 payload: { device: granted.value.entry, hostKey: key },
137 });
138 return ok(row(app, granted.value));
139 }
140
141 /** Unlist a device, which takes its grant with it. */
142 export function removeCrewDevice(
143 app: App,
144 actor: User | undefined,
145 repo: Repo,
146 entry: string,
147 ): Result<string, DeviceError> {
148 const who = admin(app, actor, repo);
149 if (!who.ok) return who;
150 if (who.value.kind === "agent") return err("forbidden");
151 const parsed = parseDevice(entry.trim());
152 if (!parsed.ok) return err("invalid");
153 if (!removeDevice(app.db, repo.id, parsed.value.entry)) return err("no_such_device");
154 app.bus.append({
155 kind: "crew.device.removed",
156 repoId: repo.id,
157 actorId: who.value.id,
158 payload: { device: parsed.value.entry },
159 });
160 return ok(parsed.value.entry);
161 }
src/contract/openapi/routes/deleteApiV1ReposOwnerNameCrewDevices.ts added +11
@@ -0,0 +1,11 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: `${REPO}/crew-devices`,
6 summary: "Remove a device, named in the body (admin scope); answers {}",
7 auth: true,
8 role: "member",
9 body: { device: "string" },
10 refuses: [401, 404],
11 };
src/contract/openapi/routes/getApiV1ReposOwnerNameCrewDevices.ts added +10
@@ -0,0 +1,10 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "get",
5 path: `${REPO}/crew-devices`,
6 summary: "The devices the crew may SSH to and the runs' ssh sessions (admin scope)",
7 auth: true,
8 role: "member",
9 refuses: [401, 404],
10 };
src/contract/openapi/routes/index.ts +4
@@ -19,6 +19,7 @@ export { route as deleteApiV1ReposOwnerNameAppEnvVar } from "./deleteApiV1ReposO
1919 export { route as deleteApiV1ReposOwnerNameBranchesBranch } from "./deleteApiV1ReposOwnerNameBranchesBranch.ts";
2020 export { route as deleteApiV1ReposOwnerNameBuildsLabel } from "./deleteApiV1ReposOwnerNameBuildsLabel.ts";
2121 export { route as deleteApiV1ReposOwnerNameBuildsLabelShotsFile } from "./deleteApiV1ReposOwnerNameBuildsLabelShotsFile.ts";
22 export { route as deleteApiV1ReposOwnerNameCrewDevices } from "./deleteApiV1ReposOwnerNameCrewDevices.ts";
2223 export { route as deleteApiV1ReposOwnerNameCrewUsername } from "./deleteApiV1ReposOwnerNameCrewUsername.ts";
2324 export { route as deleteApiV1ReposOwnerNameDeskId } from "./deleteApiV1ReposOwnerNameDeskId.ts";
2425 export { route as deleteApiV1ReposOwnerNameDropFile } from "./deleteApiV1ReposOwnerNameDropFile.ts";
@@ -158,6 +159,7 @@ export { route as getApiV1ReposOwnerNameCommitsOidCheck } from "./getApiV1ReposO
158159 export { route as getApiV1ReposOwnerNameContents } from "./getApiV1ReposOwnerNameContents.ts";
159160 export { route as getApiV1ReposOwnerNameContentsPath } from "./getApiV1ReposOwnerNameContentsPath.ts";
160161 export { route as getApiV1ReposOwnerNameCrew } from "./getApiV1ReposOwnerNameCrew.ts";
162 export { route as getApiV1ReposOwnerNameCrewDevices } from "./getApiV1ReposOwnerNameCrewDevices.ts";
161163 export { route as getApiV1ReposOwnerNameData } from "./getApiV1ReposOwnerNameData.ts";
162164 export { route as getApiV1ReposOwnerNameDataEnvFileRows } from "./getApiV1ReposOwnerNameDataEnvFileRows.ts";
163165 export { route as getApiV1ReposOwnerNameDataEnvFileTables } from "./getApiV1ReposOwnerNameDataEnvFileTables.ts";
@@ -377,6 +379,8 @@ export { route as postApiV1ReposOwnerNameChecksRecheck } from "./postApiV1ReposO
377379 export { route as postApiV1ReposOwnerNameContents } from "./postApiV1ReposOwnerNameContents.ts";
378380 export { route as postApiV1ReposOwnerNameContribute } from "./postApiV1ReposOwnerNameContribute.ts";
379381 export { route as postApiV1ReposOwnerNameCopies } from "./postApiV1ReposOwnerNameCopies.ts";
382 export { route as postApiV1ReposOwnerNameCrewDevices } from "./postApiV1ReposOwnerNameCrewDevices.ts";
383 export { route as postApiV1ReposOwnerNameCrewDevicesGrant } from "./postApiV1ReposOwnerNameCrewDevicesGrant.ts";
380384 export { route as postApiV1ReposOwnerNameDataEnvFileQuery } from "./postApiV1ReposOwnerNameDataEnvFileQuery.ts";
381385 export { route as postApiV1ReposOwnerNameDataImport } from "./postApiV1ReposOwnerNameDataImport.ts";
382386 export { route as postApiV1ReposOwnerNameDataMove } from "./postApiV1ReposOwnerNameDataMove.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNameCrewDevices.ts added +11
@@ -0,0 +1,11 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/crew-devices`,
6 summary: "List a device and the repo secret holding its key; not yet granted (admin scope)",
7 auth: true,
8 role: "member",
9 body: { device: "string", secret: "string" },
10 refuses: [401, 404],
11 };
src/contract/openapi/routes/postApiV1ReposOwnerNameCrewDevicesGrant.ts added +11
@@ -0,0 +1,11 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/crew-devices/grant`,
6 summary: "A site admin grants a listed device, pinning its host key (admin scope)",
7 auth: true,
8 role: "member",
9 body: { device: "string", host_key: "string" },
10 refuses: [401, 404],
11 };
src/contract/tags.ts +1
@@ -6,6 +6,7 @@
66
77 /** A path segment that names a resource under another tag. */
88 const ALIAS: Readonly<Record<string, string>> = {
9 "crew-devices": "crew",
910 oembed: "meta",
1011 app: "apps",
1112 timers: "apps",
src/core/account_purge.ts +2
@@ -54,6 +54,8 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5454 "allocation_entry.actor_id": FORMER,
5555 "allocation_weekly.set_by": FORMER,
5656 "cloud_watch_ack.by": FORMER,
57 "crew_device.added_by": FORMER,
58 "crew_device.granted_by": FORMER,
5759 "account_notice.user_id": DELETE,
5860 "account_request.decided_by": FORMER,
5961 "admin_ask.user_id": DELETE,
src/core/crew_devices.ts added +155
@@ -0,0 +1,155 @@
1 /**
2 * Devices a repository's crew may SSH to (#3470): `user@host:port`, exact, and
3 * the name of the repository secret holding the key. A repository admin lists
4 * a device; only a site admin's grant (which pins the host key) lets a run
5 * reach it. Same exactness and never-grantable ranges as app egress.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { isIP } from "node:net";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import { neverGrantable, parseDestination } from "./egress_grants.ts";
12 import { isSecretName } from "./secret_store.ts";
13
14 export interface Device {
15 readonly repoId: string;
16 /** `user@host:port`, lowercased host. */
17 readonly entry: string;
18 readonly user: string;
19 readonly host: string;
20 readonly port: number;
21 readonly secretName: string;
22 readonly addedBy: string;
23 readonly grantedBy: string | null;
24 readonly grantedAt: string | null;
25 /** The pinned key as a known_hosts key part: `ssh-ed25519 AAAA…`. */
26 readonly hostKey: string | null;
27 }
28
29 const USER_RE = /^[a-z_][a-z0-9_-]{0,31}$/;
30 const MAX_PER_REPO = 8;
31 /** A host key line's key part: type and base64 blob, nothing more. */
32 const HOST_KEY_RE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(?:256|384|521)) [A-Za-z0-9+/]{20,2000}={0,2}$/;
33
34 export const isHostKey = (text: string): boolean => HOST_KEY_RE.test(text);
35
36 /** `user@host:port` exactly, or why not. */
37 export function parseDevice(
38 text: string,
39 ): Result<{ user: string; host: string; port: number; entry: string }, string> {
40 const at = text.indexOf("@");
41 const user = text.slice(0, at);
42 if (at < 1 || !USER_RE.test(user))
43 return err("a device is user@host:port, like [email protected]:22");
44 const dest = parseDestination(text.slice(at + 1));
45 if (!dest.ok) return dest;
46 const { host, port } = dest.value;
47 // A literal IPv4 address only: a name is resolved again by ssh at run time
48 // (rebinding), and an IPv6 or mapped address is not checked against the
49 // never-grantable ranges. The device's address is what the sandbox opens.
50 if (isIP(host) !== 4) return err("a device is named by its IPv4 address, not a name or an IPv6 address");
51 if (neverGrantable(host)) return err(`${host} can never be granted`);
52 return ok({ user, host, port, entry: `${user}@${host}:${port}` });
53 }
54
55 interface Row {
56 repo_id: string;
57 entry: string;
58 secret_name: string;
59 added_by: string;
60 granted_by: string | null;
61 granted_at: string | null;
62 host_key: string | null;
63 }
64
65 function toDevice(r: Row): Device | undefined {
66 const parsed = parseDevice(r.entry);
67 if (!parsed.ok) return undefined;
68 return {
69 repoId: r.repo_id,
70 entry: parsed.value.entry,
71 user: parsed.value.user,
72 host: parsed.value.host,
73 port: parsed.value.port,
74 secretName: r.secret_name,
75 addedBy: r.added_by,
76 grantedBy: r.granted_by,
77 grantedAt: r.granted_at,
78 hostKey: r.host_key,
79 };
80 }
81
82 export function listDevices(db: Database, repoId: string): Device[] {
83 return db
84 .query<Row, [string]>("SELECT * FROM crew_device WHERE repo_id = ?1 ORDER BY entry")
85 .all(repoId)
86 .flatMap((r) => toDevice(r) ?? []);
87 }
88
89 /** The devices a run may use: granted, with a pinned key. */
90 export const grantedDevices = (db: Database, repoId: string): Device[] =>
91 listDevices(db, repoId).filter((d) => d.grantedBy !== null && d.hostKey !== null);
92
93 /** List a device (or change its secret); a changed secret loses its grant. */
94 export function addDevice(
95 db: Database,
96 repoId: string,
97 entry: string,
98 secretName: string,
99 by: { id: string },
100 ): Result<Device, string> {
101 const parsed = parseDevice(entry.trim());
102 if (!parsed.ok) return parsed;
103 if (!isSecretName(secretName)) return err("the key's secret name is not a usable name");
104 const count = listDevices(db, repoId).filter((d) => d.entry !== parsed.value.entry).length;
105 if (count >= MAX_PER_REPO) return err(`at most ${MAX_PER_REPO} devices per repository`);
106 db.query(
107 `INSERT INTO crew_device (repo_id, entry, secret_name, added_by) VALUES (?1, ?2, ?3, ?4)
108 ON CONFLICT(repo_id, entry) DO UPDATE SET secret_name = ?3, added_by = ?4,
109 granted_by = CASE WHEN secret_name = ?3 THEN granted_by END,
110 granted_at = CASE WHEN secret_name = ?3 THEN granted_at END,
111 host_key = CASE WHEN secret_name = ?3 THEN host_key END`,
112 ).run(repoId, parsed.value.entry, secretName, by.id);
113 return found(db, repoId, parsed.value.entry);
114 }
115
116 function found(db: Database, repoId: string, entry: string): Result<Device, string> {
117 const row = db
118 .query<Row, [string, string]>("SELECT * FROM crew_device WHERE repo_id = ?1 AND entry = ?2")
119 .get(repoId, entry);
120 const device = row === null ? undefined : toDevice(row);
121 return device === undefined ? err("no such device") : ok(device);
122 }
123
124 /** A site admin's yes, with the host key to pin. */
125 export function grantDevice(
126 db: Database,
127 repoId: string,
128 entry: string,
129 hostKey: string,
130 admin: { id: string; isAdmin: boolean },
131 ): Result<Device, string> {
132 if (!admin.isAdmin) return err("only a site admin grants a device");
133 const parsed = parseDevice(entry.trim());
134 if (!parsed.ok) return parsed;
135 if (!isHostKey(hostKey)) return err("not a host key");
136 const changed = db
137 .query(
138 `UPDATE crew_device SET granted_by = ?3, host_key = ?4,
139 granted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')
140 WHERE repo_id = ?1 AND entry = ?2`,
141 )
142 .run(repoId, parsed.value.entry, admin.id, hostKey).changes;
143 return changed === 0 ? err("no such device") : found(db, repoId, parsed.value.entry);
144 }
145
146 /** Unlist a device (and so revoke it); true when there was one. */
147 export function removeDevice(db: Database, repoId: string, entry: string): boolean {
148 const parsed = parseDevice(entry.trim());
149 if (!parsed.ok) return false;
150 return (
151 db
152 .query("DELETE FROM crew_device WHERE repo_id = ?1 AND entry = ?2")
153 .run(repoId, parsed.value.entry).changes > 0
154 );
155 }
src/core/event_audience.ts +2
@@ -408,6 +408,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
408408 // A pull waiting on a named team's review is that team's news alone
409409 // (`actions/team_waits.ts`, #10164): its members, among those who may read.
410410 if (kind === "pull.team_waiting" || kind === "pull.team_answered") return "team";
411 // A device the crew may SSH to names a private address: the repository's admins hear it (#3470).
412 if (kind.startsWith("crew.device.")) return "admins";
411413 if (READER_KINDS.has(kind)) return "readers";
412414 return undefined;
413415 }
src/core/migration-pins/20261021120000-crew-devices.pin added +1
@@ -0,0 +1,1 @@
1 4d572d534e988d89ad36fbfd6c502f845e3f6af1b87f344676e826019cd6124e
src/core/migrations/20261021120000-crew-devices.ts added +16
@@ -0,0 +1,16 @@
1 // A device a repository's crew may SSH to (#3470): `user@host:port`, the repo
2 // secret that holds its key, and, once a site admin grants it, who did and the
3 // host key pinned at that moment. Additive; a row with no granted_by opens
4 // nothing.
5 export default `
6 CREATE TABLE crew_device (
7 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
8 entry TEXT NOT NULL,
9 secret_name TEXT NOT NULL,
10 added_by TEXT NOT NULL REFERENCES user(id),
11 granted_by TEXT REFERENCES user(id),
12 granted_at TEXT,
13 host_key TEXT,
14 PRIMARY KEY (repo_id, entry)
15 );
16 `;
src/crew/brief.ts +4
@@ -18,6 +18,7 @@ import { OUTSIDE_LABEL, OUTSIDE_TITLE, saysOutside } from "../core/reports.ts";
1818 import type { Repo } from "../core/repos.ts";
1919 import { DESIGN_POINTER, DESIGN_PRINCIPLES } from "./design_principles.ts";
2020 import { READER } from "./direct.ts";
21 import { deviceLines } from "./devices.ts";
2122 import { hotFiles, hotWords } from "./hot_files.ts";
2223 import { newsSince } from "./news.ts";
2324 import {
@@ -64,6 +65,8 @@ export interface BriefInput {
6465 * it writes obey the cells and the cells it does not touch stay decided.
6566 */
6667 readonly policy?: PolicyBrief | undefined;
68 /** Device aliases the run may `ssh` to (`crew/devices.ts`), alias → entry. */
69 readonly devices?: Readonly<Record<string, string>> | undefined;
6770 /**
6871 * What the runner calls the forge's tools, when its harness names them
6972 * differently (a prefix, another convention). The brief carries only
@@ -258,6 +261,7 @@ export function systemPrompt(input: BriefInput): string {
258261 lines.push(
259262 "",
260263 ...SANDBOX_LINES,
264 ...deviceLines(input.devices ?? {}),
261265 "",
262266 "Work carefully and finish. If the task is unclear, impossible, or not something you should do, do not guess: make your last message start with `DECLINED:` followed by exactly why. Nothing is pushed then, and a person reads it.",
263267 "If the issue is already done on the base branch, decline with `DECLINED: already done on main in <commit>` naming the full or abbreviated id of each commit that did it (at most five); the forge checks they are on the base, and a person closes the issue.",
src/crew/devices.ts added +249
@@ -0,0 +1,249 @@
1 /**
2 * The devices a crew run may SSH to (#3470). For a run on a repository with
3 * granted devices, `deviceKit` materializes in the run's temp directory a key
4 * file per device (0600), a pinned known_hosts, an ssh config with an alias
5 * per device, and an `ssh` wrapper first on the run's PATH that notes each
6 * invocation. That note is the run's own self-reported record, not an audit:
7 * it lives where the run can write. The key reaches no argv, environment or log; the kit removes it
8 * (`release`) and the sandbox is told exactly the host:port pairs.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import {
13 chmodSync,
14 closeSync,
15 constants,
16 fstatSync,
17 lstatSync,
18 mkdirSync,
19 openSync,
20 readSync,
21 rmSync,
22 writeFileSync,
23 } from "node:fs";
24 import { join } from "node:path";
25 import { grantedDevices, type Device } from "../core/crew_devices.ts";
26 import type { EventBus } from "../core/events.ts";
27 import { resolveScoped } from "../core/secret_store.ts";
28 import { holdValues, releaseValues } from "../kernel/log.ts";
29 import { knownHostsLine } from "./hostkey.ts";
30
31 export interface DeviceKit {
32 /** `host:port` pairs the sandbox may reach. */
33 readonly hosts: readonly string[];
34 /** The directory to put first on the run's PATH. */
35 readonly binDir: string;
36 /** Alias → entry, for the brief and the log. */
37 readonly aliases: Readonly<Record<string, string>>;
38 /** Devices granted whose key is not a repository secret, by entry. */
39 readonly missing: readonly string[];
40 /** The ssh invocations made so far: when and with what arguments. */
41 readonly sessions: () => Sessions;
42 /** Every form of the private keys held: the push-time leak guard refuses these. */
43 readonly values: readonly string[];
44 /** Remove the key files and forget the value. Safe to call twice. */
45 readonly release: () => void;
46 }
47
48 export interface Sessions {
49 readonly entries: { at: string; alias: string; args: string }[];
50 /** Lines or bytes beyond the caps, not reported. */
51 readonly dropped: number;
52 }
53
54 const MAX_LOG_BYTES = 64 * 1024;
55 const MAX_SESSIONS = 50;
56
57 /**
58 * The run writes this file, so the forge reads it as hostile: the directory
59 * and the file must be real (no symlink) and ours, at most 64 KiB are read,
60 * at most 50 sessions are kept, and control characters are stripped.
61 */
62 function readSessions(root: string, log: string): Sessions {
63 const none: Sessions = { entries: [], dropped: 0 };
64 const me = process.getuid?.();
65 let fd: number | undefined;
66 try {
67 const dir = lstatSync(root);
68 if (!dir.isDirectory() || (me !== undefined && dir.uid !== me)) return none;
69 const st = lstatSync(log);
70 if (!st.isFile() || (me !== undefined && st.uid !== me)) return none;
71 fd = openSync(log, constants.O_RDONLY | constants.O_NOFOLLOW);
72 const fst = fstatSync(fd);
73 if (!fst.isFile() || fst.ino !== st.ino) return none;
74 const buf = Buffer.alloc(Math.min(fst.size, MAX_LOG_BYTES));
75 const n = readSync(fd, buf, 0, buf.length, 0);
76 const lines = buf.subarray(0, n).toString("utf8").split("\n").filter((l) => l !== "");
77 const truncated = fst.size > MAX_LOG_BYTES;
78 // Control characters (newlines, escapes) never reach a log line or event.
79 const clean = (v: string) => v.replace(/[\x00-\x1f\x7f-\x9f]/g, " ");
80 const entries = lines.slice(0, MAX_SESSIONS).map((l) => {
81 const [at = "", alias = "", ...rest] = l.split("\t");
82 return {
83 at: clean(at).slice(0, 40),
84 alias: clean(alias).slice(0, 64),
85 args: clean(rest.join(" ")).slice(0, 2000),
86 };
87 });
88 return {
89 entries,
90 dropped: Math.max(0, lines.length - MAX_SESSIONS) + (truncated ? 1 : 0),
91 };
92 } catch {
93 return none;
94 } finally {
95 if (fd !== undefined) closeSync(fd);
96 }
97 }
98
99 /** `pi`, `pi-2`: the alias is the host's first label, deduplicated. */
100 function aliasFor(d: Device, taken: Set<string>): string {
101 const base = d.host.split(".")[0]!.replace(/[^a-z0-9-]/g, "") || "device";
102 let alias = /^\d+$/.test(base) ? `device-${base}` : base;
103 for (let n = 2; taken.has(alias); n++) alias = `${base}-${n}`;
104 taken.add(alias);
105 return alias;
106 }
107
108 /**
109 * The wrapper's first lines: a run may not add its own ssh options (`-o`),
110 * config file (`-F`) or jump host (`-J`), alone or bundled (`-vo…`), which
111 * would undo the pinned host key and the forwarding bans. A remote command
112 * that starts with a dash goes in one quoted argument (`ssh pi "ls -o"`).
113 */
114 const REFUSE_FLAGS = `for a in "$@"; do case "$a" in -[!-]*[oFJ]*|-[oFJ]*) echo "ssh: -o, -F and -J are not allowed here" >&2; exit 2;; esac; done`;
115
116 const SAFE_PATH = /^[A-Za-z0-9_./-]+$/;
117
118 export function deviceKit(
119 db: Database,
120 dataDir: string,
121 bus: EventBus,
122 run: { id: string; repoId: string; actorId: string },
123 tmpDir: string,
124 ssh: string | null = Bun.which("ssh"),
125 nc: string | null = Bun.which("nc"),
126 ): DeviceKit | undefined {
127 const devices = grantedDevices(db, run.repoId);
128 if (devices.length === 0 || ssh === null || !SAFE_PATH.test(tmpDir) || !SAFE_PATH.test(ssh))
129 return undefined;
130 // Repository scope only: a device cannot name the forge's or an org's secret.
131 const secrets = resolveScoped(
132 db,
133 dataDir,
134 bus,
135 devices.map((d) => d.secretName),
136 { repo: run.repoId, run: run.id, actor: run.actorId },
137 );
138 const root = join(tmpDir, "ssh");
139 const binDir = join(root, "bin");
140 mkdirSync(binDir, { recursive: true, mode: 0o700 });
141 const taken = new Set<string>();
142 const aliases: Record<string, string> = {};
143 const missing: string[] = [];
144 const values: string[] = [];
145 const config: string[] = [];
146 const known: string[] = [];
147 for (const d of devices) {
148 const secret = secrets[d.secretName];
149 // No `nc` means the ProxyCommand would hang the run: the device is missing.
150 if (nc === null || !SAFE_PATH.test(nc) || secret === undefined || secret.scope !== "repo") {
151 missing.push(d.entry);
152 continue;
153 }
154 const alias = aliasFor(d, taken);
155 aliases[alias] = d.entry;
156 const keyFile = join(root, `key-${alias}`);
157 const value = secret.value.endsWith("\n") ? secret.value : `${secret.value}\n`;
158 writeFileSync(keyFile, value, { mode: 0o600 });
159 chmodSync(keyFile, 0o600);
160 values.push(secret.value, secret.value.trim());
161 known.push(knownHostsLine(d));
162 config.push(
163 `Host ${alias}`,
164 ` HostName ${d.host}`,
165 ` Port ${d.port}`,
166 ` User ${d.user}`,
167 ` IdentityFile ${keyFile}`,
168 " IdentitiesOnly yes",
169 " StrictHostKeyChecking yes",
170 ` UserKnownHostsFile ${join(root, "known_hosts")}`,
171 " GlobalKnownHostsFile /dev/null",
172 " ForwardAgent no",
173 " ForwardX11 no",
174 " ClearAllForwardings yes",
175 " BatchMode yes",
176 ` ProxyCommand ${join(binDir, "proxy")} %h %p`,
177 "",
178 );
179 }
180 if (values.length > 0) holdValues(`device:${run.id}`, values);
181 const log = join(root, "sessions.log");
182 writeFileSync(join(root, "known_hosts"), known.join(""), { mode: 0o600 });
183 writeFileSync(join(root, "config"), config.join("\n"), { mode: 0o600 });
184 writeFileSync(log, "", { mode: 0o600 });
185 // Through the sandbox's SOCKS proxy when there is one (ALL_PROXY), else direct.
186 writeFileSync(
187 join(binDir, "proxy"),
188 `#!/bin/sh\nNC='${nc ?? "nc"}'\nif [ -n "$ALL_PROXY" ]; then exec "$NC" -X 5 -x "\${ALL_PROXY#*://}" "$1" "$2"; fi\nexec "$NC" "$1" "$2"\n`,
189 { mode: 0o700 },
190 );
191 writeFileSync(
192 join(binDir, "ssh"),
193 `#!/bin/sh\n${REFUSE_FLAGS}\nprintf '%s\\t%s\\t%s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" "$*" >> '${log}'\nexec '${ssh}' -F '${join(root, "config")}' "$@"\n`,
194 { mode: 0o700 },
195 );
196 return {
197 hosts: devices.filter((d) => !missing.includes(d.entry)).map((d) => `${d.host}:${d.port}`),
198 binDir,
199 aliases,
200 missing,
201 values,
202 sessions: () => readSessions(root, log),
203 release: () => {
204 releaseValues(`device:${run.id}`);
205 rmSync(root, { recursive: true, force: true });
206 },
207 };
208 }
209
210 /** What the brief tells the crew about the devices it may reach. */
211 export function deviceLines(aliases: Readonly<Record<string, string>>): string[] {
212 const names = Object.entries(aliases);
213 if (names.length === 0) return [];
214 return [
215 "",
216 "Devices you may reach over SSH (the owner granted them to this repository):",
217 ...names.map(([alias, entry]) => `- \`ssh ${alias}\` is ${entry}; run a command with \`ssh ${alias} <command>\`.`),
218 "- Read and test freely. Restart only the services its sudo allows (`sudo systemctl restart|status` on the units the owner named). Never change the device's users, keys, authorized keys or network, and never copy its key anywhere.",
219 "- The `ssh` wrapper notes each call you make for the owner to read; that note is your own record, not a tamper-proof audit, so keep to `ssh <alias>` and never bypass it.",
220 ];
221 }
222
223 /**
224 * Each ssh call the run made, as an event on the repository (admin-only to read); the log line too.
225 */
226 export function recordDeviceSessions(
227 bus: EventBus,
228 kit: DeviceKit,
229 run: { id: string; repoId: string },
230 actorId: string,
231 write: (line: string) => void,
232 ): void {
233 const { entries, dropped } = kit.sessions();
234 if (dropped > 0) write(`ssh: ${dropped} more session notes dropped (cap reached)`);
235 for (const session of entries) {
236 write(`ssh ${session.alias}: ${session.args}`);
237 bus.append({
238 kind: "crew.device.session",
239 repoId: run.repoId,
240 actorId,
241 payload: {
242 run: run.id,
243 device: kit.aliases[session.alias] ?? session.alias,
244 at: session.at,
245 args: session.args,
246 },
247 });
248 }
249 }
src/crew/hostkey.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * The host key a device shows, read once when a site admin grants it (#3470)
3 * and pinned from then on; a changed key afterwards refuses the connection.
4 */
5
6 import { isHostKey, type Device } from "../core/crew_devices.ts";
7
8 export type HostKeyScan = (host: string, port: number) => Promise<string | undefined>;
9
10 /** `ssh-keyscan` for an ed25519 key; host and port are validated by the caller. */
11 export const scanHostKey: HostKeyScan = async (host, port) => {
12 let out = "";
13 try {
14 const proc = Bun.spawn(
15 ["ssh-keyscan", "-T", "5", "-t", "ed25519,ecdsa,rsa", "-p", String(port), host],
16 { stdin: "ignore", stdout: "pipe", stderr: "ignore", timeout: 10_000, killSignal: "SIGKILL" },
17 );
18 out = await new Response(proc.stdout).text();
19 await proc.exited;
20 } catch {
21 return undefined;
22 }
23 return pickHostKey(out);
24 };
25
26 /** ed25519 first, then ecdsa, then rsa, from `ssh-keyscan`'s lines. */
27 export function pickHostKey(out: string): string | undefined {
28 const keys = out
29 .split("\n")
30 .filter((line) => !line.startsWith("#"))
31 .map((line) => line.split(" ").slice(1).join(" ").trim())
32 .filter(isHostKey);
33 for (const kind of ["ssh-ed25519", "ecdsa-", "ssh-rsa"]) {
34 const key = keys.find((k) => k.startsWith(kind));
35 if (key !== undefined) return key;
36 }
37 return undefined;
38 }
39
40 /** The known_hosts line that pins a device. */
41 export const knownHostsLine = (d: Device): string =>
42 `${d.port === 22 ? d.host : `[${d.host}]:${d.port}`} ${d.hostKey ?? ""}\n`;
src/crew/leak.ts +8 −2
@@ -80,11 +80,17 @@ export async function pushHolds(
8080 async function logHolds(
8181 dir: string,
8282 revs: readonly string[],
83 forms: readonly string[],
83 held: readonly string[],
8484 env: Record<string, string>,
8585 clone: boolean,
8686 ): Promise<boolean> {
87 if (forms.length === 0) return false;
87 if (held.length === 0) return false;
88 // A patch prefixes every line, so a multi-line value (a private key) never
89 // appears whole in it: its long lines are searched one by one.
90 const forms = [
91 ...held,
92 ...held.flatMap((f) => (f.includes("\n") ? f.split("\n").filter((l) => l.length >= 24) : [])),
93 ];
8894 // No driver of the repository's runs to show a diff (#14747); a crew clone
8995 // is read as every forge git in one is (`clone_git.ts`), a bare
9096 // repository in pre-receive as it is.
src/crew/runner.ts +26 −2
@@ -204,6 +204,7 @@ import { trackAgentRun, untrackAgentRun } from "./running.ts";
204204 import { workBegins, workEnds } from "../runs/ending.ts";
205205 import { installCacheEnv, makeRunTmp, sandboxPolicy } from "./sandbox.ts";
206206 import { runGitAuth } from "./git_auth.ts";
207 import { deviceKit, recordDeviceSessions, type DeviceKit } from "./devices.ts";
207208 import { grantSecrets, needsYou, parseDeclaration, ungrantedSentence, type Grant } from "./grant.ts";
208209 import { historyHolds, scrubTree } from "./leak.ts";
209210 import {
@@ -1233,6 +1234,7 @@ async function work(
12331234 const modelHold = `run:${run.id}:model`;
12341235 let modelSecrets: string[] = [];
12351236 let runTmp: string | undefined;
1237 let devices: DeviceKit | undefined;
12361238 let gatewayDoor: GatewayDoor | undefined;
12371239 let early: EarlyPull | undefined;
12381240 // A paused run resumes: its pull keeps saying "In progress".
@@ -1704,6 +1706,7 @@ async function work(
17041706 extraHosts: [
17051707 ...(options.allowHosts ?? []),
17061708 ...hosts,
1709 ...(devices?.hosts ?? []),
17071710 ],
17081711 gateway: gatewayDoor?.base,
17091712 enforced: options.sandboxEnforced,
@@ -1720,6 +1723,23 @@ async function work(
17201723 makeRunTmp(app.config.dataDir, runTmp);
17211724 Object.assign(env, sandboxTmpEnv(runTmp));
17221725 env["TMPDIR"] = runTmp;
1726 // The devices the owner granted this repository: a key file, a pinned
1727 // known_hosts and an `ssh` wrapper that logs, all inside the run's own
1728 // temp directory, which goes with the run.
1729 devices = deviceKit(
1730 app.db,
1731 app.config.dataDir,
1732 app.bus,
1733 { id: run.id, repoId: repo.id, actorId: agent.user.id },
1734 runTmp,
1735 );
1736 if (devices !== undefined) {
1737 env["PATH"] = `${devices.binDir}:${process.env["PATH"] ?? "/usr/local/bin:/usr/bin:/bin"}`;
1738 for (const [alias, entry] of Object.entries(devices.aliases))
1739 write(`device: ssh ${alias} is ${entry}`);
1740 for (const entry of devices.missing)
1741 write(`device not reachable: ${entry} (its key is not a repository secret)`);
1742 }
17231743 }
17241744 // Bun's install cache is the repository's, shared by its runs, so a
17251745 // package is downloaded once rather than by every clone.
@@ -1761,7 +1781,7 @@ async function work(
17611781 binary: options.binary,
17621782 cwd: dir,
17631783 prompt,
1764 appendSystemPrompt: systemPrompt(brief),
1784 appendSystemPrompt: systemPrompt({ ...brief, devices: devices?.aliases }),
17651785 model: chosen.model || undefined,
17661786 budgetUsd,
17671787 account: runAccount(picked, env),
@@ -2174,7 +2194,7 @@ async function work(
21742194 : `Budget reached at $${stoppedAt.toFixed(2)}; this is where it stopped.`,
21752195 ),
21762196 write,
2177 [...Object.values(grant.env), ...modelSecrets],
2197 [...Object.values(grant.env), ...modelSecrets, ...(devices?.values ?? [])],
21782198 run.variantGroup,
21792199 ran.hops,
21802200 );
@@ -2199,6 +2219,10 @@ async function work(
21992219 await early?.stop();
22002220 if (!pausing) early?.settle(ending);
22012221 grant?.release();
2222 if (devices !== undefined) {
2223 recordDeviceSessions(app.bus, devices, run, agent.user.id, write);
2224 devices.release();
2225 }
22022226 gatewayDoor?.close();
22032227 releaseValues(modelHold);
22042228 releaseValues(tokenHold);
src/http/api.ts +2
@@ -311,6 +311,7 @@ import { frontInput, frontJson, setFront } from "../actions/front.ts";
311311 import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts";
312312 import { passportRoutes } from "./passport_edge.ts";
313313 import { egressGrantRoutes } from "./api/egress_grants.ts";
314 import { crewDeviceRoutes } from "./api/crew_devices.ts";
314315 import { reachAskRoutes } from "./api/reach_asks.ts";
315316 import { adminAskRoutes } from "./api/admin_asks.ts";
316317 import { printRoutes } from "./api/print.ts";
@@ -3198,6 +3199,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
31983199 deepsecRoutes(router);
31993200
32003201 egressGrantRoutes(router);
3202 crewDeviceRoutes(router);
32013203 reachAskRoutes(router);
32023204 adminAskRoutes(router);
32033205 printRoutes(router);
src/http/api/crew_devices.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * Devices the crew may SSH to over the API (#3470): a repository admin lists
3 * one with the repo secret holding its key, a site admin grants it (pinning
4 * the host key), an admin over the repository reads the sessions. The rules
5 * live in `actions/crew_devices.ts`.
6 */
7
8 import {
9 addCrewDevice,
10 devicesView,
11 grantCrewDevice,
12 removeCrewDevice,
13 } from "../../actions/crew_devices.ts";
14 import { loadRepo } from "../api.ts";
15 import type { Handler } from "../context.ts";
16 import { body, json, notFound, requireScope, respondAccess, str } from "../respond.ts";
17 import type { Router } from "../router.ts";
18
19 export function crewDeviceRoutes(router: Router<Handler>): void {
20 router.add("GET", "/api/v1/repos/:owner/:name/crew-devices", (ctx) => {
21 const denied = requireScope(ctx, "admin");
22 if (denied) return denied;
23 const repo = loadRepo(ctx);
24 if (!repo) return notFound();
25 const view = devicesView(ctx.app, ctx.auth.user, repo);
26 if (!view.ok) return respondAccess(view.error, 422);
27 return json({ items: view.value.devices, sessions: view.value.sessions, next_cursor: null });
28 });
29 router.add("POST", "/api/v1/repos/:owner/:name/crew-devices", async (ctx) => {
30 const denied = requireScope(ctx, "admin");
31 if (denied) return denied;
32 const repo = loadRepo(ctx);
33 if (!repo) return notFound();
34 const input = await body(ctx.request);
35 const added = addCrewDevice(ctx.app, ctx.auth.user, repo, str(input.device), str(input.secret));
36 if (!added.ok) return respondAccess(added.error, 422);
37 return json(added.value, 201);
38 });
39 router.add("POST", "/api/v1/repos/:owner/:name/crew-devices/grant", async (ctx) => {
40 const denied = requireScope(ctx, "admin");
41 if (denied) return denied;
42 const repo = loadRepo(ctx);
43 if (!repo) return notFound();
44 const input = await body(ctx.request);
45 const granted = await grantCrewDevice(
46 ctx.app,
47 ctx.auth.user,
48 repo,
49 str(input.device),
50 str(input.host_key),
51 );
52 if (!granted.ok) return respondAccess(granted.error, 422);
53 return json(granted.value, 200);
54 });
55 router.add("DELETE", "/api/v1/repos/:owner/:name/crew-devices", async (ctx) => {
56 const denied = requireScope(ctx, "admin");
57 if (denied) return denied;
58 const repo = loadRepo(ctx);
59 if (!repo) return notFound();
60 const input = await body(ctx.request);
61 const removed = removeCrewDevice(ctx.app, ctx.auth.user, repo, str(input.device));
62 if (!removed.ok) return respondAccess(removed.error, 422);
63 return json({}, 200);
64 });
65 }
src/http/server.ts +5
@@ -530,6 +530,7 @@ import {
530530 promptSourceRun,
531531 promptsSettingsPage,
532532 } from "../web/pages/prompts.ts";
533 import { crewDeviceAdd, crewDeviceGrant, crewDeviceRemove, crewDevicesPage } from "../web/pages/crew_devices.ts";
533534 import {
534535 labelCreate,
535536 labelDelete,
@@ -1916,6 +1917,10 @@ export function buildRouter(): Router<Handler> {
19161917 );
19171918 for (const how of ["allow", "ignore"] as const)
19181919 router.add("POST", `/:owner/:name/settings/app/blocked/:destination/${how}`, appBlocked(how));
1920 router.add("GET", "/:owner/:name/settings/devices", crewDevicesPage);
1921 router.add("POST", "/:owner/:name/settings/devices", crewDeviceAdd);
1922 router.add("POST", "/:owner/:name/settings/devices/:entry/grant", crewDeviceGrant);
1923 router.add("POST", "/:owner/:name/settings/devices/:entry/delete", crewDeviceRemove);
19191924 router.add("GET", "/:owner/:name/settings/prompts", promptsSettingsPage);
19201925 router.add("POST", "/:owner/:name/settings/prompts", promptSourceAdd);
19211926 router.add("POST", "/:owner/:name/settings/prompts/:id/run", promptSourceRun);
src/tui/screens/crewdevices.ts added +184
@@ -0,0 +1,184 @@
1 /**
2 * Devices the crew may SSH to, in the terminal (#3470): the settings page's
3 * block (`web/pages/crew_devices.ts`) from the same actions
4 * (`actions/crew_devices.ts`), gated the same way. A repository's admin sees
5 * the devices and the sessions and may list (`a`) and unlist (`x`) one; only a
6 * site admin may grant (`g`), pinning the host key the device shows; anyone
7 * else sees nothing. `s` flips between the devices and the sessions the crew
8 * made. Each write is an event on the bus, so the open settings page redraws
9 * and this screen follows a write made there.
10 */
11
12 import {
13 addCrewDevice,
14 devicesView,
15 grantCrewDevice,
16 removeCrewDevice,
17 type DeviceRow,
18 type DeviceSession,
19 } from "../../actions/crew_devices.ts";
20 import { canAdmin, type Repo } from "../../core/repos.ts";
21 import type { Ctx, Screen } from "../app/app.ts";
22 import { binding } from "../app/keys.ts";
23 import type { Command } from "../app/palette.ts";
24 import type { Session } from "../session.ts";
25 import { style } from "../term/style.ts";
26 import { truncate } from "../term/width.ts";
27 import { fill, len, split } from "../ui/layout.ts";
28 import { ListState, confirmScreen, drawList, later, live, promptScreen, runAsync, type ListRow } from "./common.ts";
29
30 const ERRORS: Record<string, string> = {
31 not_found: "An admin of this repository manages devices.",
32 forbidden: "Only a site admin grants a device.",
33 invalid: "That is not a device: user@host:port with an IPv4 address, and a usable secret name.",
34 no_host_key: "The device showed no host key; paste one.",
35 no_such_device: "No such device.",
36 };
37
38 /** The gate: an admin of the repository who is a person, not an agent. */
39 export const mayManageDevices = (f: Session, repo: Repo): boolean =>
40 f.user !== undefined && f.user.kind !== "agent" && canAdmin(f.db, repo, f.user);
41
42 export function crewDevicesScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
43 const state = new ListState();
44 const where = `${repo.ownerName}/${repo.name}`;
45 let showSessions = false;
46 const view = () => {
47 const v = devicesView(f.app, f.user, repo);
48 return v.ok ? v.value : { devices: [] as DeviceRow[], sessions: [] as DeviceSession[], canGrant: false };
49 };
50 const rows = (): ListRow[] => {
51 const v = view();
52 if (showSessions)
53 return v.sessions.map((s) => ({
54 title: `${s.device} · ${s.by}`,
55 note: truncate(s.command, 100),
56 meta: `${s.at.slice(0, 16).replace("T", " ")} · run ${s.run}`,
57 }));
58 return v.devices.map((d) => ({
59 title: d.entry,
60 note: `key: secret ${d.secret}`,
61 meta: d.granted ? `granted by ${d.grantedBy ?? "someone"}` : "listed, not granted",
62 }));
63 };
64 const said = (result: { ok: boolean; error?: string }, ok: string): void => {
65 ctx.toast(result.ok ? ok : (ERRORS[result.error ?? ""] ?? "That could not be done."), result.ok ? "success" : "danger");
66 ctx.invalidate();
67 };
68 const screen: Screen = {
69 title: `${where} — Devices`,
70 get keys() {
71 const may = mayManageDevices(f, repo);
72 return [
73 binding(["j", "k"], "move cursor"),
74 binding(["s"], showSessions ? "devices" : "sessions"),
75 ...(may ? [binding(["a"], "list a device"), binding(["x"], "unlist")] : []),
76 ...(may && view().canGrant ? [binding(["g"], "grant")] : []),
77 ];
78 },
79 async load(signal) {
80 live(f, signal, { repoId: repo.id, where: (e) => e.kind.startsWith("crew.device.") }, () => ctx.invalidate());
81 },
82 render(area, s) {
83 const c = ctx.theme.c;
84 const may = mayManageDevices(f, repo);
85 const v = view();
86 const [head, list] = split(area, "v", [len(1), fill(1)]);
87 const note = !may
88 ? "An admin of this repository manages devices."
89 : showSessions
90 ? "ssh sessions the crew reported: their own note, not an audit. s shows the devices."
91 : v.canGrant
92 ? "Devices a run may ssh to. a lists one, g grants it, x unlists."
93 : "Devices a run may reach. a lists one, x unlists. Only a site admin grants.";
94 s.text(head!.x, head!.y, truncate(note, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
95 drawList(s, list!, c, state, rows());
96 },
97 key(e) {
98 const all = view();
99 const count = showSessions ? all.sessions.length : all.devices.length;
100 if (e.ctrl || e.alt) return false;
101 if (e.key !== "s" && e.key !== "a" && e.key !== "x" && e.key !== "g") return state.key(e, count);
102 if (e.key === "s") {
103 showSessions = !showSessions;
104 state.clamp(showSessions ? all.sessions.length : all.devices.length);
105 ctx.invalidate();
106 return true;
107 }
108 if (!mayManageDevices(f, repo)) {
109 ctx.toast(ERRORS["not_found"]!, "danger");
110 return true;
111 }
112 if (e.key === "a") {
113 void later(ctx, () =>
114 promptScreen(ctx, screen, {
115 title: "List a device",
116 label: "user@host:port",
117 placeholder: "[email protected]:22",
118 onSubmit: (device) =>
119 later(ctx, () =>
120 promptScreen(ctx, screen, {
121 title: "The key's secret",
122 label: "repository secret holding the private key",
123 placeholder: "ARM_PI_SSH_KEY",
124 onSubmit: (secret) => {
125 said(addCrewDevice(f.app, f.user, repo, device, secret), `${device} is listed; it waits for a grant.`);
126 return undefined;
127 },
128 }),
129 ),
130 }),
131 );
132 return true;
133 }
134 const at = showSessions ? undefined : all.devices[state.index];
135 if (at === undefined) return true;
136 if (e.key === "g") {
137 if (!all.canGrant) {
138 ctx.toast(ERRORS["forbidden"]!, "danger");
139 return true;
140 }
141 void later(ctx, () =>
142 promptScreen(ctx, screen, {
143 title: `Grant ${at.entry}`,
144 label: "host key to pin (empty: read what the device shows now)",
145 hint: "A grant lets runs of this repository reach it.",
146 onSubmit: (key) => {
147 runAsync(ctx, async () => {
148 said(await grantCrewDevice(f.app, f.user, repo, at.entry, key), `${at.entry} is granted.`);
149 });
150 return undefined;
151 },
152 }),
153 );
154 return true;
155 }
156 void later(ctx, () =>
157 confirmScreen(ctx, screen, {
158 title: "Unlist device",
159 body: [`${at.entry} is no longer reachable by runs; its grant goes with it.`],
160 actions: [{ label: "Cancel", variant: "ghost" }, { label: "Unlist" }],
161 selected: 0,
162 onChoose: (i) => {
163 if (i === 1) said(removeCrewDevice(f.app, f.user, repo, at.entry), `${at.entry} is unlisted.`);
164 },
165 }),
166 );
167 return true;
168 },
169 };
170 return screen;
171 }
172
173 /** The palette's command while a repository the viewer administers is open. */
174 export function crewDevicesCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
175 if (repo === undefined || !mayManageDevices(f, repo)) return [];
176 return [
177 {
178 id: "crew-devices",
179 title: `${repo.ownerName}/${repo.name} — Devices`,
180 hint: "devices the crew may ssh to: list, grant, unlist, sessions",
181 run: () => ctx.push(crewDevicesScreen(f, ctx, repo)),
182 },
183 ];
184 }
src/tui/screens/workspace.ts +2
@@ -214,6 +214,7 @@ import { trafficCommands } from "./trafficview.ts";
214214 import { chaptersCommands } from "./chapters.ts";
215215 import { cutOverCommands } from "./cutover.ts";
216216 import { outsideAgentsCommands } from "./outsideagents.ts";
217 import { crewDevicesCommands } from "./crewdevices.ts";
217218 import { crewSwitchCommands } from "./crewswitch.ts";
218219 import { walletCapCommands } from "./wallet.ts";
219220 import { allocationCommands } from "./allocation.ts";
@@ -2449,6 +2450,7 @@ export function workspaceScreen(
24492450 ...recheckWindowCommands(f, ctx, repo, () => screen),
24502451 ...deskCommands(f, ctx, repo),
24512452 ...outsideAgentsCommands(f, ctx, repo),
2453 ...crewDevicesCommands(f, ctx, repo),
24522454 ...cutOverCommands(f, ctx, repo),
24532455 ...crewSwitchCommands(f, ctx, repo),
24542456 ...walletCapCommands(f, ctx, repo),
src/web/pages/crew_devices.ts added +164
@@ -0,0 +1,164 @@
1 /**
2 * Settings › Devices, admin-only (#3470): the devices the crew may SSH to, the
3 * sessions it made on them, and the forms that list, grant and unlist one, from
4 * the same actions as the API and the terminal (`actions/crew_devices.ts`).
5 * Granting is a site admin's; a repository admin sees the grant as waiting.
6 * The block follows events from any door without a reload.
7 */
8
9 import {
10 addCrewDevice,
11 devicesView,
12 grantCrewDevice,
13 removeCrewDevice,
14 type DeviceRow,
15 type DeviceSession,
16 } from "../../actions/crew_devices.ts";
17 import { timePhase } from "../../core/route_timing.ts";
18 import type { Ctx } from "../../http/context.ts";
19 import { adminForm } from "../admin_form.ts";
20 import { repoBase, repoNotFound } from "../chrome.ts";
21 import { field } from "../form.ts";
22 import { html, type Html } from "../html.ts";
23 import { icon } from "../icons.ts";
24 import { flashTo } from "../layout.ts";
25 import { badge, btn, confirmAction, field as formField, row, rowList, time } from "../ui.ts";
26 import { settingsPageResponse, timedAdminRepo } from "./settings.ts";
27
28 /**
29 * The block follows a device listed, granted or unlisted, and a session reported, from any door.
30 */
31 export const crewDevicesJs = /* js */ `
32 (function () {
33 if (!document.getElementById('crew-devices')) return;
34 var es = new EventSource(location.pathname.split('/').slice(0, 3).join('/') + '/stream');
35 function refresh() {
36 fetch(location.pathname).then(function (r) { return r.text(); }).then(function (t) {
37 var h = document.createElement('div');
38 h.innerHTML = t;
39 var mine = document.getElementById('crew-devices'), next = h.querySelector('#crew-devices');
40 if (mine && next && mine.innerHTML !== next.innerHTML) mine.replaceWith(next);
41 }).catch(function () {});
42 }
43 ['crew.device.listed', 'crew.device.granted', 'crew.device.removed', 'crew.device.session'].forEach(function (k) {
44 es.addEventListener(k, refresh);
45 });
46 })();
47 `;
48
49 const ERRORS: Record<string, string> = {
50 forbidden: "Only a site admin grants a device.",
51 invalid: "That is not a device: user@host:port with an IPv4 address, and a usable secret name.",
52 no_host_key: "The device showed no host key. Paste one.",
53 no_such_device: "No such device.",
54 };
55
56 function devicesBlock(
57 base: string,
58 v: { devices: DeviceRow[]; sessions: DeviceSession[]; canGrant: boolean },
59 ): Html {
60 const at = (entry: string) => `${base}/settings/devices/${encodeURIComponent(entry)}`;
61 const rows = v.devices.map((d) =>
62 row({
63 lead: icon("key"),
64 title: html`<span class="mono">${d.entry}</span> ${d.granted ? badge("granted", { tone: "success" }) : badge("not granted", { tone: "attn" })}`,
65 meta: d.granted
66 ? html`Key is the secret <span class="mono">${d.secret}</span>. Granted by ${d.grantedBy ?? "someone"} ${d.grantedAt === null ? null : time(d.grantedAt)}.`
67 : html`Key is the secret <span class="mono">${d.secret}</span>. No run reaches it until it is granted. Only a site admin grants a device.`,
68 trail: html`<div class="row-fields">
69 ${v.canGrant && !d.granted
70 ? html`<form method="post" action="${at(d.entry)}/grant">
71 <input type="text" name="host_key" class="mono" placeholder="the device's key (empty: read it now)" autocomplete="off" />
72 ${btn("Grant", { size: "sm", variant: "outline" })}
73 </form>`
74 : null}
75 ${confirmAction({ action: `${at(d.entry)}/delete`, verb: "Unlist", size: "sm" })}
76 </div>`,
77 }),
78 );
79 const sessions = v.sessions.map((s) =>
80 row({
81 lead: icon("terminal"),
82 title: html`<span class="mono">${s.device}</span>`,
83 meta: html`${s.by} ${time(s.at)}: <span class="mono">${s.command}</span>`,
84 }),
85 );
86 return html`<section class="settings-block" id="crew-devices">
87 <h2>Devices the crew may reach</h2>
88 ${rows.length === 0
89 ? html`<p class="muted small">A run's shell reaches the forge and the registry only. List a device by its IPv4 address to change that.</p>`
90 : rowList(rows, { bare: true })}
91 <form class="mt" method="post" action="${base}/settings/devices">
92 ${formField({ label: "Device", name: "device", hint: "user@IPv4:port, exactly, like [email protected]:22", required: true, autocomplete: "off", mono: true })}
93 ${formField({ label: "Key's secret", name: "secret", hint: "The name of a secret set on this repository that holds the private key.", required: true, autocomplete: "off", mono: true })}
94 <div class="form-actions">${btn("List device", { variant: "primary", icon: "plus" })}</div>
95 </form>
96 ${sessions.length === 0
97 ? null
98 : html`<h3>Sessions the crew reported</h3>
99 <p class="muted small">The run's own note of each remote call: not an audit; the device's logs are.</p>
100 ${rowList(sessions, { bare: true })}`}
101 </section>`;
102 }
103
104 // GET /:owner/:name/settings/devices
105 export function crewDevicesPage(ctx: Ctx): Response {
106 const repo = timedAdminRepo(ctx);
107 if (!repo) return repoNotFound(ctx);
108 const v = timePhase(ctx.request, "devices", () => devicesView(ctx.app, ctx.auth.user, repo));
109 if (!v.ok) return repoNotFound(ctx);
110 return timePhase(ctx.request, "render", () =>
111 settingsPageResponse(ctx, repo, "devices", "Devices", devicesBlock(repoBase(repo), v.value)),
112 );
113 }
114
115 const back = (repoBaseUrl: string) => `${repoBaseUrl}/settings/devices`;
116
117 // POST /:owner/:name/settings/devices
118 export async function crewDeviceAdd(ctx: Ctx): Promise<Response> {
119 const gate = await adminForm(ctx);
120 if (gate instanceof Response) return gate;
121 const { repo, form } = gate;
122 const device = field(form, "device");
123 const added = addCrewDevice(ctx.app, ctx.auth.user, repo, device, field(form, "secret"));
124 if (!added.ok && added.error === "not_found") return repoNotFound(ctx);
125 return flashTo(
126 ctx,
127 back(repoBase(repo)),
128 added.ok
129 ? { message: `${added.value.entry} is listed. It waits for a site admin's grant.` }
130 : { tone: "danger", message: ERRORS[added.error] ?? "That could not be listed." },
131 );
132 }
133
134 // POST /:owner/:name/settings/devices/:entry/grant
135 export async function crewDeviceGrant(ctx: Ctx): Promise<Response> {
136 const gate = await adminForm(ctx);
137 if (gate instanceof Response) return gate;
138 const { repo, form } = gate;
139 const granted = await grantCrewDevice(ctx.app, ctx.auth.user, repo, ctx.params.entry ?? "", field(form, "host_key"));
140 if (!granted.ok && granted.error === "not_found") return repoNotFound(ctx);
141 return flashTo(
142 ctx,
143 back(repoBase(repo)),
144 granted.ok
145 ? { message: `${granted.value.entry} is granted; its host key is pinned.` }
146 : { tone: "danger", message: ERRORS[granted.error] ?? "That could not be granted." },
147 );
148 }
149
150 // POST /:owner/:name/settings/devices/:entry/delete
151 export async function crewDeviceRemove(ctx: Ctx): Promise<Response> {
152 const gate = await adminForm(ctx);
153 if (gate instanceof Response) return gate;
154 const { repo } = gate;
155 const removed = removeCrewDevice(ctx.app, ctx.auth.user, repo, ctx.params.entry ?? "");
156 if (!removed.ok && removed.error === "not_found") return repoNotFound(ctx);
157 return flashTo(
158 ctx,
159 back(repoBase(repo)),
160 removed.ok
161 ? { message: `${removed.value} is unlisted.` }
162 : { tone: "danger", message: ERRORS[removed.error] ?? "That could not be unlisted." },
163 );
164 }
src/web/pages/settings.ts +9 −1
@@ -126,6 +126,7 @@ import { emptyLine } from "../empty_words.ts";
126126 import { cutWaveFor } from "../../actions/cut_wave.ts";
127127 import { liveClientJs } from "../live.ts";
128128 import { outsideAgentsJs } from "./outside-agents-live.ts";
129 import { crewDevicesJs } from "./crew_devices.ts";
129130 import { proposalTokensSection } from "./proposal-tokens.ts";
130131 import { secretsSection } from "./secrets.ts";
131132 import { checkMemoryAt } from "../../apps/check-memory.ts";
@@ -137,6 +138,7 @@ type Section =
137138 | "general"
138139 | "app"
139140 | "prompts"
141 | "devices"
140142 | "labels"
141143 | "hooks"
142144 | "machines"
@@ -169,6 +171,12 @@ function sections(base: string, active: Section) {
169171 icon: "comment" as const,
170172 current: active === "prompts",
171173 },
174 {
175 label: "Devices",
176 href: `${base}/settings/devices`,
177 icon: "key" as const,
178 current: active === "devices",
179 },
172180 {
173181 label: "Labels",
174182 href: `${base}/settings/labels`,
@@ -213,7 +221,7 @@ export function settingsPageResponse(
213221 crumbs: crumbsFor(repo),
214222 palette: repoPalette(ctx, repo),
215223 ...(styleCss !== undefined ? { styleCss } : {}),
216 scriptJs: `${teamJs}\n${liveClientJs}\n${outsideAgentsJs}`,
224 scriptJs: `${teamJs}\n${liveClientJs}\n${outsideAgentsJs}\n${crewDevicesJs}`,
217225 body: html`${repoHeader(ctx, repo, "settings", { compact: true })}
218226 ${settingsLayout(sections(repoBase(repo), active), body)}`,
219227 },
test/crew-devices.test.ts added +433
@@ -0,0 +1,433 @@
1 /**
2 * Devices the crew may SSH to (#3470): a repository admin lists one, only a
3 * site admin grants it (pinning the host key), a run on that repository gets
4 * a key file, a pinned known_hosts and a logging `ssh`, exactly that
5 * host:port in its sandbox, and the key never reaches a log; an ungranted
6 * device is nowhere.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { chmodSync, existsSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
11 import { mkdtemp, rm, writeFile } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { createRepo } from "../src/actions/repos.ts";
16 import {
17 addCrewDevice,
18 devicesView,
19 grantCrewDevice,
20 removeCrewDevice,
21 } from "../src/actions/crew_devices.ts";
22 import { parseDevice } from "../src/core/crew_devices.ts";
23 import { setSecret } from "../src/core/secret_store.ts";
24 import { createToken } from "../src/core/tokens.ts";
25 import { createUser, type User } from "../src/core/users.ts";
26 import type { Repo } from "../src/core/repos.ts";
27 import { historyHolds, scrubTree } from "../src/crew/leak.ts";
28 import { runGit } from "../src/git/env.ts";
29 import { deviceKit, deviceLines, recordDeviceSessions } from "../src/crew/devices.ts";
30 import { systemPrompt, type BriefInput } from "../src/crew/brief.ts";
31 import { redactHeld } from "../src/kernel/log.ts";
32 import { serve, type Servers } from "../src/http/server.ts";
33 import { quietLogs } from "./helpers/globals.ts";
34 import { promote } from "./helpers/members.ts";
35
36 quietLogs();
37
38 const PI = "[email protected]:22";
39 const OTHER = "[email protected]:22";
40 const HOST_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFakeHostKeyFakeHostKeyFakeHostKey1234";
41 const DASHES = "-".repeat(5); // spelled apart so this file is not itself a key
42 const KEY = `${DASHES}BEGIN OPENSSH PRIVATE KEY${DASHES}\nsecretsecretsecretsecretsecret\n${DASHES}END OPENSSH PRIVATE KEY${DASHES}`;
43
44 let dataDir: string;
45 let app: App;
46 let servers: Servers;
47 let ada: User; // site admin
48 let cy: User; // owns the repository, no site admin
49 let bot: User; // an agent
50 let repo: Repo;
51 let cyToken = "";
52 let bobToken = "";
53
54 const scan = async () => HOST_KEY;
55 const run = () => ({ id: "run1", repoId: repo.id, actorId: bot.id });
56
57 beforeAll(async () => {
58 dataDir = await mkdtemp(join(tmpdir(), "forge-crew-devices-"));
59 app = createApp({ dataDir, port: 0, host: "forge.test" });
60 servers = await serve(app);
61 const make = async (username: string, extra: { adminIfFirst?: boolean } = {}) => {
62 const made = await createUser(app.db, {
63 origin: "seed",
64 trusted: true,
65 username,
66 email: `${username}@forge.local`,
67 password: "a-good-passphrase",
68 ...extra,
69 });
70 if (!made.ok) throw new Error(made.error);
71 return made.value;
72 };
73 ada = await make("ada", { adminIfFirst: true });
74 cy = await make("cy");
75 promote(app.db, cy);
76 const bob = await make("bob");
77 bot = await make("robin");
78 app.db.query("UPDATE user SET is_agent = 1 WHERE id = ?1").run(bot.id);
79 bot = { ...bot, kind: "agent" };
80 const made = await createRepo(app, cy, { name: "arm", visibility: "public", description: "" });
81 if (!made.ok) throw new Error(String(made.error));
82 repo = made.value;
83 cyToken = createToken(app.db, cy.id, "admin", "admin").token;
84 bobToken = createToken(app.db, bob.id, "admin", "admin").token;
85 }, 60_000);
86
87 afterAll(async () => {
88 await servers.stop();
89 await rm(dataDir, { recursive: true, force: true });
90 });
91
92 describe("a device is exact", () => {
93 test("user@host:port only: no range, wildcard, missing port or local address", () => {
94 expect(parseDevice(PI).ok).toBe(true);
95 for (const bad of ["100.89.95.68:22", "[email protected]/24:22", "crew@*.example.com:22", "crew@host", "-oProxy@host:22", "[email protected]:22", "[email protected]:22"])
96 expect(parseDevice(bad).ok).toBe(false);
97 });
98 });
99
100 describe("listing and granting", () => {
101 test("the owner lists, only a site admin grants, an agent does neither", () => {
102 expect(addCrewDevice(app, cy, repo, PI, "ARM_PI_SSH_KEY").ok).toBe(true);
103 expect(addCrewDevice(app, cy, repo, "[email protected]/8:22", "ARM_PI_SSH_KEY").ok).toBe(false);
104 expect(addCrewDevice(app, bot, repo, OTHER, "K").ok).toBe(false);
105 });
106
107 test("a grant needs a site admin and a host key, and pins the key", async () => {
108 const byOwner = await grantCrewDevice(app, cy, repo, PI, "", scan);
109 expect(byOwner.ok ? "" : byOwner.error).toBe("forbidden");
110 const unknown = await grantCrewDevice(app, ada, repo, OTHER, "", scan);
111 expect(unknown.ok ? "" : unknown.error).toBe("no_such_device");
112 const unreadable = await grantCrewDevice(app, ada, repo, PI, "", async () => undefined);
113 expect(unreadable.ok ? "" : unreadable.error).toBe("no_host_key");
114 const garbage = await grantCrewDevice(app, ada, repo, PI, "not a key", scan);
115 expect(garbage.ok ? "" : garbage.error).toBe("no_host_key");
116 const before = devicesView(app, ada, repo);
117 expect(before.ok && before.value.devices.map((d) => [d.entry, d.granted])).toEqual([[PI, false]]);
118 const granted = await grantCrewDevice(app, ada, repo, PI, "", scan);
119 expect(granted.ok && granted.value.hostKey).toBe(HOST_KEY);
120 expect(granted.ok && granted.value.grantedBy).toBe("ada");
121 });
122
123 test("the routes agree: a stranger is refused, the owner reads", async () => {
124 const url = `${servers.url}/api/v1/repos/cy/arm/crew-devices`;
125 const auth = (token: string) => ({ authorization: `Bearer ${token}` });
126 expect((await fetch(url, { headers: auth(bobToken) })).status).toBe(404);
127 const read = await fetch(url, { headers: auth(cyToken) });
128 expect(read.status).toBe(200);
129 const body = (await read.json()) as { items: { entry: string; granted: boolean }[] };
130 expect(body.items).toEqual([expect.objectContaining({ entry: PI, granted: true })]);
131 const grant = await fetch(`${url}/grant`, {
132 method: "POST",
133 headers: { ...auth(cyToken), "content-type": "application/json" },
134 body: JSON.stringify({ device: PI, host_key: HOST_KEY }),
135 });
136 expect(grant.status).toBe(403);
137 });
138
139 test("changing the key's secret drops the grant", () => {
140 addCrewDevice(app, cy, repo, PI, "OTHER_KEY");
141 const v = devicesView(app, cy, repo);
142 expect(v.ok && v.value.devices[0]?.granted).toBe(false);
143 });
144 });
145
146 describe("a run on the repository", () => {
147 let fakeSsh: string;
148 beforeAll(async () => {
149 await grantCrewDevice(app, ada, repo, PI, "", scan);
150 // Re-point the grant at the secret that exists.
151 addCrewDevice(app, cy, repo, PI, "ARM_PI_SSH_KEY");
152 await grantCrewDevice(app, ada, repo, PI, "", scan);
153 // A listed but ungranted device.
154 addCrewDevice(app, cy, repo, OTHER, "ARM_PI_SSH_KEY");
155 fakeSsh = join(dataDir, "fakessh");
156 writeFileSync(fakeSsh, '#!/bin/sh\necho "fake ssh: $*"\n');
157 chmodSync(fakeSsh, 0o755);
158 });
159
160 test("a granted device without a repository secret is not reachable", async () => {
161 setSecret(app.db, dataDir, "forge", "", "ARM_PI_SSH_KEY", KEY);
162 const tmp = await mkdtemp(join(tmpdir(), "forge-kit-"));
163 const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh, fakeSsh);
164 expect(kit?.hosts).toEqual([]);
165 expect(kit?.missing).toEqual([PI]);
166 kit?.release();
167 await rm(tmp, { recursive: true, force: true });
168 });
169
170 test("gets exactly the granted host:port, a 0600 key, a pinned host, and a logged ssh", async () => {
171 setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY);
172 const tmp = await mkdtemp(join(tmpdir(), "forge-kit-"));
173 const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh, fakeSsh)!;
174 expect(kit.hosts).toEqual(["100.89.95.68:22"]);
175 expect(Object.values(kit.aliases)).toEqual([PI]);
176 const root = join(tmp, "ssh");
177 const keyFile = join(root, `key-${Object.keys(kit.aliases)[0]}`);
178 expect(statSync(keyFile).mode & 0o777).toBe(0o600);
179 expect(readFileSync(keyFile, "utf8")).toContain("secretsecret");
180 expect(readFileSync(join(root, "known_hosts"), "utf8")).toBe(`100.89.95.68 ${HOST_KEY}\n`);
181 const config = readFileSync(join(root, "config"), "utf8");
182 expect(config).toContain("StrictHostKeyChecking yes");
183 expect(config).toContain("User crew");
184 expect(config).not.toContain("secretsecret");
185 expect(config).not.toContain("100.89.95.70");
186
187 const ssh = Bun.spawnSync([join(kit.binDir, "ssh"), "100", "uptime"], { stdout: "pipe", stderr: "ignore" });
188 const printed = ssh.stdout.toString();
189 expect(printed).toContain(`-F ${join(root, "config")} 100 uptime`);
190 expect(printed).not.toContain("secretsecret");
191 const sessions = kit.sessions().entries;
192 expect(sessions).toHaveLength(1);
193 expect(sessions[0]?.args).toBe("100 uptime");
194 // The key is redacted from any log line while the run holds it.
195 expect(redactHeld(`oops ${KEY}`)).not.toContain("secretsecret");
196
197 kit.release();
198 expect(existsSync(keyFile)).toBe(false);
199 await rm(tmp, { recursive: true, force: true });
200 });
201
202 test("the session note is read as hostile: a symlink yields nothing, a big log is capped, controls are stripped", async () => {
203 setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY);
204 const tmp = await mkdtemp(join(tmpdir(), "forge-kit-"));
205 const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh, fakeSsh)!;
206 const log = join(tmp, "ssh", "sessions.log");
207 writeFileSync(join(tmp, "target"), "now\tpi\tstolen secret\n");
208 rmSync(log);
209 symlinkSync(join(tmp, "target"), log);
210 expect(kit.sessions()).toEqual({ entries: [], dropped: 0 });
211 rmSync(log);
212 writeFileSync(log, "t\tpi\tline\u001b[31m\rforged\n".repeat(5000));
213 const big = kit.sessions();
214 expect(big.entries.length).toBe(50);
215 expect(big.dropped).toBeGreaterThan(0);
216 expect(big.entries[0]!.args).not.toMatch(/[\x00-\x1f]/);
217 kit.release();
218 await rm(tmp, { recursive: true, force: true });
219 });
220
221 test("the key is exposed to the push-time leak guard: a copy in the tree is scrubbed, in a commit refused", async () => {
222 setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY);
223 const tmp = await mkdtemp(join(tmpdir(), "forge-kit-"));
224 const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh, fakeSsh)!;
225 expect(kit.values.length).toBeGreaterThan(0);
226 const repoDir = await mkdtemp(join(tmpdir(), "forge-leak-"));
227 for (const args of [
228 ["init", "-q"],
229 ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "base"],
230 ])
231 await runGit(args, { cwd: repoDir });
232 await writeFile(join(repoDir, "deploy_key"), readFileSync(join(tmp, "ssh", `key-${Object.keys(kit.aliases)[0]}`)));
233 expect(await scrubTree(repoDir, kit.values, {})).toEqual(["deploy_key"]);
234 expect(readFileSync(join(repoDir, "deploy_key"), "utf8")).not.toContain("secretsecret");
235 await writeFile(join(repoDir, "again"), KEY);
236 await runGit(["add", "-A"], { cwd: repoDir });
237 await runGit(["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "oops"], { cwd: repoDir });
238 expect(await historyHolds(repoDir, "HEAD~1..HEAD", kit.values, {})).toBe(true);
239 kit.release();
240 await rm(tmp, { recursive: true, force: true });
241 await rm(repoDir, { recursive: true, force: true });
242 });
243
244 test("a revoked device gives the run nothing", async () => {
245 expect(removeCrewDevice(app, cy, repo, PI).ok).toBe(true);
246 const tmp = await mkdtemp(join(tmpdir(), "forge-kit-"));
247 expect(deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh, fakeSsh)).toBeUndefined();
248 await rm(tmp, { recursive: true, force: true });
249 });
250 });
251
252 describe("the brief", () => {
253 test("names the device and the rules; says nothing when there is none", () => {
254 const base = {
255 agent: { user: { username: "bot", displayName: "" }, brief: "" },
256 repo: { ownerName: "cy", name: "arm", defaultBranch: "main" },
257 issue: { number: 1 },
258 branch: "bot/1",
259 forgeUrl: "http://forge.test",
260 isApp: false,
261 };
262 const with_ = systemPrompt({ ...base, devices: { pi: PI } } as unknown as BriefInput);
263 expect(with_).toContain(`\`ssh pi\` is ${PI}`);
264 expect(with_).toContain("Never change the device's users, keys");
265 expect(systemPrompt(base as unknown as BriefInput)).not.toContain("over SSH");
266 expect(deviceLines({})).toEqual([]);
267 });
268 });
269
270 describe("a device is named by an IPv4 address, so a run never resolves a name", () => {
271 test("IPv6, mapped, bracketed and named hosts are refused at parse and at listing", () => {
272 for (const bad of [
273 "crew@::1:22",
274 "crew@[::1]:22",
275 "crew@fc00::1:22",
276 "crew@fe80::1:22",
277 "crew@::ffff:127.0.0.1:22",
278 "crew@[::ffff:127.0.0.1]:22",
279 "crew@localhost:22",
280 // A name an attacker may point at a v6 loopback after the grant.
281 "[email protected]:22",
282 ])
283 expect(parseDevice(bad).ok, bad).toBe(false);
284 expect(parseDevice(PI).ok).toBe(true);
285 const listed = addCrewDevice(app, cy, repo, "[email protected]:22", "ARM_PI_SSH_KEY");
286 expect(listed.ok).toBe(false);
287 const view = devicesView(app, cy, repo);
288 expect(view.ok && view.value.devices.map((d) => d.entry)).not.toContain("[email protected]:22");
289 });
290 });
291
292 describe("the host key", () => {
293 test("ed25519 is preferred over whatever order ssh-keyscan prints", async () => {
294 const { pickHostKey } = await import("../src/crew/hostkey.ts");
295 const rsa = `ssh-rsa ${"A".repeat(40)}`;
296 const ecdsa = `ecdsa-sha2-nistp256 ${"B".repeat(40)}`;
297 const out = `# 1.2.3.4:22 SSH-2.0\n1.2.3.4 ${rsa}\n1.2.3.4 ${ecdsa}\n1.2.3.4 ${HOST_KEY}\n`;
298 expect(pickHostKey(out)).toBe(HOST_KEY);
299 expect(pickHostKey(`1.2.3.4 ${rsa}\n1.2.3.4 ${ecdsa}\n`)).toBe(ecdsa);
300 expect(pickHostKey("# nothing\n")).toBeUndefined();
301 });
302 });
303
304 describe("the kit's wrapper and proxy", () => {
305 let fakeSsh: string;
306 beforeAll(() => {
307 fakeSsh = join(dataDir, "fakessh2");
308 writeFileSync(fakeSsh, '#!/bin/sh\necho "fake ssh: $*"\n');
309 chmodSync(fakeSsh, 0o755);
310 });
311 const granted = async () => {
312 expect(addCrewDevice(app, cy, repo, PI, "ARM_PI_SSH_KEY").ok).toBe(true);
313 expect((await grantCrewDevice(app, ada, repo, PI, "", scan)).ok).toBe(true);
314 setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY);
315 };
316
317 test("the run's own -o, -F and -J are refused, alone or bundled; a quoted command passes", async () => {
318 await granted();
319 const tmp = await mkdtemp(join(tmpdir(), "forge-kit-"));
320 const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh, fakeSsh)!;
321 const ssh = (...args: string[]) => Bun.spawnSync([join(kit.binDir, "ssh"), ...args], { stdout: "pipe", stderr: "pipe" });
322 for (const args of [
323 ["-o", "StrictHostKeyChecking=no", "pi"],
324 ["-oProxyCommand=sh", "pi"],
325 ["-F", "/dev/null", "pi"],
326 ["-J", "evil", "pi"],
327 ["-vo", "UserKnownHostsFile=/dev/null", "pi"],
328 ]) {
329 const r = ssh(...args);
330 expect(r.exitCode, args.join(" ")).toBe(2);
331 expect(r.stdout.toString()).toBe("");
332 }
333 const ok = ssh("-p", "22", "pi", "ls -o");
334 expect(ok.exitCode).toBe(0);
335 expect(ok.stdout.toString()).toContain("pi ls -o");
336 kit.release();
337 await rm(tmp, { recursive: true, force: true });
338 });
339
340 test("without nc the device is listed as missing and the sandbox is given nothing", async () => {
341 await granted();
342 const tmp = await mkdtemp(join(tmpdir(), "forge-kit-"));
343 const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh, null)!;
344 expect(kit.missing).toEqual([PI]);
345 expect(kit.hosts).toEqual([]);
346 kit.release();
347 await rm(tmp, { recursive: true, force: true });
348 });
349 });
350
351 describe("over HTTP, and from a run's end to the sandbox", () => {
352 let adaToken = "";
353 let botToken = "";
354 const url = () => `${servers.url}/api/v1/repos/cy/arm/crew-devices`;
355 const send = (method: string, token: string, path: string, body?: object) =>
356 fetch(`${url()}${path}`, {
357 method,
358 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
359 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
360 });
361 beforeAll(() => {
362 adaToken = createToken(app.db, ada.id, "admin", "admin").token;
363 botToken = createToken(app.db, bot.id, "admin", "admin").token;
364 removeCrewDevice(app, cy, repo, PI);
365 removeCrewDevice(app, cy, repo, OTHER);
366 });
367
368 test("an agent that administers a repository is refused every write with 403", async () => {
369 const own = await createRepo(app, cy, { name: "botrepo", visibility: "public", description: "" });
370 expect(own.ok).toBe(true);
371 app.db.query("UPDATE repo SET owner_id = ?1 WHERE name = 'botrepo'").run(bot.id);
372 const at = `${servers.url}/api/v1/repos/robin/botrepo/crew-devices`;
373 const call = (method: string, path: string, body: object) =>
374 fetch(`${at}${path}`, { method, headers: { authorization: `Bearer ${botToken}`, "content-type": "application/json" }, body: JSON.stringify(body) });
375 expect((await call("POST", "", { device: PI, secret: "K" })).status).toBe(403);
376 expect((await call("POST", "/grant", { device: PI, host_key: HOST_KEY })).status).toBe(403);
377 expect((await call("DELETE", "", { device: PI })).status).toBe(403);
378 });
379
380 test("add, grant and delete work for the right person, and a stranger gets 404", async () => {
381 expect((await send("POST", bobToken, "", { device: PI, secret: "ARM_PI_SSH_KEY" })).status).toBe(404);
382 const added = await send("POST", cyToken, "", { device: PI, secret: "ARM_PI_SSH_KEY" });
383 expect(added.status).toBe(201);
384 expect(await added.json()).toMatchObject({ entry: PI, granted: false });
385 expect((await send("POST", cyToken, "", { device: "[email protected]:22", secret: "K" })).status).toBe(422);
386 const granted = await send("POST", adaToken, "/grant", { device: PI, host_key: HOST_KEY });
387 expect(granted.status).toBe(200);
388 expect(await granted.json()).toMatchObject({ entry: PI, granted: true, hostKey: HOST_KEY });
389 expect((await send("DELETE", cyToken, "", { device: PI })).status).toBe(200);
390 expect((await send("DELETE", cyToken, "", { device: PI })).status).toBe(422);
391 const read = await send("GET", cyToken, "");
392 expect(((await read.json()) as { items: unknown[] }).items).toEqual([]);
393 });
394
395 test("a run's end records its ssh calls as events the owner reads and nobody else does", async () => {
396 const fakeSsh = join(dataDir, "fakessh3");
397 writeFileSync(fakeSsh, '#!/bin/sh\necho ok\n');
398 chmodSync(fakeSsh, 0o755);
399 await send("POST", cyToken, "", { device: PI, secret: "ARM_PI_SSH_KEY" });
400 await send("POST", adaToken, "/grant", { device: PI, host_key: HOST_KEY });
401 setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY);
402 const tmp = await mkdtemp(join(tmpdir(), "forge-kit-"));
403 const kit = deviceKit(app.db, dataDir, app.bus, run(), tmp, fakeSsh, fakeSsh)!;
404 Bun.spawnSync([join(kit.binDir, "ssh"), Object.keys(kit.aliases)[0]!, "uptime"]);
405 const written: string[] = [];
406 recordDeviceSessions(app.bus, kit, { id: "run1", repoId: repo.id }, bot.id, (l) => written.push(l));
407 expect(written).toHaveLength(1);
408
409 const read = await send("GET", cyToken, "");
410 const body = (await read.json()) as { sessions: { run: string; device: string; command: string; by: string }[] };
411 expect(body.sessions).toEqual([expect.objectContaining({ run: "run1", device: PI, command: expect.stringContaining("uptime"), by: "robin" })]);
412 expect((await send("GET", bobToken, "")).status).toBe(404);
413
414 // The sandbox is told exactly the granted host:port, and an ungranted device is nowhere.
415 addCrewDevice(app, cy, repo, OTHER, "ARM_PI_SSH_KEY");
416 const kit2 = deviceKit(app.db, dataDir, app.bus, run(), await mkdtemp(join(tmpdir(), "forge-kit-")), fakeSsh, fakeSsh)!;
417 const { sandboxPolicy } = await import("../src/crew/sandbox.ts");
418 const policy = sandboxPolicy({ dataDir, agentName: "robin", urls: [], extraHosts: kit2.hosts, runId: "run1", repoId: repo.id });
419 expect(policy.allowHosts).toContain("100.89.95.68:22");
420 expect(policy.allowHosts).not.toContain("100.89.95.70:22");
421 expect(sandboxPolicy({ dataDir, agentName: "robin", urls: [], runId: "run1" }).allowHosts).not.toContain("100.89.95.68:22");
422 kit.release();
423 kit2.release();
424 await rm(tmp, { recursive: true, force: true });
425 });
426
427 test("the runner wires the kit: hosts into the sandbox, keys into the held values, events at the end", () => {
428 const src = readFileSync(join(import.meta.dir, "../src/crew/runner.ts"), "utf8");
429 expect(src).toContain("...(devices?.hosts ?? [])");
430 expect(src).toMatch(/\.\.\.\(devices\?\.values \?\? \[\]\)\s*\]/);
431 expect(src).toContain("recordDeviceSessions(app.bus, devices,");
432 });
433 });
test/route-timing-coverage.test.ts +1
@@ -26,6 +26,7 @@ const UNTIMED: Record<string, string> = {
2626 "/api/v1/repos/:owner/:name/issues/:number/estimates": "an issue's base rate from one indexed read of its history; no page to phase",
2727 "/api/v1/templates": "the marked repositories, one indexed read; no page to phase",
2828 "/api/v1/repos/:owner/:name/drop": "an app's drop listing, one indexed read and a directory scan; no page to phase",
29 "/api/v1/repos/:owner/:name/crew-devices": "a repository admin's device list, one indexed read; no page to phase",
2930 "/metrics": "Prometheus text exposition, scraped by token; not a page read",
3031 };
3132
test/spawn-pipes.test.ts +1
@@ -25,6 +25,7 @@ const PIPING: Record<string, { sites: string[]; reason: string }> = {
2525 "src/blob/large.ts": { sites: ["stdout"], reason: "cat-file stdout is the blob, read to the end into the store; stderr is ignored" },
2626 "src/chaos/faults.ts": { sites: ["stdout"], reason: "stdout is read until the kill closes it, then cancelled; stderr is ignored" },
2727 "src/crew/claude.ts": { sites: ["stdout+stderr", "stdout"], reason: "session pumps stdout and stderr; --version awaits stdout, stderr ignored" },
28 "src/crew/hostkey.ts": { sites: ["stdout"], reason: "stdout is read to its end with Response.text() before the exit is awaited; stderr ignored" },
2829 "src/crew/claude_usage.ts": { sites: ["stdout"], reason: "/usage stdout awaited with the exit, under a kill timer; stderr ignored" },
2930 "src/crew/openai_runner.ts": { sites: ["stdout+stderr"], reason: "bash() reads stdout and stderr to the end alongside the exit, under a kill timer" },
3031 "src/crew/plan.ts": { sites: ["stdout"], reason: "stdout awaited with the exit; stderr ignored" },
test/spawn-sites.test.ts +2
@@ -45,6 +45,8 @@ const SITES: Record<string, string> = {
4545 "the agent binary from configuration with flags the runner fixes; the prompt (a person's issue text) is one argv element after its flag and the binary never hands it to a shell; `--version` probe is fixed",
4646 "src/crew/claude_usage.ts":
4747 "the agent binary from configuration with the fixed argv `-p /usage`; only the account's credential, in the environment, varies",
48 "src/crew/hostkey.ts":
49 "`ssh-keyscan` with a fixed flag list; the host and port are validated at grant and are separate argv elements",
4850 "src/crew/openai_runner.ts":
4951 "the Bash tool of the OpenAI-compatible runner: /bin/sh -c with the model's command, which is the point of the tool, run in the run's clone (under bwrap when the sandbox is enforced); no person's text reaches argv",
5052 "src/crew/plan.ts":
test/tui-crew-devices.test.ts added +154
@@ -0,0 +1,154 @@
1 /**
2 * Devices the crew may reach, in the terminal (#3470): the settings page's
3 * block from the same actions and gates. A repository admin lists and unlists
4 * and reads; only a site admin grants; a guest sees nothing. A write made
5 * here is an event the web page follows.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { addCrewDevice, devicesView } from "../src/actions/crew_devices.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { listEvents } from "../src/core/events.ts";
14 import { createRepo, type Repo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { crewDevicesCommands, crewDevicesScreen } from "../src/tui/screens/crewdevices.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { adminCookie } from "./helpers/admin.ts";
21 import { settleApp } from "./helpers/tui.ts";
22
23 const PI = "[email protected]:22";
24 const HOST_KEY = `ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFakeHostKeyFakeHostKeyFakeHostKey1234`;
25 let dir: string;
26 let app: App;
27 let servers: Servers;
28 let ada: User; // site admin, owns the repository
29 let cy: User; // administers it, no site admin
30 let bob: User; // a guest
31 let repo: Repo;
32 let adaCookie: string;
33
34 beforeAll(async () => {
35 dir = await mkdtemp(join(tmpdir(), "forge-devices-tui-"));
36 app = createApp({ dataDir: dir, port: 0 });
37 servers = await serve(app);
38 adaCookie = await adminCookie(app, { username: "ada", email: "[email protected]", password: "a-good-passphrase" });
39 const make = async (username: string) => {
40 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase" });
41 if (!made.ok) throw new Error(made.error);
42 return made.value;
43 };
44 ada = (await import("../src/core/users.ts")).getUserByName(app.db, "ada")!;
45 cy = await make("cy");
46 bob = await make("bob");
47 const r = await createRepo(app.db, app.reposRoot, { ownerId: cy.id, name: "arm", visibility: "public", description: "", defaultBranch: "main" });
48 if (!r.ok) throw new Error(r.error);
49 repo = r.value;
50 app.db.query("UPDATE repo SET owner_id = ?1 WHERE id = ?2").run(cy.id, repo.id);
51 });
52 afterAll(async () => {
53 await servers.stop();
54 app.close();
55 await rm(dir, { recursive: true, force: true });
56 });
57
58 const key = (k: string) => ({ type: "key" as const, key: k, ctrl: false, alt: false, shift: false });
59 function open(user: User) {
60 const { app: tui, session } = createForgeApp(
61 app,
62 { sshUsername: user.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
63 { terminal: headlessTerminal(140, 40), exitHooks: false },
64 );
65 tui.start();
66 tui.ctx.push(crewDevicesScreen(session, tui.ctx, repo));
67 return { tui, session };
68 }
69 const type = (tui: ReturnType<typeof open>["tui"], text: string) => {
70 for (const ch of text) tui.dispatch(key(ch));
71 };
72
73 test("a repository admin lists, reads and unlists, with no grant key; the web page follows", async () => {
74 const events: string[] = [];
75 const off = app.bus.subscribe((e) => {
76 if (e.repoId === repo.id) events.push(e.kind);
77 });
78 const { tui, session } = open(cy);
79 await settleApp(tui);
80 expect(tui.screen.toText()).toContain("a site admin grants");
81 expect(tui.screen.toText()).not.toContain("g grants");
82 tui.dispatch(key("a"));
83 await settleApp(tui);
84 type(tui, PI);
85 tui.dispatch(key("enter"));
86 await settleApp(tui);
87 type(tui, "ARM_PI_SSH_KEY");
88 tui.dispatch(key("enter"));
89 await settleApp(tui);
90 const v = devicesView(app, cy, repo);
91 expect(v.ok && v.value.devices.map((d) => [d.entry, d.granted])).toEqual([[PI, false]]);
92 expect(events).toContain("crew.device.listed");
93 expect(tui.screen.toText()).toContain(PI);
94 // The same row is on the web page.
95 expect(await (await fetch(`${servers.url}/cy/arm/settings/devices`, { headers: { cookie: adaCookie } })).text()).toContain("100.89.95.68:22");
96
97 // g does nothing for a repository admin who is no site admin.
98 tui.dispatch(key("g"));
99 await settleApp(tui);
100 expect(devicesView(app, cy, repo).ok && (devicesView(app, cy, repo) as { value: { devices: { granted: boolean }[] } }).value.devices[0]!.granted).toBe(false);
101 expect(events).not.toContain("crew.device.granted");
102 expect(crewDevicesCommands(session, tui.ctx, repo)).toHaveLength(1);
103
104 tui.dispatch(key("x"));
105 await settleApp(tui);
106 tui.dispatch(key("right"));
107 tui.dispatch(key("enter"));
108 await settleApp(tui);
109 expect(devicesView(app, cy, repo).ok && (devicesView(app, cy, repo) as { value: { devices: unknown[] } }).value.devices).toEqual([]);
110 expect(events).toContain("crew.device.removed");
111 off();
112 tui.stop?.();
113 });
114
115 test("a site admin grants from the terminal with a pasted host key, and it is an event", async () => {
116 addCrewDevice(app, cy, repo, PI, "ARM_PI_SSH_KEY");
117 const events: string[] = [];
118 const off = app.bus.subscribe((e) => events.push(e.kind));
119 const { tui } = open(ada);
120 await settleApp(tui);
121 expect(tui.screen.toText()).toContain("g grants");
122 tui.dispatch(key("g"));
123 await settleApp(tui);
124 tui.dispatch({ type: "paste", text: HOST_KEY });
125 tui.dispatch(key("enter"));
126 await settleApp(tui);
127 const v = devicesView(app, ada, repo);
128 expect(v.ok && v.value.devices[0]?.granted).toBe(true);
129 expect(events).toContain("crew.device.granted");
130 expect(listEvents(app.db, { repoId: repo.id, kind: "crew.device.granted" })).toHaveLength(1);
131 off();
132 tui.stop?.();
133 });
134
135 test("a guest sees nothing and writes nothing", async () => {
136 const { tui, session } = open(bob);
137 await settleApp(tui);
138 expect(crewDevicesCommands(session, tui.ctx, repo)).toEqual([]);
139 expect(tui.screen.toText()).toContain("An admin of this repository manages devices.");
140 expect(tui.screen.toText()).not.toContain(PI);
141 tui.dispatch(key("a"));
142 await settleApp(tui);
143 expect(tui.screen.toText()).not.toContain("List a device");
144 tui.stop?.();
145 });
146
147 test("the settings page is the same block: an admin reads it, a stranger gets 404", async () => {
148 const page = await fetch(`${servers.url}/cy/arm/settings/devices`, { headers: { cookie: adaCookie } });
149 expect(page.status).toBe(200);
150 const text = await page.text();
151 expect(text).toContain("Devices the crew may reach");
152 expect(text).toContain('id="crew-devices"');
153 expect((await fetch(`${servers.url}/cy/arm/settings/devices`)).status).toBe(404);
154 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs