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) #3492
torque/forge:torque/3470-crew-runs-can-ssh-to-a-device-the-reposi → main 5 commits fork 7 threads · 7 unresolved
Dockerfile +1 −1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | # nothing to install. |
| 8 | 8 | FROM oven/bun:1.3-debian |
| 9 | 9 | RUN apt-get update \ |
| 10 | && apt-get install -y --no-install-recommends git ca-certificates curl bubblewrap socat nodejs npm tini chromium fonts-liberation \ | |
| 10 | && apt-get install -y --no-install-recommends git ca-certificates curl bubblewrap socat openssh-client nodejs npm tini chromium fonts-liberation \ | |
| 11 | 11 | && rm -rf /var/lib/apt/lists/* \ |
| 12 | 12 | && npm install -g @anthropic-ai/claude-code \ |
| 13 | 13 | && npm cache clean --force |
README.md +28
| @@ -1164,6 +1164,34 @@ Crew shows **Unsandboxed** with it, and every agent run's page says | ||
| 1164 | 1164 | "Sandboxed" or "Unsandboxed" from what it was actually started with (runs |
| 1165 | 1165 | from before this record say nothing). |
| 1166 | 1166 | |
| 1167 | **Devices.** A crew run can SSH to a device its repository names — the arm's | |
| 1168 | Pi, say. On **Settings → Devices** a repository admin adds an exact | |
| 1169 | `user@host:port` (no ranges, no wildcards; the port is 22 when left off), a | |
| 1170 | short name (`pi`), and the name of the secret that holds its private key (a | |
| 1171 | secret on the repository, its organization or the forge, set under Secrets). | |
| 1172 | Only a forge admin grants it, and the grant pins the host key: pasted, or | |
| 1173 | read with `ssh-keyscan` from the forge when left empty. A run on that | |
| 1174 | repository then gets, in its own temp directory, the key (0600), a | |
| 1175 | known_hosts with the pinned key, and an SSH config with | |
| 1176 | `StrictHostKeyChecking yes`; `ssh pi` and `scp … pi:` work as they stand | |
| 1177 | (wrappers first on the run's PATH pass `-F` that config), and the sandbox is | |
| 1178 | widened by exactly that `host:port`, reached through its proxy | |
| 1179 | (`src/crew/device_proxy.ts` is the ProxyCommand). The key is never an | |
| 1180 | argument or in the environment, is redacted from the run log, and is | |
| 1181 | removed when the run ends, however it ends. Devices go only to a task a | |
| 1182 | writer of the repository opened. The grant's flash and the device's row show | |
| 1183 | the host key's `SHA256:` fingerprint, to compare with | |
| 1184 | `ssh-keyscan host | ssh-keygen -lf -`. The brief tells the run the rules | |
| 1185 | (read and test freely, restart only what sudo allows, never change the | |
| 1186 | device's users, keys or network), and the Devices page lists, newest first, | |
| 1187 | two kinds of row. A *command* is a shell command the run asked for that names | |
| 1188 | the device's alias or address, read from Claude Code's own stream, which the | |
| 1189 | agent cannot edit; a command that builds the name at run time | |
| 1190 | (`h=p; ssh ${h}i`) is not recognized. A *session opened* row is best-effort: | |
| 1191 | the ProxyCommand writes it to a file in the run's temp directory, which the | |
| 1192 | agent can write too, so it can drop or forge those rows. The image carries | |
| 1193 | `openssh-client` for `ssh` and `ssh-keyscan`. | |
| 1194 | ||
| 1167 | 1195 | `docs/APPS.md` is the contract: the vocabulary, and the rules that are |
| 1168 | 1196 | mechanical rather than advisory. |
| 1169 | 1197 |
src/actions/devices.ts added +161
| @@ -0,0 +1,161 @@ | ||
| 1 | /** | |
| 2 | * Devices the crew may reach, as people reach them (#3470). A repository's | |
| 3 | * admins name a device and the secret that holds its key; only a forge | |
| 4 | * admin grants one, and the grant pins the host key — pasted, or read with | |
| 5 | * `ssh-keyscan` from the forge at that moment. Everyone else is told | |
| 6 | * `not_found`. Every change leaves an event naming the device, never a key. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { | |
| 11 | addDevice, | |
| 12 | destination, | |
| 13 | deviceLog, | |
| 14 | getDevice, | |
| 15 | grantDevice, | |
| 16 | hostKeyFingerprint, | |
| 17 | listDevices, | |
| 18 | parseHostKey, | |
| 19 | removeDevice, | |
| 20 | revokeDevice, | |
| 21 | type Device, | |
| 22 | type DeviceError, | |
| 23 | type DeviceLogEntry, | |
| 24 | } from "../core/devices.ts"; | |
| 25 | import { canAdmin, type Repo } from "../core/repos.ts"; | |
| 26 | import type { User } from "../core/users.ts"; | |
| 27 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 28 | ||
| 29 | /** Reads a device's host key from where the forge stands. */ | |
| 30 | export type HostKeyScan = ( | |
| 31 | host: string, | |
| 32 | port: number, | |
| 33 | ) => Promise<Result<string, "scan_failed">>; | |
| 34 | ||
| 35 | /** | |
| 36 | * `ssh-keyscan -T 5 -p <port> -- <host>`: the host is a validated name or | |
| 37 | * address (`parseDeviceEntry`), never a flag, and never passes a shell. | |
| 38 | */ | |
| 39 | export const scanHostKey: HostKeyScan = async (host, port) => { | |
| 40 | const binary = Bun.which("ssh-keyscan"); | |
| 41 | if (binary === null) return err("scan_failed"); | |
| 42 | try { | |
| 43 | const proc = Bun.spawn([binary, "-T", "5", "-p", String(port), "--", host], { | |
| 44 | stdin: "ignore", | |
| 45 | stdout: "pipe", | |
| 46 | stderr: "ignore", | |
| 47 | }); | |
| 48 | const timer = setTimeout(() => proc.kill("SIGKILL"), 10_000); | |
| 49 | const [out] = await Promise.all([new Response(proc.stdout).text(), proc.exited]); | |
| 50 | clearTimeout(timer); | |
| 51 | const key = parseHostKey(out); | |
| 52 | return key.ok ? ok(key.value) : err("scan_failed"); | |
| 53 | } catch { | |
| 54 | return err("scan_failed"); | |
| 55 | } | |
| 56 | }; | |
| 57 | ||
| 58 | /** Who may see the devices and their log: the repository's admins and the forge's. */ | |
| 59 | const mayManage = (app: App, repo: Repo, actor: User | undefined): actor is User => | |
| 60 | actor !== undefined && (actor.isAdmin || canAdmin(app.db, repo, actor)); | |
| 61 | ||
| 62 | export function repoDevices( | |
| 63 | app: App, | |
| 64 | actor: User | undefined, | |
| 65 | repo: Repo, | |
| 66 | ): Result<{ devices: Device[]; log: DeviceLogEntry[] }, "not_found"> { | |
| 67 | if (!mayManage(app, repo, actor)) return err("not_found"); | |
| 68 | return ok({ | |
| 69 | devices: listDevices(app.db, repo.id), | |
| 70 | log: deviceLog(app.db, repo.id), | |
| 71 | }); | |
| 72 | } | |
| 73 | ||
| 74 | export function addRepoDevice( | |
| 75 | app: App, | |
| 76 | actor: User | undefined, | |
| 77 | repo: Repo, | |
| 78 | input: { alias: string; entry: string; secretName: string }, | |
| 79 | ): Result<Device, "not_found" | DeviceError> { | |
| 80 | if (!mayManage(app, repo, actor)) return err("not_found"); | |
| 81 | const added = addDevice(app.db, repo.id, input, actor.id); | |
| 82 | if (!added.ok) return added; | |
| 83 | app.bus.append({ | |
| 84 | kind: "device.added", | |
| 85 | repoId: repo.id, | |
| 86 | actorId: actor.id, | |
| 87 | payload: { | |
| 88 | alias: added.value.alias, | |
| 89 | destination: `${added.value.user}@${destination(added.value)}`, | |
| 90 | secret: added.value.secretName, | |
| 91 | }, | |
| 92 | }); | |
| 93 | return added; | |
| 94 | } | |
| 95 | ||
| 96 | export function removeRepoDevice( | |
| 97 | app: App, | |
| 98 | actor: User | undefined, | |
| 99 | repo: Repo, | |
| 100 | alias: string, | |
| 101 | ): Result<void, "not_found" | "no_such_device"> { | |
| 102 | if (!mayManage(app, repo, actor)) return err("not_found"); | |
| 103 | if (!removeDevice(app.db, repo.id, alias)) return err("no_such_device"); | |
| 104 | app.bus.append({ | |
| 105 | kind: "device.removed", | |
| 106 | repoId: repo.id, | |
| 107 | actorId: actor.id, | |
| 108 | payload: { alias }, | |
| 109 | }); | |
| 110 | return ok(); | |
| 111 | } | |
| 112 | ||
| 113 | export async function grantRepoDevice( | |
| 114 | app: App, | |
| 115 | actor: User | undefined, | |
| 116 | repo: Repo, | |
| 117 | alias: string, | |
| 118 | pastedKey: string, | |
| 119 | scan: HostKeyScan = scanHostKey, | |
| 120 | ): Promise<Result<Device, "not_found" | "scan_failed" | DeviceError>> { | |
| 121 | if (actor === undefined || !actor.isAdmin) return err("not_found"); | |
| 122 | const device = getDevice(app.db, repo.id, alias); | |
| 123 | if (device === undefined) return err("no_such_device"); | |
| 124 | let key = pastedKey.trim(); | |
| 125 | if (key === "") { | |
| 126 | const scanned = await scan(device.host, device.port); | |
| 127 | if (!scanned.ok) return scanned; | |
| 128 | key = scanned.value; | |
| 129 | } | |
| 130 | const granted = grantDevice(app.db, repo.id, alias, key, actor.id); | |
| 131 | if (!granted.ok) return granted; | |
| 132 | app.bus.append({ | |
| 133 | kind: "device.granted", | |
| 134 | repoId: repo.id, | |
| 135 | actorId: actor.id, | |
| 136 | payload: { | |
| 137 | alias, | |
| 138 | destination: `${device.user}@${destination(device)}`, | |
| 139 | hostKeyType: granted.value.hostKey?.split(" ")[0] ?? "", | |
| 140 | hostKeyFingerprint: hostKeyFingerprint(granted.value.hostKey ?? ""), | |
| 141 | }, | |
| 142 | }); | |
| 143 | return granted; | |
| 144 | } | |
| 145 | ||
| 146 | export function revokeRepoDevice( | |
| 147 | app: App, | |
| 148 | actor: User | undefined, | |
| 149 | repo: Repo, | |
| 150 | alias: string, | |
| 151 | ): Result<void, "not_found" | "no_such_device"> { | |
| 152 | if (actor === undefined || !actor.isAdmin) return err("not_found"); | |
| 153 | if (!revokeDevice(app.db, repo.id, alias)) return err("no_such_device"); | |
| 154 | app.bus.append({ | |
| 155 | kind: "device.revoked", | |
| 156 | repoId: repo.id, | |
| 157 | actorId: actor.id, | |
| 158 | payload: { alias }, | |
| 159 | }); | |
| 160 | return ok(); | |
| 161 | } |
src/core/devices.ts added +362
| @@ -0,0 +1,362 @@ | ||
| 1 | /** | |
| 2 | * Devices the crew may reach: a repository names `user@host:port` and the | |
| 3 | * secret that holds the key, and a forge admin grants each one (#3470). | |
| 4 | * Exact destinations only — no ranges, no wildcards — and a grant pins the | |
| 5 | * host key it was given, so a run that finds another key refuses to log in. | |
| 6 | * Adding is a repository admin's; granting is a site admin's, the same | |
| 7 | * two-step as a cloud credential. Changing a device means removing it and | |
| 8 | * adding it again, which drops its grant: a grant never outlives the | |
| 9 | * destination it was given for. | |
| 10 | * | |
| 11 | * Every SSH session a run opens is written to `device_log` (who, when, | |
| 12 | * what command), and the repository's admins read it on the Devices page. | |
| 13 | * | |
| 14 | * Plain data in, plain data out; the tables are made here, on first use, | |
| 15 | * like `run_secret`, because they are this module's alone. | |
| 16 | */ | |
| 17 | ||
| 18 | import type { Database } from "bun:sqlite"; | |
| 19 | import { isSecretName } from "./secret_store.ts"; | |
| 20 | import { id } from "../kernel/id.ts"; | |
| 21 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 22 | ||
| 23 | export interface Device { | |
| 24 | readonly id: string; | |
| 25 | readonly repoId: string; | |
| 26 | /** The `ssh <alias>` the run is handed. */ | |
| 27 | readonly alias: string; | |
| 28 | readonly user: string; | |
| 29 | readonly host: string; | |
| 30 | readonly port: number; | |
| 31 | /** The secret holding the private key, resolved repo → org → forge. */ | |
| 32 | readonly secretName: string; | |
| 33 | /** `type base64`, pinned at the grant; null until granted. */ | |
| 34 | readonly hostKey: string | null; | |
| 35 | readonly grantedBy: string | null; | |
| 36 | readonly grantedAt: string | null; | |
| 37 | readonly addedBy: string; | |
| 38 | readonly addedAt: string; | |
| 39 | } | |
| 40 | ||
| 41 | export interface DeviceLogEntry { | |
| 42 | readonly id: string; | |
| 43 | readonly runId: string; | |
| 44 | readonly actorId: string; | |
| 45 | readonly alias: string; | |
| 46 | readonly at: string; | |
| 47 | /** `command`: a shell command naming the device; `connect`: a session opened. */ | |
| 48 | readonly kind: "command" | "connect"; | |
| 49 | readonly detail: string; | |
| 50 | } | |
| 51 | ||
| 52 | export type DeviceError = | |
| 53 | | "invalid_entry" | |
| 54 | | "invalid_alias" | |
| 55 | | "invalid_secret" | |
| 56 | | "invalid_host_key" | |
| 57 | | "alias_taken" | |
| 58 | | "too_many" | |
| 59 | | "no_such_device"; | |
| 60 | ||
| 61 | const USER = /^[a-z_][a-z0-9_-]{0,31}$/; | |
| 62 | const ALIAS = /^[a-z][a-z0-9-]{0,30}$/; | |
| 63 | const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/; | |
| 64 | const HOSTNAME = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/; | |
| 65 | const KEY_TYPE = /^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)$/; | |
| 66 | const KEY_BODY = /^[A-Za-z0-9+/]{16,8192}={0,3}$/; | |
| 67 | export const MAX_DEVICES = 8; | |
| 68 | const MAX_DETAIL = 2000; | |
| 69 | ||
| 70 | /** | |
| 71 | * `user@host:port`, exactly: a lowercase login, an IPv4 address or a host | |
| 72 | * name, and a port (22 when left off). Anything else — a range, a | |
| 73 | * wildcard, an option smuggled into the host — is `invalid_entry`. | |
| 74 | */ | |
| 75 | export function parseDeviceEntry( | |
| 76 | text: string, | |
| 77 | ): Result<{ user: string; host: string; port: number }, "invalid_entry"> { | |
| 78 | const m = /^([^@\s]+)@([^:\s]+)(?::(\d{1,5}))?$/.exec(text.trim()); | |
| 79 | if (m === null) return err("invalid_entry"); | |
| 80 | const user = m[1]!; | |
| 81 | const host = m[2]!.toLowerCase(); | |
| 82 | const port = m[3] === undefined ? 22 : Number(m[3]); | |
| 83 | if (!USER.test(user)) return err("invalid_entry"); | |
| 84 | // A dotted quad is an address or nothing: 999.1.1.1 is not a host name. | |
| 85 | const dotted = /^[\d.]+$/.test(host); | |
| 86 | if (dotted ? !IPV4.test(host) : !HOSTNAME.test(host)) | |
| 87 | return err("invalid_entry"); | |
| 88 | if (!Number.isInteger(port) || port < 1 || port > 65535) | |
| 89 | return err("invalid_entry"); | |
| 90 | return ok({ user, host, port }); | |
| 91 | } | |
| 92 | ||
| 93 | /** The destination as the sandbox allows it: `host:port`. */ | |
| 94 | export const destination = (d: Pick<Device, "host" | "port">): string => | |
| 95 | `${d.host}:${d.port}`; | |
| 96 | ||
| 97 | /** | |
| 98 | * A host key as `type base64`, from what an admin pasted or `ssh-keyscan` | |
| 99 | * printed: a bare `type key`, or a known_hosts line (`host type key | |
| 100 | * [comment]`). Comment lines and blank lines are skipped; the first key | |
| 101 | * line wins, ed25519 preferred where there are several. | |
| 102 | */ | |
| 103 | export function parseHostKey(text: string): Result<string, "invalid_host_key"> { | |
| 104 | const keys: string[] = []; | |
| 105 | for (const raw of text.split(/\r?\n/)) { | |
| 106 | const line = raw.trim(); | |
| 107 | if (line === "" || line.startsWith("#")) continue; | |
| 108 | const parts = line.split(/\s+/); | |
| 109 | for (let i = 0; i + 1 < parts.length; i++) { | |
| 110 | if (KEY_TYPE.test(parts[i]!) && KEY_BODY.test(parts[i + 1]!)) { | |
| 111 | keys.push(`${parts[i]} ${parts[i + 1]}`); | |
| 112 | break; | |
| 113 | } | |
| 114 | } | |
| 115 | } | |
| 116 | const pick = keys.find((k) => k.startsWith("ssh-ed25519 ")) ?? keys[0]; | |
| 117 | return pick === undefined ? err("invalid_host_key") : ok(pick); | |
| 118 | } | |
| 119 | ||
| 120 | /** | |
| 121 | * A host key's fingerprint as `ssh-keygen -lf` prints it: `SHA256:` and | |
| 122 | * the unpadded base64 of the SHA-256 of the key's decoded blob — what an | |
| 123 | * admin compares with `ssh-keyscan host | ssh-keygen -lf -`. | |
| 124 | */ | |
| 125 | export function hostKeyFingerprint(hostKey: string): string { | |
| 126 | const body = hostKey.split(" ")[1] ?? ""; | |
| 127 | const digest = new Bun.CryptoHasher("sha256").update(Buffer.from(body, "base64")).digest("base64"); | |
| 128 | return `SHA256:${digest.replace(/=+$/, "")}`; | |
| 129 | } | |
| 130 | ||
| 131 | const made = new WeakSet<Database>(); | |
| 132 | function tables(db: Database): void { | |
| 133 | if (made.has(db)) return; | |
| 134 | db.run(`CREATE TABLE IF NOT EXISTS repo_device ( | |
| 135 | id TEXT PRIMARY KEY, | |
| 136 | repo_id TEXT NOT NULL, | |
| 137 | alias TEXT NOT NULL, | |
| 138 | user TEXT NOT NULL, | |
| 139 | host TEXT NOT NULL, | |
| 140 | port INTEGER NOT NULL, | |
| 141 | secret_name TEXT NOT NULL, | |
| 142 | host_key TEXT, | |
| 143 | granted_by TEXT, | |
| 144 | granted_at TEXT, | |
| 145 | added_by TEXT NOT NULL, | |
| 146 | added_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 147 | UNIQUE (repo_id, alias) | |
| 148 | )`); | |
| 149 | db.run(`CREATE TABLE IF NOT EXISTS device_log ( | |
| 150 | id TEXT PRIMARY KEY, | |
| 151 | repo_id TEXT NOT NULL, | |
| 152 | run_id TEXT NOT NULL, | |
| 153 | actor_id TEXT NOT NULL, | |
| 154 | alias TEXT NOT NULL, | |
| 155 | at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), | |
| 156 | kind TEXT NOT NULL, | |
| 157 | detail TEXT NOT NULL | |
| 158 | )`); | |
| 159 | db.run( | |
| 160 | "CREATE INDEX IF NOT EXISTS device_log_repo ON device_log (repo_id, id)", | |
| 161 | ); | |
| 162 | made.add(db); | |
| 163 | } | |
| 164 | ||
| 165 | interface Row { | |
| 166 | id: string; | |
| 167 | repo_id: string; | |
| 168 | alias: string; | |
| 169 | user: string; | |
| 170 | host: string; | |
| 171 | port: number; | |
| 172 | secret_name: string; | |
| 173 | host_key: string | null; | |
| 174 | granted_by: string | null; | |
| 175 | granted_at: string | null; | |
| 176 | added_by: string; | |
| 177 | added_at: string; | |
| 178 | } | |
| 179 | ||
| 180 | const toDevice = (r: Row): Device => ({ | |
| 181 | id: r.id, | |
| 182 | repoId: r.repo_id, | |
| 183 | alias: r.alias, | |
| 184 | user: r.user, | |
| 185 | host: r.host, | |
| 186 | port: r.port, | |
| 187 | secretName: r.secret_name, | |
| 188 | hostKey: r.host_key, | |
| 189 | grantedBy: r.granted_by, | |
| 190 | grantedAt: r.granted_at, | |
| 191 | addedBy: r.added_by, | |
| 192 | addedAt: r.added_at, | |
| 193 | }); | |
| 194 | ||
| 195 | export function listDevices(db: Database, repoId: string): Device[] { | |
| 196 | tables(db); | |
| 197 | return db | |
| 198 | .query<Row, [string]>( | |
| 199 | "SELECT * FROM repo_device WHERE repo_id = ?1 ORDER BY alias", | |
| 200 | ) | |
| 201 | .all(repoId) | |
| 202 | .map(toDevice); | |
| 203 | } | |
| 204 | ||
| 205 | /** The devices a run on this repository may reach: granted, key pinned. */ | |
| 206 | export function grantedDevices(db: Database, repoId: string): Device[] { | |
| 207 | return listDevices(db, repoId).filter( | |
| 208 | (d) => d.grantedAt !== null && d.hostKey !== null, | |
| 209 | ); | |
| 210 | } | |
| 211 | ||
| 212 | export function getDevice( | |
| 213 | db: Database, | |
| 214 | repoId: string, | |
| 215 | alias: string, | |
| 216 | ): Device | undefined { | |
| 217 | tables(db); | |
| 218 | const row = db | |
| 219 | .query<Row, [string, string]>( | |
| 220 | "SELECT * FROM repo_device WHERE repo_id = ?1 AND alias = ?2", | |
| 221 | ) | |
| 222 | .get(repoId, alias); | |
| 223 | return row === null ? undefined : toDevice(row); | |
| 224 | } | |
| 225 | ||
| 226 | export function addDevice( | |
| 227 | db: Database, | |
| 228 | repoId: string, | |
| 229 | input: { alias: string; entry: string; secretName: string }, | |
| 230 | actorId: string, | |
| 231 | ): Result<Device, DeviceError> { | |
| 232 | tables(db); | |
| 233 | const alias = input.alias.trim().toLowerCase(); | |
| 234 | if (!ALIAS.test(alias)) return err("invalid_alias"); | |
| 235 | const parsed = parseDeviceEntry(input.entry); | |
| 236 | if (!parsed.ok) return parsed; | |
| 237 | const secretName = input.secretName.trim(); | |
| 238 | if (!isSecretName(secretName)) return err("invalid_secret"); | |
| 239 | if (getDevice(db, repoId, alias) !== undefined) return err("alias_taken"); | |
| 240 | if (listDevices(db, repoId).length >= MAX_DEVICES) return err("too_many"); | |
| 241 | const deviceId = id(); | |
| 242 | db.query( | |
| 243 | `INSERT INTO repo_device (id, repo_id, alias, user, host, port, secret_name, added_by) | |
| 244 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`, | |
| 245 | ).run( | |
| 246 | deviceId, | |
| 247 | repoId, | |
| 248 | alias, | |
| 249 | parsed.value.user, | |
| 250 | parsed.value.host, | |
| 251 | parsed.value.port, | |
| 252 | secretName, | |
| 253 | actorId, | |
| 254 | ); | |
| 255 | return ok(getDevice(db, repoId, alias)!); | |
| 256 | } | |
| 257 | ||
| 258 | export function removeDevice(db: Database, repoId: string, alias: string): boolean { | |
| 259 | tables(db); | |
| 260 | return ( | |
| 261 | db | |
| 262 | .query("DELETE FROM repo_device WHERE repo_id = ?1 AND alias = ?2") | |
| 263 | .run(repoId, alias).changes > 0 | |
| 264 | ); | |
| 265 | } | |
| 266 | ||
| 267 | /** Grant a device with the host key it must present from now on. */ | |
| 268 | export function grantDevice( | |
| 269 | db: Database, | |
| 270 | repoId: string, | |
| 271 | alias: string, | |
| 272 | hostKey: string, | |
| 273 | adminId: string, | |
| 274 | ): Result<Device, DeviceError> { | |
| 275 | tables(db); | |
| 276 | const key = parseHostKey(hostKey); | |
| 277 | if (!key.ok) return key; | |
| 278 | const changed = db | |
| 279 | .query( | |
| 280 | `UPDATE repo_device SET host_key = ?3, granted_by = ?4, | |
| 281 | granted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') | |
| 282 | WHERE repo_id = ?1 AND alias = ?2`, | |
| 283 | ) | |
| 284 | .run(repoId, alias, key.value, adminId).changes; | |
| 285 | if (changed === 0) return err("no_such_device"); | |
| 286 | return ok(getDevice(db, repoId, alias)!); | |
| 287 | } | |
| 288 | ||
| 289 | export function revokeDevice(db: Database, repoId: string, alias: string): boolean { | |
| 290 | tables(db); | |
| 291 | return ( | |
| 292 | db | |
| 293 | .query( | |
| 294 | `UPDATE repo_device SET host_key = NULL, granted_by = NULL, granted_at = NULL | |
| 295 | WHERE repo_id = ?1 AND alias = ?2 AND granted_at IS NOT NULL`, | |
| 296 | ) | |
| 297 | .run(repoId, alias).changes > 0 | |
| 298 | ); | |
| 299 | } | |
| 300 | ||
| 301 | export function logDeviceUse( | |
| 302 | db: Database, | |
| 303 | entry: { | |
| 304 | repoId: string; | |
| 305 | runId: string; | |
| 306 | actorId: string; | |
| 307 | alias: string; | |
| 308 | kind: DeviceLogEntry["kind"]; | |
| 309 | detail: string; | |
| 310 | at?: string | undefined; | |
| 311 | }, | |
| 312 | ): void { | |
| 313 | tables(db); | |
| 314 | db.query( | |
| 315 | `INSERT INTO device_log (id, repo_id, run_id, actor_id, alias, at, kind, detail) | |
| 316 | VALUES (?1, ?2, ?3, ?4, ?5, COALESCE(?6, strftime('%Y-%m-%dT%H:%M:%fZ','now')), ?7, ?8)`, | |
| 317 | ).run( | |
| 318 | id(), | |
| 319 | entry.repoId, | |
| 320 | entry.runId, | |
| 321 | entry.actorId, | |
| 322 | entry.alias, | |
| 323 | entry.at ?? null, | |
| 324 | entry.kind, | |
| 325 | entry.detail.slice(0, MAX_DETAIL), | |
| 326 | ); | |
| 327 | } | |
| 328 | ||
| 329 | /** The newest uses first. */ | |
| 330 | export function deviceLog( | |
| 331 | db: Database, | |
| 332 | repoId: string, | |
| 333 | limit = 100, | |
| 334 | ): DeviceLogEntry[] { | |
| 335 | tables(db); | |
| 336 | return db | |
| 337 | .query< | |
| 338 | { | |
| 339 | id: string; | |
| 340 | run_id: string; | |
| 341 | actor_id: string; | |
| 342 | alias: string; | |
| 343 | at: string; | |
| 344 | kind: string; | |
| 345 | detail: string; | |
| 346 | }, | |
| 347 | [string, number] | |
| 348 | >( | |
| 349 | `SELECT id, run_id, actor_id, alias, at, kind, detail FROM device_log | |
| 350 | WHERE repo_id = ?1 ORDER BY id DESC LIMIT ?2`, | |
| 351 | ) | |
| 352 | .all(repoId, limit) | |
| 353 | .map((r) => ({ | |
| 354 | id: r.id, | |
| 355 | runId: r.run_id, | |
| 356 | actorId: r.actor_id, | |
| 357 | alias: r.alias, | |
| 358 | at: r.at, | |
| 359 | kind: r.kind === "connect" ? "connect" : "command", | |
| 360 | detail: r.detail, | |
| 361 | })); | |
| 362 | } |
src/core/event_audience.ts +2
| @@ -38,6 +38,8 @@ export function eventAudience(kind: string): EventAudience { | ||
| 38 | 38 | kind.startsWith("app.domain.") || |
| 39 | 39 | kind.startsWith("prompt.") || |
| 40 | 40 | kind.startsWith("secret.") || |
| 41 | // Which devices the crew may reach is configuration, like a webhook. | |
| 42 | kind.startsWith("device.") || | |
| 41 | 43 | // The forge's mail ceiling is its owner's to hear (`actions/mail.ts`). |
| 42 | 44 | kind.startsWith("mail.") || |
| 43 | 45 | // A restore drill's verdict is the forge owner's (`snapshot/service.ts`). |
src/crew/brief.ts +25
| @@ -13,6 +13,7 @@ import type { Comment, Issue } from "../core/issues.ts"; | ||
| 13 | 13 | import type { Pull } from "../core/pulls.ts"; |
| 14 | 14 | import { OUTSIDE_LABEL, OUTSIDE_TITLE, saysOutside } from "../core/reports.ts"; |
| 15 | 15 | import type { Repo } from "../core/repos.ts"; |
| 16 | import type { DeviceBrief } from "./devices.ts"; | |
| 16 | 17 | import { READER } from "./direct.ts"; |
| 17 | 18 | import { newsSince } from "./news.ts"; |
| 18 | 19 | import type { Reserve } from "./reserve.ts"; |
| @@ -51,6 +52,8 @@ export interface BriefInput { | ||
| 51 | 52 | * it writes obey the cells and the cells it does not touch stay decided. |
| 52 | 53 | */ |
| 53 | 54 | readonly policy?: PolicyBrief | undefined; |
| 55 | /** The devices this run can SSH to (`crew/devices.ts`). */ | |
| 56 | readonly devices?: readonly DeviceBrief[] | undefined; | |
| 54 | 57 | } |
| 55 | 58 | |
| 56 | 59 | export interface PolicyBrief { |
| @@ -71,6 +74,27 @@ export const SANDBOX_LINES = [ | ||
| 71 | 74 | "It cannot: reach any host but the forge and the package registry, write outside the clone and `$TMPDIR`, read the forge's data or the machine's, bind a unix socket, or signal a process started in an earlier command. Never leave the sandbox: it cannot be asked to. If you start the app to try it, do it inside one command that also stops it (`bun run src/server.ts & pid=$!; sleep 2; curl …; kill $pid`). Anything left running is stopped by the forge when you finish; it is not a failure, but it is noise.", |
| 72 | 75 | ]; |
| 73 | 76 | |
| 77 | /** | |
| 78 | * What a run is told about the devices it can reach, and the rules. Empty | |
| 79 | * when there are none, so a run without one reads nothing about SSH. | |
| 80 | */ | |
| 81 | export function deviceLines(devices: readonly DeviceBrief[]): string[] { | |
| 82 | if (devices.length === 0) return []; | |
| 83 | return [ | |
| 84 | "", | |
| 85 | "Devices you can reach over SSH (granted to this repository by its owner):", | |
| 86 | ...devices.map( | |
| 87 | (d) => | |
| 88 | `- \`ssh ${d.alias}\` — ${d.user}@${d.host}:${d.port}. \`ssh ${d.alias} 'command'\` runs one command; \`scp file ${d.alias}:path\` copies. The key and the pinned host key are already in place; this host:port is the only one beyond the forge your shell can reach.`, | |
| 89 | ), | |
| 90 | "The rules on a device:", | |
| 91 | "- Read and test freely: logs, files, the hardware, the services' status.", | |
| 92 | "- Restart only the services sudo allows you to (`sudo -n systemctl restart <service>`); never try to widen what sudo allows.", | |
| 93 | "- Never change the device's users, SSH keys, network or firewall, and never copy its key anywhere. If the host key changes, stop and say so — do not work around it.", | |
| 94 | "- Every command you run that names the device is logged on the repository for its owner.", | |
| 95 | ]; | |
| 96 | } | |
| 97 | ||
| 74 | 98 | /** |
| 75 | 99 | * A short name for the prompt an agent ran on: a hash of its brief, its |
| 76 | 100 | * role and the standing system-prompt text. Per-run facts (issue, branch) |
| @@ -154,6 +178,7 @@ export function systemPrompt(input: BriefInput): string { | ||
| 154 | 178 | lines.push( |
| 155 | 179 | "", |
| 156 | 180 | ...SANDBOX_LINES, |
| 181 | ...deviceLines(input.devices ?? []), | |
| 157 | 182 | "", |
| 158 | 183 | "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.", |
| 159 | 184 | "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/claude.ts +17
| @@ -46,6 +46,8 @@ export interface ClaudeInput { | ||
| 46 | 46 | * for this invocation, never deltas. |
| 47 | 47 | */ |
| 48 | 48 | readonly onUsage?: ((spent: Spent) => void) | undefined; |
| 49 | /** Each tool call as the agent asked for it, name and raw input. */ | |
| 50 | readonly onTool?: ((name: string, input: unknown) => void) | undefined; | |
| 49 | 51 | /** |
| 50 | 52 | * How long a session may stay silent after a result while its input is |
| 51 | 53 | * still open (a steer was pending) before it is closed and settled as |
| @@ -308,6 +310,7 @@ export async function runClaude(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 308 | 310 | if (type === "assistant") { |
| 309 | 311 | for (const text of assistantLines(e, workdir)) input.log(text); |
| 310 | 312 | const message = e["message"]; |
| 313 | if (input.onTool) toolCalls(e, input.onTool); | |
| 311 | 314 | if (input.onUsage && typeof message === "object" && message !== null) { |
| 312 | 315 | const m = message as Record<string, unknown>; |
| 313 | 316 | if (typeof m["usage"] === "object" && m["usage"] !== null) { |
| @@ -494,6 +497,20 @@ function assistantLines( | ||
| 494 | 497 | return out; |
| 495 | 498 | } |
| 496 | 499 | |
| 500 | /** Every tool call of an assistant turn, handed over as asked. */ | |
| 501 | function toolCalls( | |
| 502 | e: Record<string, unknown>, | |
| 503 | onTool: (name: string, input: unknown) => void, | |
| 504 | ): void { | |
| 505 | const message = e["message"]; | |
| 506 | if (typeof message !== "object" || message === null) return; | |
| 507 | const content = (message as Record<string, unknown>)["content"]; | |
| 508 | if (!Array.isArray(content)) return; | |
| 509 | for (const block of content as Record<string, unknown>[]) | |
| 510 | if (block["type"] === "tool_use") | |
| 511 | onTool(String(block["name"] ?? ""), block["input"]); | |
| 512 | } | |
| 513 | ||
| 497 | 514 | function describeTool( |
| 498 | 515 | name: string, |
| 499 | 516 | input: unknown, |
src/crew/device_proxy.ts added +129
| @@ -0,0 +1,129 @@ | ||
| 1 | /** | |
| 2 | * The `ProxyCommand` of a device's SSH config (#3470). Copied whole into a | |
| 3 | * run's own SSH directory and run by `ssh` as | |
| 4 | * | |
| 5 | * bun proxy.ts <sessions-log> <alias> <host> <port> | |
| 6 | * | |
| 7 | * with the destination written by the forge, never taken from `%h %p`: the | |
| 8 | * config can only open the device it was made for. Inside Claude Code's | |
| 9 | * sandbox the only way out is its HTTP proxy, so the tunnel is an HTTP | |
| 10 | * `CONNECT` through `HTTPS_PROXY` (credentials from the URL), which the | |
| 11 | * sandbox allows for exactly the granted `host:port`; with no proxy set (a | |
| 12 | * host that cannot sandbox) it is a plain TCP connection. A loopback | |
| 13 | * destination is always direct. Each connection appends one line to the | |
| 14 | * sessions log, which the forge reads into the repository's device log | |
| 15 | * when the run ends. | |
| 16 | * | |
| 17 | * Self-contained on purpose — it imports nothing from the forge, because | |
| 18 | * it runs from the run's temp directory, not from the forge's tree. | |
| 19 | */ | |
| 20 | ||
| 21 | import { appendFileSync } from "node:fs"; | |
| 22 | import { connect, type Socket } from "node:net"; | |
| 23 | ||
| 24 | const LOOPBACK = /^(127\.\d+\.\d+\.\d+|localhost|::1)$/; | |
Minor: a loopback destination always skips the proxy, which only serves the tests. Consider refusing loopback hosts in |
||
| 25 | ||
| 26 | /** The HTTP proxy the environment names, if any. */ | |
| 27 | export function proxyFrom( | |
| 28 | env: Record<string, string | undefined>, | |
| 29 | ): URL | undefined { | |
| 30 | for (const name of ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"]) { | |
| 31 | const value = env[name]; | |
| 32 | if (value === undefined || value === "") continue; | |
| 33 | try { | |
| 34 | const url = new URL(value); | |
| 35 | if (url.protocol === "http:") return url; | |
| 36 | } catch { | |
| 37 | // not a URL: try the next | |
| 38 | } | |
| 39 | } | |
| 40 | return undefined; | |
| 41 | } | |
| 42 | ||
| 43 | function open(host: string, port: number): Promise<Socket> { | |
| 44 | return new Promise((resolve, reject) => { | |
| 45 | const socket = connect({ host, port }); | |
| 46 | socket.once("connect", () => { | |
| 47 | socket.off("error", reject); | |
| 48 | resolve(socket); | |
| 49 | }); | |
| 50 | socket.once("error", reject); | |
| 51 | }); | |
| 52 | } | |
| 53 | ||
| 54 | /** | |
| 55 | * A socket to `host:port`, through the proxy when there is one. What the | |
| 56 | * proxy sent past its answer's headers is handed back as `head`, to be | |
| 57 | * written out before anything else the socket says. | |
| 58 | */ | |
| 59 | export async function tunnel( | |
| 60 | env: Record<string, string | undefined>, | |
| 61 | host: string, | |
| 62 | port: number, | |
| 63 | ): Promise<{ socket: Socket; head: Buffer }> { | |
| 64 | const proxy = LOOPBACK.test(host) ? undefined : proxyFrom(env); | |
| 65 | if (proxy === undefined) | |
| 66 | return { socket: await open(host, port), head: Buffer.alloc(0) }; | |
| 67 | const socket = await open(proxy.hostname, Number(proxy.port || 80)); | |
| 68 | const target = `${host.includes(":") ? `[${host}]` : host}:${port}`; | |
| 69 | const auth = | |
| 70 | proxy.username === "" | |
| 71 | ? "" | |
| 72 | : `Proxy-Authorization: Basic ${Buffer.from( | |
| 73 | `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`, | |
| 74 | ).toString("base64")}\r\n`; | |
| 75 | socket.write(`CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n${auth}\r\n`); | |
| 76 | return await new Promise((resolve, reject) => { | |
| 77 | let got = Buffer.alloc(0); | |
| 78 | const onData = (chunk: Buffer) => { | |
| 79 | got = Buffer.concat([got, chunk]); | |
| 80 | const end = got.indexOf("\r\n\r\n"); | |
| 81 | if (end === -1) { | |
| 82 | if (got.length > 16_384) fail(new Error("proxy answer too long")); | |
| 83 | return; | |
| 84 | } | |
| 85 | socket.off("data", onData); | |
| 86 | socket.off("error", fail); | |
| 87 | const status = /^HTTP\/1\.[01] (\d{3})/.exec(got.subarray(0, end).toString("latin1")); | |
| 88 | if (status?.[1] !== "200") { | |
| 89 | socket.destroy(); | |
| 90 | return reject( | |
| 91 | new Error(`the sandbox refused ${target} (${status?.[1] ?? "no answer"})`), | |
| 92 | ); | |
| 93 | } | |
| 94 | resolve({ socket, head: got.subarray(end + 4) }); | |
| 95 | }; | |
| 96 | const fail = (error: Error) => { | |
| 97 | socket.destroy(); | |
| 98 | reject(error); | |
| 99 | }; | |
| 100 | socket.on("data", onData); | |
| 101 | socket.once("error", fail); | |
| 102 | socket.once("end", () => fail(new Error("the proxy closed the connection"))); | |
| 103 | }); | |
| 104 | } | |
| 105 | ||
| 106 | if (import.meta.main) { | |
| 107 | const [log = "", alias = "", host = "", portText = ""] = process.argv.slice(2); | |
| 108 | const port = Number(portText); | |
| 109 | if (log === "" || alias === "" || host === "" || !Number.isInteger(port)) { | |
| 110 | process.stderr.write("usage: proxy.ts <log> <alias> <host> <port>\n"); | |
| 111 | process.exit(2); | |
| 112 | } | |
| 113 | try { | |
| 114 | appendFileSync(log, `${new Date().toISOString()}\tconnect\t${alias}\n`); | |
| 115 | } catch { | |
| 116 | // the log is the forge's record; a connection without it still opens | |
| 117 | } | |
| 118 | try { | |
| 119 | const { socket, head } = await tunnel(process.env, host, port); | |
| 120 | if (head.length > 0) process.stdout.write(head); | |
| 121 | socket.pipe(process.stdout); | |
| 122 | process.stdin.pipe(socket); | |
| 123 | socket.on("close", () => process.exit(0)); | |
| 124 | socket.on("error", () => process.exit(1)); | |
| 125 | } catch (error) { | |
| 126 | process.stderr.write(`${alias}: ${(error as Error).message}\n`); | |
| 127 | process.exit(1); | |
| 128 | } | |
| 129 | } |
src/crew/devices.ts added +269
| @@ -0,0 +1,269 @@ | ||
| 1 | /** | |
| 2 | * A run's way to the repository's granted devices (#3470). For each one | |
| 3 | * the forge writes, into the run's own temp directory (`crew/sandbox.ts` | |
| 4 | * `runTmpDir`, removed when the run ends): | |
| 5 | * | |
| 6 | * ssh/id_<alias> the private key from the named secret, 0600 | |
| 7 | * ssh/known_hosts the host key pinned at the grant | |
| 8 | * ssh/config Host <alias>: user, port, key, StrictHostKeyChecking | |
| 9 | * ssh/proxy.ts the ProxyCommand (`crew/device_proxy.ts`) | |
| 10 | * ssh/bin/ssh, scp `ssh -F ssh/config "$@"`, first on the run's PATH | |
| 11 | * | |
| 12 | * so `ssh <alias>` works as it stands, and the sandbox is widened by | |
| 13 | * exactly each `host:port`. The key goes to a file and nowhere else: never | |
| 14 | * an argument, never the environment; its text and every line of it are | |
| 15 | * held for redaction from the moment it is opened (`kernel/log.ts`), so a | |
| 16 | * `cat` of the key reaches the run log as `[redacted]`. | |
| 17 | * | |
| 18 | * `finish()` removes the whole `ssh/` directory itself, so the key goes | |
| 19 | * on every way a run ends — including the ones that return before the | |
| 20 | * sandbox (and the run's temp directory with it) is set up. | |
| 21 | * | |
| 22 | * What the crew did on a device is logged on the repository | |
| 23 | * (`core/devices.ts` `device_log`), in two kinds of row with different | |
| 24 | * strength: | |
| 25 | * | |
| 26 | * command every shell command of the run that names a device's alias or | |
| 27 | * address, as Claude Code asked for it — the forge reads the | |
| 28 | * stream and the agent cannot edit it. A command that builds the | |
| 29 | * name at run time (`h=p; ssh ${h}i`) is not recognized. | |
| 30 | * connect every connection the ProxyCommand opened, read from | |
| 31 | * `ssh/sessions.log` when the run ends. Best-effort: the file is | |
| 32 | * in the run's writable temp directory, so the agent can truncate | |
| 33 | * it or add lines to it. A hint, not a record. | |
| 34 | */ | |
| 35 | ||
| 36 | import type { Database } from "bun:sqlite"; | |
| 37 | import { | |
| 38 | chmodSync, | |
| 39 | copyFileSync, | |
| 40 | mkdirSync, | |
| 41 | readFileSync, | |
| 42 | rmSync, | |
| 43 | writeFileSync, | |
| 44 | } from "node:fs"; | |
| 45 | import { join } from "node:path"; | |
| 46 | import type { EventBus } from "../core/events.ts"; | |
| 47 | import { destination, grantedDevices, logDeviceUse, type Device } from "../core/devices.ts"; | |
| 48 | import { resolveScoped } from "../core/secret_store.ts"; | |
| 49 | import { holdValues, redactHeld, releaseValues } from "../kernel/log.ts"; | |
| 50 | ||
| 51 | /** What the brief tells the crew about one device. */ | |
| 52 | export interface DeviceBrief { | |
| 53 | readonly alias: string; | |
| 54 | readonly user: string; | |
| 55 | readonly host: string; | |
| 56 | readonly port: number; | |
| 57 | } | |
| 58 | ||
| 59 | export interface DeviceRun { | |
| 60 | /** The devices this run can reach, keys in place. */ | |
| 61 | readonly devices: readonly DeviceBrief[]; | |
| 62 | /** Granted, but the key's secret is set at no scope: not handed. */ | |
| 63 | readonly missing: readonly string[]; | |
| 64 | /** `host:port` for the sandbox, one per device handed. */ | |
| 65 | readonly hosts: readonly string[]; | |
| 66 | /** PATH with the wrappers first; empty when no device was handed. */ | |
| 67 | readonly env: Record<string, string>; | |
| 68 | /** The key texts, for the leak checks on what the run pushes. */ | |
| 69 | readonly values: readonly string[]; | |
| 70 | /** One tool call of the run: logged when it is a shell command naming a device. */ | |
| 71 | readonly watch: (tool: string, input: unknown) => void; | |
| 72 | /** Read the sessions file into the log, remove `ssh/`, forget the keys. Safe twice. */ | |
| 73 | readonly finish: () => void; | |
| 74 | } | |
| 75 | ||
| 76 | /** The pieces of a key worth redacting: the whole, and each body line. */ | |
| 77 | export function keyForms(key: string): string[] { | |
| 78 | const lines = key | |
| 79 | .split(/\r?\n/) | |
| 80 | .map((l) => l.trim()) | |
| 81 | .filter((l) => l.length >= 16 && !l.startsWith("-----")); | |
| 82 | return [key, key.trim(), ...lines]; | |
| 83 | } | |
| 84 | ||
| 85 | /** Single-quoted for `sh`: the paths are the forge's, but quoting costs nothing. */ | |
| 86 | const sq = (s: string): string => `'${s.replaceAll("'", `'\\''`)}'`; | |
| 87 | ||
| 88 | /** `[host]:port` unless the port is 22, as known_hosts keys a host. */ | |
| 89 | const knownHost = (d: Device): string => | |
| 90 | d.port === 22 ? d.host : `[${d.host}]:${d.port}`; | |
| 91 | ||
| 92 | /** The ssh config for the devices, every path absolute. */ | |
| 93 | export function sshConfig(dir: string, devices: readonly Device[]): string { | |
| 94 | const blocks = devices.map((d) => | |
| 95 | [ | |
| 96 | `Host ${d.alias}`, | |
| 97 | ` HostName ${d.host}`, | |
| 98 | ` Port ${d.port}`, | |
| 99 | ` User ${d.user}`, | |
| 100 | ` IdentityFile ${join(dir, `id_${d.alias}`)}`, | |
| 101 | " IdentitiesOnly yes", | |
| 102 | ` UserKnownHostsFile ${join(dir, "known_hosts")}`, | |
| 103 | " GlobalKnownHostsFile /dev/null", | |
| 104 | " StrictHostKeyChecking yes", | |
| 105 | " UpdateHostKeys no", | |
| 106 | " ForwardAgent no", | |
| 107 | " ForwardX11 no", | |
| 108 | " ControlMaster no", | |
| 109 | " ControlPath none", | |
| 110 | " BatchMode yes", | |
| 111 | // bun by its full path: ssh runs this with the user's shell, and the | |
| 112 | // forge knows exactly which bun it is. | |
| 113 | ` ProxyCommand ${process.execPath} ${join(dir, "proxy.ts")} ${join(dir, "sessions.log")} ${d.alias} ${d.host} ${d.port}`, | |
| 114 | ].join("\n"), | |
| 115 | ); | |
| 116 | // Anything else named on the command line gets no key and no way out. | |
| 117 | return `${blocks.join("\n\n")}\n\nHost *\n IdentitiesOnly yes\n IdentityFile none\n BatchMode yes\n`; | |
| 118 | } | |
| 119 | ||
| 120 | /** Whether a shell command names this device: its alias or its address, beside ssh/scp/sftp/rsync. */ | |
| 121 | export function namesDevice(command: string, d: DeviceBrief): boolean { | |
| 122 | if (!/(^|[^\w.-])(ssh|scp|sftp|rsync)(?![\w.-])/.test(command)) return false; | |
| 123 | const word = (w: string) => | |
| 124 | new RegExp(`(^|[\\s@'"])${w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?=[\\s:'"]|$)`).test(command); | |
| 125 | return word(d.alias) || word(d.host); | |
| 126 | } | |
| 127 | ||
| 128 | /** Everything under `ssh/`: the keys, known_hosts, the config, the proxy, the wrappers. */ | |
| 129 | function write( | |
| 130 | dir: string, | |
| 131 | bin: string, | |
| 132 | handed: readonly Device[], | |
| 133 | found: Record<string, { value: string } | undefined>, | |
| 134 | path: string, | |
| 135 | ): void { | |
| 136 | chmodSync(dir, 0o700); | |
| 137 | for (const d of handed) { | |
| 138 | const file = join(dir, `id_${d.alias}`); | |
| 139 | const value = found[d.secretName]!.value; | |
| 140 | writeFileSync(file, value.endsWith("\n") ? value : `${value}\n`, { mode: 0o600 }); | |
| 141 | chmodSync(file, 0o600); | |
| 142 | } | |
| 143 | writeFileSync( | |
| 144 | join(dir, "known_hosts"), | |
| 145 | handed.map((d) => `${knownHost(d)} ${d.hostKey}\n`).join(""), | |
| 146 | { mode: 0o600 }, | |
| 147 | ); | |
| 148 | writeFileSync(join(dir, "config"), sshConfig(dir, handed), { mode: 0o600 }); | |
| 149 | copyFileSync(join(import.meta.dir, "device_proxy.ts"), join(dir, "proxy.ts")); | |
| 150 | writeFileSync(join(dir, "sessions.log"), "", { mode: 0o600 }); | |
| 151 | const config = join(dir, "config"); | |
| 152 | for (const tool of ["ssh", "scp", "sftp"]) { | |
| 153 | const real = Bun.which(tool, { PATH: path }); | |
| 154 | writeFileSync( | |
| 155 | join(bin, tool), | |
| 156 | real === null | |
| 157 | ? `#!/bin/sh\necho "${tool} is not installed on this forge's machine" >&2\nexit 127\n` | |
| 158 | : `#!/bin/sh\nexec ${sq(real)} -F ${sq(config)} "$@"\n`, | |
| 159 | { mode: 0o700 }, | |
| 160 | ); | |
| 161 | } | |
| 162 | } | |
| 163 | ||
| 164 | const NONE: DeviceRun = { | |
| 165 | devices: [], | |
| 166 | missing: [], | |
| 167 | hosts: [], | |
| 168 | env: {}, | |
| 169 | values: [], | |
| 170 | watch: () => {}, | |
| 171 | finish: () => {}, | |
| 172 | }; | |
| 173 | ||
| 174 | export function prepareDevices(input: { | |
| 175 | db: Database; | |
| 176 | dataDir: string; | |
| 177 | bus: EventBus; | |
| 178 | run: { id: string; repoId: string; ownerId: string; actorId: string }; | |
| 179 | /** The run's own temp directory. */ | |
| 180 | tmpDir: string; | |
| 181 | /** The PATH the run would have had. */ | |
| 182 | path: string; | |
| 183 | }): DeviceRun { | |
| 184 | const granted = grantedDevices(input.db, input.run.repoId); | |
| 185 | if (granted.length === 0) return NONE; | |
| 186 | const found = resolveScoped( | |
| 187 | input.db, | |
| 188 | input.dataDir, | |
| 189 | input.bus, | |
| 190 | [...new Set(granted.map((d) => d.secretName))], | |
| 191 | { | |
| 192 | repo: input.run.repoId, | |
| 193 | org: input.run.ownerId, | |
| 194 | actor: input.run.actorId, | |
| 195 | run: input.run.id, | |
| 196 | }, | |
| 197 | ); | |
| 198 | const handed = granted.filter((d) => found[d.secretName] !== undefined); | |
| 199 | const missing = granted.filter((d) => found[d.secretName] === undefined).map((d) => d.alias); | |
| 200 | if (handed.length === 0) return { ...NONE, missing }; | |
| 201 | const values = [...new Set(handed.map((d) => found[d.secretName]!.value))]; | |
| 202 | const holdKey = `devices:${input.run.id}`; | |
| 203 | // Held before a byte is written: from here a key in any log line is redacted. | |
| 204 | holdValues(holdKey, values.flatMap(keyForms)); | |
| 205 | ||
| 206 | const dir = join(input.tmpDir, "ssh"); | |
| 207 | const bin = join(dir, "bin"); | |
| 208 | mkdirSync(bin, { recursive: true, mode: 0o700 }); | |
| 209 | const remove = () => rmSync(dir, { recursive: true, force: true }); | |
| 210 | try { | |
| 211 | write(dir, bin, handed, found, input.path); | |
| 212 | } catch (error) { | |
| 213 | // A half-written directory holds a key all the same. | |
| 214 | remove(); | |
| 215 | releaseValues(holdKey); | |
| 216 | throw error; | |
| 217 | } | |
| 218 | ||
| 219 | const devices: DeviceBrief[] = handed.map((d) => ({ | |
outdated
This file sits in the run's writable TMPDIR, so the agent can truncate it or forge lines in it. Either keep it out of the sandbox's write set, or document |
||
| 220 | alias: d.alias, | |
| 221 | user: d.user, | |
| 222 | host: d.host, | |
| 223 | port: d.port, | |
| 224 | })); | |
| 225 | const log = (alias: string, kind: "command" | "connect", detail: string, at?: string) => | |
| 226 | logDeviceUse(input.db, { | |
| 227 | repoId: input.run.repoId, | |
| 228 | runId: input.run.id, | |
| 229 | actorId: input.run.actorId, | |
| 230 | alias, | |
| 231 | kind, | |
| 232 | detail: redactHeld(detail), | |
| 233 | at, | |
| 234 | }); | |
| 235 | let finished = false; | |
| 236 | return { | |
| 237 | devices, | |
| 238 | missing, | |
| 239 | hosts: handed.map(destination), | |
| 240 | env: { PATH: `${bin}:${input.path}` }, | |
| 241 | values, | |
| 242 | watch: (tool, args) => { | |
| 243 | if (finished || tool !== "Bash") return; | |
| 244 | const command = | |
| 245 | typeof args === "object" && args !== null | |
| 246 | ? (args as Record<string, unknown>)["command"] | |
| 247 | : undefined; | |
| 248 | if (typeof command !== "string") return; | |
| 249 | for (const d of devices) if (namesDevice(command, d)) log(d.alias, "command", command); | |
| 250 | }, | |
| 251 | finish: () => { | |
| 252 | if (finished) return; | |
| 253 | finished = true; | |
| 254 | try { | |
| 255 | const known = new Set(devices.map((d) => d.alias)); | |
| 256 | for (const line of readFileSync(join(dir, "sessions.log"), "utf8").split("\n")) { | |
| 257 | const [at = "", kind = "", alias = ""] = line.split("\t"); | |
| 258 | if (kind !== "connect" || !known.has(alias)) continue; | |
| 259 | if (!/^\d{4}-\d\d-\d\dT[\d:.]+Z$/.test(at)) continue; | |
| 260 | log(alias, "connect", "session opened", at); | |
| 261 | } | |
| 262 | } catch { | |
| 263 | // the run's directory went first: the commands are logged already | |
| 264 | } | |
| 265 | remove(); | |
| 266 | releaseValues(holdKey); | |
| 267 | }, | |
| 268 | }; | |
| 269 | } |
src/crew/runner.ts +33 −2
| @@ -135,7 +135,8 @@ import { | ||
| 135 | 135 | type UsageOutcome, |
| 136 | 136 | } from "../core/usage.ts"; |
| 137 | 137 | import { trackAgentRun, untrackAgentRun } from "./running.ts"; |
| 138 | import { sandboxPolicy } from "./sandbox.ts"; | |
| 138 | import { runTmpDir, sandboxPolicy } from "./sandbox.ts"; | |
| 139 | import { keyForms, prepareDevices, type DeviceRun } from "./devices.ts"; | |
| 139 | 140 | import { grantSecrets, parseDeclaration, type Grant } from "./grant.ts"; |
| 140 | 141 | import { historyHolds, scrubTree } from "./leak.ts"; |
| 141 | 142 | import { workdirFor } from "./workdir.ts"; |
| @@ -832,6 +833,7 @@ async function work( | ||
| 832 | 833 | }; |
| 833 | 834 | |
| 834 | 835 | let grant: Grant | undefined; |
| 836 | let devices: DeviceRun | undefined; | |
| 835 | 837 | let runTmp: string | undefined; |
| 836 | 838 | let early: EarlyPull | undefined; |
| 837 | 839 | // A paused run resumes: its pull keeps saying "In progress". |
| @@ -869,6 +871,30 @@ async function work( | ||
| 869 | 871 | write(`secrets: holding ${grant.names.join(", ")} for this run`); |
| 870 | 872 | for (const name of grant.missing) write(`secret not set: ${name}`); |
| 871 | 873 | for (const host of grant.hosts) write(`egress: +${host} for this run`); |
| 874 | // The devices the repository's admins named and a site admin granted | |
| 875 | // (`crew/devices.ts`): keys into this run's temp directory, egress by | |
| 876 | // exactly their host:port. Only for a task a writer opened — the same | |
| 877 | // floor as a secret the issue declares. | |
| 878 | devices = | |
High: the key is written here, but |
||
| 879 | author !== undefined && canWrite(app.db, repo, author) | |
| 880 | ? prepareDevices({ | |
| 881 | db: app.db, | |
| 882 | dataDir: app.config.dataDir, | |
| 883 | bus: app.bus, | |
| 884 | run: { | |
| 885 | id: run.id, | |
| 886 | repoId: repo.id, | |
| 887 | ownerId: repo.ownerId, | |
| 888 | actorId: agent.user.id, | |
| 889 | }, | |
| 890 | tmpDir: runTmpDir(app.config.dataDir, agent.user.username, run.id), | |
| 891 | path: process.env["PATH"] ?? "/usr/local/bin:/usr/bin:/bin", | |
| 892 | }) | |
| 893 | : undefined; | |
| 894 | for (const d of devices?.devices ?? []) | |
| 895 | write(`device: ssh ${d.alias} (${d.user}@${d.host}:${d.port}) for this run`); | |
| 896 | for (const alias of devices?.missing ?? []) | |
| 897 | write(`device ${alias}: its key's secret is set nowhere; not handed`); | |
| 872 | 898 | const bare = repoDir(app.reposRoot, repo.ownerName, repo.name); |
| 873 | 899 | const forkBare = repoDir( |
| 874 | 900 | app.reposRoot, |
| @@ -919,6 +945,7 @@ async function work( | ||
| 919 | 945 | isApp: record !== undefined, |
| 920 | 946 | previewUrl, |
| 921 | 947 | policy, |
| 948 | devices: devices?.devices ?? [], | |
| 922 | 949 | // A review reads one head afresh: a resumed session would carry an |
| 923 | 950 | // older head's diff and preview into the verdict on this one. |
| 924 | 951 | resuming: |
| @@ -1141,6 +1168,7 @@ async function work( | ||
| 1141 | 1168 | ...passportEnv(app.config.dataDir), |
| 1142 | 1169 | ...credentialEnv(picked), |
| 1143 | 1170 | ...grant.env, |
| 1171 | ...devices?.env, | |
| 1144 | 1172 | ...(options.configDir === undefined |
| 1145 | 1173 | ? {} |
| 1146 | 1174 | : { CLAUDE_CONFIG_DIR: options.configDir }), |
| @@ -1163,6 +1191,7 @@ async function work( | ||
| 1163 | 1191 | extraHosts: [ |
| 1164 | 1192 | ...(options.allowHosts ?? []), |
| 1165 | 1193 | ...hosts, |
| 1194 | ...(devices?.hosts ?? []), | |
| 1166 | 1195 | ...(gatewayHost === undefined ? [] : [gatewayHost]), |
| 1167 | 1196 | ], |
| 1168 | 1197 | enforced: options.sandboxEnforced, |
| @@ -1206,6 +1235,7 @@ async function work( | ||
| 1206 | 1235 | log: write, |
| 1207 | 1236 | signal, |
| 1208 | 1237 | onSteer: (send) => steering.set(run.id, send), |
| 1238 | onTool: devices?.watch, | |
| 1209 | 1239 | onUsage: (so) => |
| 1210 | 1240 | meterLive( |
| 1211 | 1241 | app, |
| @@ -1542,7 +1572,7 @@ async function work( | ||
| 1542 | 1572 | ? undefined |
| 1543 | 1573 | : `Budget reached at $${stoppedAt.toFixed(2)}; this is where it stopped.`, |
| 1544 | 1574 | write, |
| 1545 | Object.values(grant.env), | |
| 1575 | [...Object.values(grant.env), ...(devices?.values ?? []).flatMap(keyForms)], | |
| 1546 | 1576 | run.variantGroup, |
| 1547 | 1577 | ); |
| 1548 | 1578 | // An outage that outlasted every pause is named as one, not as a push |
| @@ -1562,6 +1592,7 @@ async function work( | ||
| 1562 | 1592 | await early?.stop(); |
| 1563 | 1593 | if (!pausing) early?.settle(ending); |
| 1564 | 1594 | grant?.release(); |
| 1595 | devices?.finish(); | |
| 1565 | 1596 | deleteToken(app.db, agent.user.id, token.id); |
| 1566 | 1597 | if (runTmp !== undefined) rmSync(runTmp, { recursive: true, force: true }); |
| 1567 | 1598 | } |
src/http/server.ts +12
| @@ -142,6 +142,13 @@ import { reconnectSubmit } from "../web/pages/frozen.ts"; | ||
| 142 | 142 | import { activityAtom } from "../web/feeds.ts"; |
| 143 | 143 | import { auditCsv, auditPage, auditProbeSubmit } from "../web/pages/audit.ts"; |
| 144 | 144 | import { secretDelete, secretSet, secretsPage } from "../web/pages/secrets.ts"; |
| 145 | import { | |
| 146 | deviceAdd, | |
| 147 | deviceGrant, | |
| 148 | deviceRemove, | |
| 149 | deviceRevoke, | |
| 150 | devicesPage, | |
| 151 | } from "../web/pages/devices.ts"; | |
| 145 | 152 | import { |
| 146 | 153 | backupsClear, |
| 147 | 154 | backupsDestination, |
| @@ -1388,6 +1395,11 @@ export function buildRouter(): Router<Handler> { | ||
| 1388 | 1395 | ); |
| 1389 | 1396 | router.add("GET", "/:owner/:name/settings/autonomy", autonomySettingsPage); |
| 1390 | 1397 | router.add("POST", "/:owner/:name/settings/autonomy", autonomySettingsUpdate); |
| 1398 | router.add("GET", "/:owner/:name/settings/devices", devicesPage); | |
| 1399 | router.add("POST", "/:owner/:name/settings/devices", deviceAdd); | |
| 1400 | router.add("POST", "/:owner/:name/settings/devices/:alias/grant", deviceGrant); | |
| 1401 | router.add("POST", "/:owner/:name/settings/devices/:alias/revoke", deviceRevoke); | |
| 1402 | router.add("POST", "/:owner/:name/settings/devices/:alias/remove", deviceRemove); | |
| 1391 | 1403 | router.add("GET", "/:owner/:name/settings/labels", labelsPage); |
| 1392 | 1404 | router.add("POST", "/:owner/:name/settings/labels", labelCreate); |
| 1393 | 1405 | router.add("POST", "/:owner/:name/settings/labels/:id", labelUpdate); |
src/web/pages/devices.ts added +255
| @@ -0,0 +1,255 @@ | ||
| 1 | /** | |
| 2 | * Settings → Devices (#3470): the devices the crew may reach over SSH, and | |
| 3 | * the log of what it did there. A repository admin adds `user@host:port` | |
| 4 | * with the name of the secret that holds the key; a forge admin grants it, | |
| 5 | * pinning the host key (pasted, or scanned from the forge when left | |
| 6 | * empty). The log lists every connection a run opened and every command it | |
| 7 | * ran that named the device, newest first. Nobody else sees the page. | |
| 8 | */ | |
| 9 | ||
| 10 | import { | |
| 11 | addRepoDevice, | |
| 12 | grantRepoDevice, | |
| 13 | removeRepoDevice, | |
| 14 | repoDevices, | |
| 15 | revokeRepoDevice, | |
| 16 | } from "../../actions/devices.ts"; | |
| 17 | import { hostKeyFingerprint, type Device, type DeviceLogEntry } from "../../core/devices.ts"; | |
| 18 | import type { Repo } from "../../core/repos.ts"; | |
| 19 | import { getUserById } from "../../core/users.ts"; | |
| 20 | import type { Ctx } from "../../http/context.ts"; | |
| 21 | import { loadRepo, repoBase, repoNotFound } from "../chrome.ts"; | |
| 22 | import { field, readForm, type Form } from "../form.ts"; | |
| 23 | import { html, when, type Html } from "../html.ts"; | |
| 24 | import { flashTo } from "../layout.ts"; | |
| 25 | import { badge, btn, card, icon, row, time } from "../ui.ts"; | |
| 26 | import { settingsPageResponse } from "./settings.ts"; | |
| 27 | ||
| 28 | const ERRORS: Record<string, string> = { | |
| 29 | invalid_entry: | |
| 30 | "A device is user@host:port exactly — a lowercase login, an address or host name, a port (22 when left off). No ranges, no wildcards.", | |
| 31 | invalid_alias: | |
| 32 | "A name is lowercase letters, digits and dashes, starting with a letter — like pi.", | |
| 33 | invalid_secret: | |
| 34 | "The key's secret is named like ARM_PI_SSH_KEY: capital letters, digits and underscores.", | |
| 35 | invalid_host_key: | |
| 36 | "That is not a host key. Paste a line from ssh-keyscan or known_hosts, like ssh-ed25519 AAAA…", | |
| 37 | alias_taken: "This repository already has a device by that name.", | |
| 38 | too_many: "A repository names at most 8 devices.", | |
| 39 | no_such_device: "No device by that name here.", | |
| 40 | scan_failed: | |
| 41 | "The forge could not read the device's host key (ssh-keyscan found none). Paste it instead.", | |
| 42 | not_found: "Only a forge admin grants a device.", | |
| 43 | }; | |
| 44 | ||
| 45 | function deviceRow(base: string, d: Device, isAdmin: boolean): Html { | |
| 46 | const action = (verb: string) => | |
| 47 | `${base}/settings/devices/${encodeURIComponent(d.alias)}/${verb}`; | |
| 48 | return row({ | |
| 49 | lead: icon("terminal"), | |
| 50 | title: html`<span class="mono">ssh ${d.alias}</span> | |
| 51 | <span class="muted mono small">${d.user}@${d.host}:${String(d.port)}</span>`, | |
| 52 | meta: html`key from <span class="mono">${d.secretName}</span> · | |
| 53 | ${ | |
| 54 | d.grantedAt === null || d.hostKey === null | |
| 55 | ? badge("waiting for a forge admin's grant", { tone: "attn" }) | |
outdated
A state is a |
||
| 56 | : html`granted ${time(d.grantedAt)} · host key | |
| 57 | <span class="mono">${d.hostKey.split(" ")[0] ?? ""} ${hostKeyFingerprint(d.hostKey)}</span>` | |
| 58 | }`, | |
| 59 | trail: html`${when( | |
outdated
DESIGN.md: a row whose trail holds a form (host-key input + Grant) uses |
||
| 60 | isAdmin && d.grantedAt === null, | |
| 61 | () => html`<form class="row-fields" method="post" action="${action("grant")}"> | |
| 62 | <input | |
| 63 | class="input mono" | |
| 64 | type="text" | |
| 65 | name="hostKey" | |
| 66 | placeholder="host key (empty: scan it now)" | |
| 67 | aria-label="Host key for ${d.alias}" | |
| 68 | autocomplete="off" | |
| 69 | spellcheck="false" | |
| 70 | /> | |
| 71 | ${btn("Grant", { size: "sm", icon: "shield" })} | |
| 72 | </form>`, | |
outdated
One accent per page: with several ungranted devices this adds a primary per row beside the primary Add. Make Grant a plain button. |
||
| 73 | )} | |
| 74 | <div class="row-actions"> | |
| 75 | ${when( | |
| 76 | isAdmin && d.grantedAt !== null, | |
| 77 | () => html`<form method="post" action="${action("revoke")}"> | |
| 78 | ${btn("Revoke", { size: "sm", icon: "ban", label: `Revoke ${d.alias}` })} | |
| 79 | </form>`, | |
| 80 | )} | |
| 81 | <form method="post" action="${action("remove")}"> | |
| 82 | ${btn("Remove", { size: "sm", icon: "x", label: `Remove ${d.alias}` })} | |
| 83 | </form> | |
| 84 | </div>`, | |
| 85 | }); | |
| 86 | } | |
| 87 | ||
| 88 | function logRow(ctx: Ctx, e: DeviceLogEntry): Html { | |
| 89 | const who = getUserById(ctx.app.db, e.actorId); | |
| 90 | return html`<tr> | |
| 91 | <td>${time(e.at)}</td> | |
| 92 | <td>${who === undefined ? "someone" : `@${who.username}`}</td> | |
| 93 | <td class="mono">${e.alias}</td> | |
| 94 | <td class="mono small">${e.kind === "connect" ? html`<em>session opened</em>` : e.detail}</td> | |
| 95 | </tr>`; | |
| 96 | } | |
| 97 | ||
| 98 | /** The pane: the devices, a form to add one, and the log. */ | |
| 99 | function devicesPane( | |
| 100 | ctx: Ctx, | |
| 101 | repo: Repo, | |
| 102 | devices: Device[], | |
| 103 | log: DeviceLogEntry[], | |
| 104 | ): Html { | |
| 105 | const base = repoBase(repo); | |
| 106 | const isAdmin = ctx.auth.user?.isAdmin === true; | |
| 107 | const list = card( | |
| 108 | html`<div class="card-body"> | |
| 109 | <p class="muted small"> | |
| 110 | A crew run on this repository can <span class="mono">ssh</span> to | |
| 111 | each granted device: the sandbox lets it reach exactly that | |
| 112 | host:port, the key goes into the run's own temp directory and is | |
| 113 | removed when the run ends, and the host key is pinned at the grant. | |
| 114 | Only a forge admin grants. The key itself is a secret on this | |
| 115 | repository (or its organization, or the forge) — set it under | |
| 116 | Secrets. | |
| 117 | </p> | |
| 118 | </div> | |
| 119 | ${when( | |
| 120 | devices.length > 0, | |
| 121 | () => html`<ul class="list setting-list"> | |
| 122 | ${devices.map((d) => deviceRow(base, d, isAdmin))} | |
| 123 | </ul>`, | |
| 124 | )} | |
| 125 | <form class="edit-row" method="post" action="${base}/settings/devices"> | |
| 126 | <input class="input mono" type="text" name="alias" placeholder="pi" | |
| 127 | aria-label="Name" pattern="[a-z][a-z0-9\\-]{0,30}" maxlength="31" | |
| 128 | autocomplete="off" spellcheck="false" required /> | |
| 129 | <input class="input mono" type="text" name="entry" | |
| 130 | placeholder="[email protected]:22" aria-label="user@host:port" | |
| 131 | maxlength="300" autocomplete="off" spellcheck="false" required /> | |
| 132 | <input class="input mono" type="text" name="secretName" | |
| 133 | placeholder="ARM_PI_SSH_KEY" aria-label="Secret holding the key" | |
| 134 | pattern="[A-Z][A-Z0-9_]*" maxlength="128" autocomplete="off" | |
| 135 | spellcheck="false" required /> | |
| 136 | ${btn("Add", { variant: "primary", size: "sm", icon: "plus" })} | |
| 137 | </form>`, | |
| 138 | { head: html`${icon("terminal")}<h2>Devices the crew may reach</h2>`, pad: false }, | |
| 139 | ); | |
| 140 | const sessions = card( | |
| 141 | log.length === 0 | |
| 142 | ? html`<p class="muted">No run has used a device yet.</p>` | |
| 143 | : html`<table class="table"> | |
| 144 | <thead><tr><th>When</th><th>Who</th><th>Device</th><th>What</th></tr></thead> | |
| 145 | <tbody>${log.map((e) => logRow(ctx, e))}</tbody> | |
| 146 | </table> | |
| 147 | <p class="muted small mt"> | |
| 148 | A command is read from Claude Code's own stream, which the run | |
| 149 | cannot edit; one that builds the device's name at run time is | |
| 150 | not caught. <em>Session opened</em> is best-effort: the run can | |
| 151 | write the file it comes from. | |
| 152 | </p>`, | |
| 153 | { head: html`${icon("history")}<h2>What the crew did on them</h2>` }, | |
| 154 | ); | |
| 155 | return html`${list}<div class="mt">${sessions}</div>`; | |
| 156 | } | |
| 157 | ||
| 158 | function managed(ctx: Ctx): Repo | undefined { | |
| 159 | const repo = loadRepo(ctx); | |
| 160 | if (repo === undefined) return undefined; | |
| 161 | return repoDevices(ctx.app, ctx.auth.user, repo).ok ? repo : undefined; | |
| 162 | } | |
| 163 | ||
| 164 | // GET /:owner/:name/settings/devices | |
| 165 | export function devicesPage(ctx: Ctx): Response { | |
| 166 | const repo = loadRepo(ctx); | |
| 167 | if (repo === undefined) return repoNotFound(ctx); | |
| 168 | const got = repoDevices(ctx.app, ctx.auth.user, repo); | |
| 169 | if (!got.ok) return repoNotFound(ctx); | |
| 170 | return settingsPageResponse( | |
| 171 | ctx, | |
| 172 | repo, | |
| 173 | "devices", | |
| 174 | "Devices", | |
| 175 | devicesPane(ctx, repo, got.value.devices, got.value.log), | |
| 176 | ); | |
| 177 | } | |
| 178 | ||
| 179 | async function gate(ctx: Ctx): Promise<{ repo: Repo; form: Form } | Response> { | |
| 180 | const repo = managed(ctx); | |
| 181 | if (repo === undefined) return repoNotFound(ctx); | |
| 182 | const form = await readForm(ctx, "admin"); | |
| 183 | if (form instanceof Response) return form; | |
| 184 | return { repo, form }; | |
| 185 | } | |
| 186 | ||
| 187 | const back = (repo: Repo): string => `${repoBase(repo)}/settings/devices`; | |
| 188 | const said = (error: string): string => ERRORS[error] ?? "That could not be done."; | |
| 189 | ||
| 190 | // POST /:owner/:name/settings/devices | |
| 191 | export async function deviceAdd(ctx: Ctx): Promise<Response> { | |
| 192 | const g = await gate(ctx); | |
| 193 | if (g instanceof Response) return g; | |
| 194 | const added = addRepoDevice(ctx.app, ctx.auth.user, g.repo, { | |
| 195 | alias: field(g.form, "alias"), | |
| 196 | entry: field(g.form, "entry"), | |
| 197 | secretName: field(g.form, "secretName"), | |
| 198 | }); | |
| 199 | return flashTo( | |
| 200 | ctx, | |
| 201 | back(g.repo), | |
| 202 | added.ok | |
| 203 | ? { message: `${added.value.alias} is added; a forge admin grants it.` } | |
| 204 | : { tone: "danger", message: said(added.error) }, | |
| 205 | ); | |
| 206 | } | |
| 207 | ||
| 208 | // POST /:owner/:name/settings/devices/:alias/remove | |
| 209 | export async function deviceRemove(ctx: Ctx): Promise<Response> { | |
| 210 | const g = await gate(ctx); | |
| 211 | if (g instanceof Response) return g; | |
| 212 | const alias = ctx.params.alias ?? ""; | |
| 213 | const done = removeRepoDevice(ctx.app, ctx.auth.user, g.repo, alias); | |
| 214 | return flashTo( | |
| 215 | ctx, | |
| 216 | back(g.repo), | |
| 217 | done.ok ? { message: `${alias} is removed.` } : { tone: "danger", message: said(done.error) }, | |
| 218 | ); | |
| 219 | } | |
| 220 | ||
| 221 | // POST /:owner/:name/settings/devices/:alias/grant | |
| 222 | export async function deviceGrant(ctx: Ctx): Promise<Response> { | |
| 223 | const g = await gate(ctx); | |
| 224 | if (g instanceof Response) return g; | |
| 225 | const alias = ctx.params.alias ?? ""; | |
| 226 | const done = await grantRepoDevice( | |
| 227 | ctx.app, | |
| 228 | ctx.auth.user, | |
| 229 | g.repo, | |
| 230 | alias, | |
| 231 | field(g.form, "hostKey"), | |
| 232 | ); | |
| 233 | return flashTo( | |
| 234 | ctx, | |
| 235 | back(g.repo), | |
| 236 | done.ok | |
| 237 | ? { | |
| 238 | message: `${alias} is granted; its host key ${hostKeyFingerprint(done.value.hostKey ?? "")} is pinned.`, | |
| 239 | } | |
| 240 | : { tone: "danger", message: said(done.error) }, | |
| 241 | ); | |
| 242 | } | |
| 243 | ||
| 244 | // POST /:owner/:name/settings/devices/:alias/revoke | |
| 245 | export async function deviceRevoke(ctx: Ctx): Promise<Response> { | |
| 246 | const g = await gate(ctx); | |
| 247 | if (g instanceof Response) return g; | |
| 248 | const alias = ctx.params.alias ?? ""; | |
| 249 | const done = revokeRepoDevice(ctx.app, ctx.auth.user, g.repo, alias); | |
| 250 | return flashTo( | |
| 251 | ctx, | |
| 252 | back(g.repo), | |
| 253 | done.ok ? { message: `${alias} is revoked.` } : { tone: "danger", message: said(done.error) }, | |
| 254 | ); | |
| 255 | } |
src/web/pages/settings.ts +8 −1
| @@ -115,6 +115,7 @@ type Section = | ||
| 115 | 115 | | "app" |
| 116 | 116 | | "prompts" |
| 117 | 117 | | "labels" |
| 118 | | "devices" | |
| 118 | 119 | | "hooks" |
| 119 | 120 | | "danger"; |
| 120 | 121 | |
| @@ -152,6 +153,12 @@ function sections(base: string, active: Section) { | ||
| 152 | 153 | icon: "tag" as const, |
| 153 | 154 | current: active === "labels", |
| 154 | 155 | }, |
| 156 | { | |
| 157 | label: "Devices", | |
| 158 | href: `${base}/settings/devices`, | |
| 159 | icon: "terminal" as const, | |
| 160 | current: active === "devices", | |
| 161 | }, | |
| 155 | 162 | { |
| 156 | 163 | label: "Webhooks", |
| 157 | 164 | href: `${base}/settings/hooks`, |
| @@ -168,7 +175,7 @@ function sections(base: string, active: Section) { | ||
| 168 | 175 | } |
| 169 | 176 | |
| 170 | 177 | /** Every settings page is the same frame with a different pane inside it. */ |
| 171 | function settingsPageResponse( | |
| 178 | export function settingsPageResponse( | |
| 172 | 179 | ctx: Ctx, |
| 173 | 180 | repo: Repo, |
| 174 | 181 | active: Section, |
test/crew-devices.test.ts added +487
| @@ -0,0 +1,487 @@ | ||
| 1 | /** | |
| 2 | * Devices the crew may reach (#3470): an exact `user@host:port` a repository | |
| 3 | * admin names and a forge admin grants. A granted device gets a run a key | |
| 4 | * file, a pinned known_hosts, a config whose ProxyCommand opens exactly | |
| 5 | * that destination, and the sandbox widened by exactly that host:port; an | |
| 6 | * ungranted one gets nothing, and a proxy that refuses a destination | |
| 7 | * refuses the tunnel. The key is never in the environment, and a key | |
| 8 | * echoed into the run log is redacted. What a run did on a device is in | |
| 9 | * the repository's device log. | |
| 10 | */ | |
| 11 | ||
| 12 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 13 | import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; | |
| 14 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 15 | import { connect, createServer, type Server } from "node:net"; | |
| 16 | import { tmpdir } from "node:os"; | |
| 17 | import { join } from "node:path"; | |
| 18 | import { addToCrew, createAgent } from "../src/actions/crew.ts"; | |
| 19 | import { assignIssue, openIssue } from "../src/actions/issues.ts"; | |
| 20 | import { | |
| 21 | addRepoDevice, | |
| 22 | grantRepoDevice, | |
| 23 | repoDevices, | |
| 24 | revokeRepoDevice, | |
| 25 | } from "../src/actions/devices.ts"; | |
| 26 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 27 | import { createApp, type App } from "../src/app.ts"; | |
| 28 | import { deviceLog, grantedDevices, hostKeyFingerprint, parseDeviceEntry, parseHostKey } from "../src/core/devices.ts"; | |
| 29 | import { setAccountCeiling } from "../src/core/account_ceiling.ts"; | |
| 30 | import type { Repo } from "../src/core/repos.ts"; | |
| 31 | import { createRun, getRun } from "../src/core/runs.ts"; | |
| 32 | import { setSecret } from "../src/core/secret_store.ts"; | |
| 33 | import { createUser, type User } from "../src/core/users.ts"; | |
| 34 | import { deviceLines } from "../src/crew/brief.ts"; | |
| 35 | import { namesDevice, prepareDevices } from "../src/crew/devices.ts"; | |
| 36 | import { tunnel } from "../src/crew/device_proxy.ts"; | |
| 37 | import { runClaude } from "../src/crew/claude.ts"; | |
| 38 | import { executeAgentRun } from "../src/crew/runner.ts"; | |
| 39 | import { runTmpDir, sandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 40 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 41 | import { appendRunLog, readRunLog } from "../src/runs/log.ts"; | |
| 42 | import { adminCookie } from "./helpers/admin.ts"; | |
| 43 | import { quietLogs } from "./helpers/globals.ts"; | |
| 44 | import { promote } from "./helpers/members.ts"; | |
| 45 | ||
| 46 | quietLogs(); | |
| 47 | ||
| 48 | const KEY_LINE = "b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW"; | |
| 49 | const KEY = `-----BEGIN OPENSSH PRIVATE KEY-----\n${KEY_LINE}\nQyNTUxOQAAACBfakefakefakefakefakefakefakefakefakefakefakeAAAA\n-----END OPENSSH PRIVATE KEY-----\n`; | |
| 50 | const HOST_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFakeHostKeyForTheTestsOnly0123456789abcdef"; | |
| 51 | ||
| 52 | /** A fake SSH host: says its banner to whoever connects. */ | |
| 53 | function fakeSshHost(): Promise<{ server: Server; port: number }> { | |
| 54 | return new Promise((resolve) => { | |
| 55 | const server = createServer((s) => s.end("SSH-2.0-fake_device\r\n")); | |
| 56 | server.listen(0, "127.0.0.1", () => { | |
| 57 | const a = server.address(); | |
| 58 | resolve({ server, port: typeof a === "object" && a !== null ? a.port : 0 }); | |
| 59 | }); | |
| 60 | }); | |
| 61 | } | |
| 62 | ||
| 63 | /** | |
| 64 | * A fake sandbox proxy: HTTP CONNECT, basic auth, and an allow-list of | |
| 65 | * `host:port` it tunnels — anything else is a 403, as Claude Code's is. | |
| 66 | * Every allowed target is tunnelled to the fake host on loopback. | |
| 67 | */ | |
| 68 | function fakeProxy(allow: string, hostPort: number): Promise<{ server: Server; port: number; seen: string[] }> { | |
| 69 | const seen: string[] = []; | |
| 70 | return new Promise((resolve) => { | |
| 71 | const server = createServer((client) => { | |
| 72 | let buf = Buffer.alloc(0); | |
| 73 | const onData = (chunk: Buffer) => { | |
| 74 | buf = Buffer.concat([buf, chunk]); | |
| 75 | const end = buf.indexOf("\r\n\r\n"); | |
| 76 | if (end === -1) return; | |
| 77 | client.off("data", onData); | |
| 78 | const head = buf.subarray(0, end).toString(); | |
| 79 | const target = /^CONNECT (\S+) /.exec(head)?.[1] ?? ""; | |
| 80 | seen.push(head); | |
| 81 | const authed = head.includes(`Proxy-Authorization: Basic ${btoa("srt:pw")}`); | |
| 82 | if (target !== allow || !authed) { | |
| 83 | client.end("HTTP/1.1 403 Forbidden\r\n\r\n"); | |
| 84 | return; | |
| 85 | } | |
| 86 | const up = connect({ host: "127.0.0.1", port: hostPort }, () => { | |
| 87 | client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); | |
| 88 | up.pipe(client); | |
| 89 | client.pipe(up); | |
| 90 | }); | |
| 91 | }; | |
| 92 | client.on("data", onData); | |
| 93 | }); | |
| 94 | server.listen(0, "127.0.0.1", () => { | |
| 95 | const a = server.address(); | |
| 96 | resolve({ server, port: typeof a === "object" && a !== null ? a.port : 0, seen }); | |
| 97 | }); | |
| 98 | }); | |
| 99 | } | |
| 100 | ||
| 101 | describe("a device entry", () => { | |
| 102 | test("is user@host:port exactly; the port defaults to 22", () => { | |
| 103 | expect(parseDeviceEntry("[email protected]:22")).toEqual({ | |
| 104 | ok: true, | |
| 105 | value: { user: "crew", host: "100.89.95.68", port: 22 }, | |
| 106 | }); | |
| 107 | expect(parseDeviceEntry("[email protected]")).toEqual({ | |
| 108 | ok: true, | |
| 109 | value: { user: "crew", host: "pi.local", port: 22 }, | |
| 110 | }); | |
| 111 | }); | |
| 112 | ||
| 113 | test("ranges, wildcards, options and junk are refused", () => { | |
| 114 | for (const bad of [ | |
| 115 | "[email protected]/24", | |
| 116 | "[email protected].*", | |
| 117 | "[email protected]:22-25", | |
| 118 | "crew@-oProxyCommand=touch", | |
| 119 | "[email protected]", | |
| 120 | "crew@host:0", | |
| 121 | "crew@host:70000", | |
| 122 | "-o@host", | |
| 123 | "crew host", | |
| 124 | "crew@a b", | |
| 125 | "@host", | |
| 126 | ]) | |
| 127 | expect(parseDeviceEntry(bad).ok).toBe(false); | |
| 128 | }); | |
| 129 | ||
| 130 | test("a host key is read from ssh-keyscan's output, ed25519 first", () => { | |
| 131 | const scanned = `# 100.89.95.68:22 SSH-2.0-dropbear\n100.89.95.68 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ\n100.89.95.68 ${HOST_KEY}\n`; | |
| 132 | expect(parseHostKey(scanned)).toEqual({ ok: true, value: HOST_KEY }); | |
| 133 | expect(parseHostKey("not a key").ok).toBe(false); | |
| 134 | expect(parseHostKey("ssh-ed25519 short").ok).toBe(false); | |
| 135 | }); | |
| 136 | ||
| 137 | test("a host key's fingerprint is ssh-keygen's: SHA256 of the blob, unpadded base64", () => { | |
| 138 | // By hand: the blob is the base64 body decoded; its SHA-256, base64, '=' dropped. | |
| 139 | const blob = Buffer.from(HOST_KEY.split(" ")[1]!, "base64"); | |
| 140 | const hand = new Bun.CryptoHasher("sha256").update(blob).digest("base64").replace(/=+$/, ""); | |
| 141 | expect(hostKeyFingerprint(HOST_KEY)).toBe(`SHA256:${hand}`); | |
| 142 | expect(hostKeyFingerprint(HOST_KEY)).not.toContain("="); | |
| 143 | // A fixed vector: the 4-byte blob "abcd" (YWJjZA==). | |
| 144 | expect(hostKeyFingerprint("ssh-ed25519 YWJjZA==")).toBe( | |
| 145 | "SHA256:iNQmb9TmM40TuEX88olXnSCciXgjuSF9o+Fhk28DFYk", | |
| 146 | ); | |
| 147 | }); | |
| 148 | }); | |
| 149 | ||
| 150 | describe("devices on a repository", () => { | |
| 151 | let dataDir = ""; | |
| 152 | let app: App; | |
| 153 | let admin: User; | |
| 154 | let owner: User; | |
| 155 | let repo: Repo; | |
| 156 | let fake: { server: Server; port: number }; | |
| 157 | ||
| 158 | beforeAll(async () => { | |
| 159 | dataDir = await mkdtemp(join(tmpdir(), "forge-devices-")); | |
| 160 | app = createApp({ dataDir, port: 0 }); | |
| 161 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 162 | const o = await createUser(app.db, { origin: "seed", trusted: true, username: "olive", email: "[email protected]", password: "a-good-passphrase" }); | |
| 163 | if (!a.ok || !o.ok) throw new Error("users"); | |
| 164 | admin = a.value; | |
| 165 | owner = o.value; | |
| 166 | promote(app.db, owner); | |
| 167 | const r = await createRepo(app, owner, { name: "arm", visibility: "private" }); | |
| 168 | if (!r.ok) throw new Error(String(r.error)); | |
| 169 | repo = r.value; | |
| 170 | fake = await fakeSshHost(); | |
| 171 | }); | |
| 172 | afterAll(async () => { | |
| 173 | fake.server.close(); | |
| 174 | app.close(); | |
| 175 | await rm(dataDir, { recursive: true, force: true }); | |
| 176 | }); | |
| 177 | ||
| 178 | test("the repository's admin adds; only a forge admin grants", async () => { | |
| 179 | expect(addRepoDevice(app, admin, repo, { alias: "x", entry: "[email protected]", secretName: "K" }).ok).toBe(true); | |
| 180 | const stranger = await createUser(app.db, { origin: "seed", trusted: true, username: "eve", email: "[email protected]", password: "a-good-passphrase" }); | |
| 181 | if (!stranger.ok) throw new Error("eve"); | |
| 182 | expect(addRepoDevice(app, stranger.value, repo, { alias: "y", entry: "[email protected]", secretName: "K" })).toEqual({ ok: false, error: "not_found" }); | |
| 183 | expect(repoDevices(app, stranger.value, repo).ok).toBe(false); | |
| 184 | ||
| 185 | const added = addRepoDevice(app, owner, repo, { alias: "pi", entry: `[email protected]:${fake.port}`, secretName: "ARM_PI_SSH_KEY" }); | |
| 186 | expect(added.ok).toBe(true); | |
| 187 | expect(addRepoDevice(app, owner, repo, { alias: "pi", entry: "[email protected]", secretName: "K" })).toEqual({ ok: false, error: "alias_taken" }); | |
| 188 | expect(grantedDevices(app.db, repo.id)).toEqual([]); | |
| 189 | ||
| 190 | // The owner is not a forge admin: the grant is not theirs to give. | |
| 191 | expect(await grantRepoDevice(app, owner, repo, "pi", HOST_KEY)).toEqual({ ok: false, error: "not_found" }); | |
| 192 | // An empty key is scanned from the forge; a scan that finds none refuses. | |
| 193 | expect(await grantRepoDevice(app, admin, repo, "pi", "", async () => ({ ok: false, error: "scan_failed" }))).toEqual({ ok: false, error: "scan_failed" }); | |
| 194 | let scanned = ""; | |
| 195 | const granted = await grantRepoDevice(app, admin, repo, "pi", "", async (host, port) => { | |
| 196 | scanned = `${host}:${port}`; | |
| 197 | return { ok: true, value: HOST_KEY }; | |
| 198 | }); | |
| 199 | expect(scanned).toBe(`127.0.0.1:${fake.port}`); | |
| 200 | expect(granted.ok && granted.value.hostKey).toBe(HOST_KEY); | |
| 201 | expect(grantedDevices(app.db, repo.id).map((d) => d.alias)).toEqual(["pi"]); | |
| 202 | const ev = app.db.query<{ payload: string }, []>("SELECT payload FROM event WHERE kind = 'device.granted'").get()!; | |
| 203 | expect(ev.payload).toContain("pi"); | |
| 204 | }); | |
| 205 | ||
| 206 | test("a run gets the granted device and nothing else, and its key stays out of the log", async () => { | |
| 207 | setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY); | |
| 208 | const runTmp = join(dataDir, "run-tmp"); | |
| 209 | const run = { id: "run-dev-1", repoId: repo.id, ownerId: repo.ownerId, actorId: admin.id }; | |
| 210 | // A stand-in ssh on the run's PATH that says what it was asked. | |
| 211 | const tools = join(dataDir, "tools"); | |
| 212 | mkdirSync(tools); | |
| 213 | writeFileSync(join(tools, "ssh"), '#!/bin/sh\necho "$@"\n', { mode: 0o755 }); | |
| 214 | const prepared = prepareDevices({ db: app.db, dataDir, bus: app.bus, run, tmpDir: runTmp, path: tools }); | |
| 215 | try { | |
| 216 | expect(prepared.devices.map((d) => d.alias)).toEqual(["pi"]); | |
| 217 | expect(prepared.hosts).toEqual([`127.0.0.1:${fake.port}`]); | |
| 218 | // "x" was never granted: no key, no config entry, no egress. | |
| 219 | const config = readFileSync(join(runTmp, "ssh", "config"), "utf8"); | |
| 220 | expect(config).toContain("Host pi\n"); | |
| 221 | expect(config).not.toContain("Host x\n"); | |
| 222 | expect(config).toContain("StrictHostKeyChecking yes"); | |
| 223 | expect(readFileSync(join(runTmp, "ssh", "known_hosts"), "utf8")).toBe(`[127.0.0.1]:${fake.port} ${HOST_KEY}\n`); | |
| 224 | const keyFile = join(runTmp, "ssh", "id_pi"); | |
| 225 | expect(statSync(keyFile).mode & 0o777).toBe(0o600); | |
| 226 | expect(readFileSync(keyFile, "utf8")).toBe(KEY); | |
| 227 | // `ssh pi …` on the run's PATH is the real ssh with the run's config. | |
| 228 | expect(prepared.env["PATH"]).toBe(`${join(runTmp, "ssh", "bin")}:${tools}`); | |
| 229 | const said = Bun.spawnSync(["ssh", "pi", "uptime"], { env: { PATH: prepared.env["PATH"]! } }); | |
| 230 | expect(said.stdout.toString()).toBe(`-F ${join(runTmp, "ssh", "config")} pi uptime\n`); | |
| 231 | // The key goes to a file, never to the environment or the config. | |
| 232 | expect(JSON.stringify(prepared.env)).not.toContain(KEY_LINE); | |
| 233 | expect(config).not.toContain(KEY_LINE); | |
| 234 | ||
| 235 | const policy = sandboxPolicy({ dataDir, agentName: "torque", urls: [], extraHosts: prepared.hosts }); | |
| 236 | expect(policy.allowHosts).toContain(`127.0.0.1:${fake.port}`); | |
| 237 | expect(policy.allowHosts).not.toContain("h.example:22"); | |
| 238 | ||
| 239 | // A `cat` of the key in the run's shell reaches the log redacted. | |
| 240 | appendRunLog(dataDir, run.id, `→ Bash cat id_pi\n${KEY}`); | |
| 241 | appendRunLog(dataDir, run.id, `stray ${KEY_LINE}`); | |
| 242 | const logged = readRunLog(dataDir, run.id).lines.join("\n"); | |
| 243 | expect(logged).not.toContain(KEY_LINE); | |
| 244 | expect(logged).toContain("[redacted]"); | |
| 245 | ||
| 246 | // The run connects: ssh's ProxyCommand, as the config names it, opens | |
| 247 | // the fake host and hands its banner back. | |
| 248 | const proxyLine = /ProxyCommand (.*)/.exec(config)![1]!.split(" "); | |
| 249 | expect(proxyLine.slice(-2)).toEqual(["127.0.0.1", String(fake.port)]); | |
| 250 | const proc = Bun.spawn([process.execPath, ...proxyLine.slice(1)], { | |
| 251 | stdin: "pipe", | |
| 252 | stdout: "pipe", | |
| 253 | stderr: "pipe", | |
| 254 | env: { PATH: process.env["PATH"] ?? "" }, | |
| 255 | }); | |
| 256 | const banner = await new Response(proc.stdout).text(); | |
| 257 | proc.stdin.end(); | |
| 258 | await proc.exited; | |
| 259 | expect(banner).toBe("SSH-2.0-fake_device\r\n"); | |
| 260 | ||
| 261 | // Commands naming the device are logged as asked for; others are not. | |
| 262 | prepared.watch("Bash", { command: "ssh pi 'sudo -n systemctl status so101.service'" }); | |
| 263 | prepared.watch("Bash", { command: "bun test" }); | |
| 264 | prepared.watch("Bash", { command: `echo ${KEY_LINE} | ssh pi tee x` }); | |
| 265 | prepared.watch("Read", { file_path: "pi" }); | |
| 266 | } finally { | |
| 267 | prepared.finish(); | |
| 268 | } | |
| 269 | // The key and everything beside it go with finish(), not with the run's directory. | |
| 270 | expect(existsSync(join(runTmp, "ssh"))).toBe(false); | |
| 271 | expect(existsSync(runTmp)).toBe(true); | |
| 272 | const entries = deviceLog(app.db, repo.id); | |
| 273 | expect(entries.filter((e) => e.kind === "connect").length).toBe(1); | |
| 274 | const commands = entries.filter((e) => e.kind === "command").map((e) => e.detail); | |
| 275 | expect(commands.length).toBe(2); | |
| 276 | expect(commands).toContain("ssh pi 'sudo -n systemctl status so101.service'"); | |
| 277 | expect(commands.join("\n")).not.toContain(KEY_LINE); | |
| 278 | expect(entries.every((e) => e.actorId === admin.id && e.runId === "run-dev-1")).toBe(true); | |
| 279 | }); | |
| 280 | ||
| 281 | test("a revoked device is handed to no run", () => { | |
| 282 | expect(revokeRepoDevice(app, owner, repo, "pi").ok).toBe(false); | |
| 283 | expect(revokeRepoDevice(app, admin, repo, "pi").ok).toBe(true); | |
| 284 | const prepared = prepareDevices({ | |
| 285 | db: app.db, | |
| 286 | dataDir, | |
| 287 | bus: app.bus, | |
| 288 | run: { id: "run-dev-2", repoId: repo.id, ownerId: repo.ownerId, actorId: admin.id }, | |
| 289 | tmpDir: join(dataDir, "run-tmp-2"), | |
| 290 | path: "", | |
| 291 | }); | |
| 292 | expect(prepared.devices).toEqual([]); | |
| 293 | expect(prepared.hosts).toEqual([]); | |
| 294 | }); | |
| 295 | }); | |
| 296 | ||
| 297 | describe("the tunnel", () => { | |
| 298 | let fake: { server: Server; port: number }; | |
| 299 | let proxy: Awaited<ReturnType<typeof fakeProxy>>; | |
| 300 | beforeAll(async () => { | |
| 301 | fake = await fakeSshHost(); | |
| 302 | proxy = await fakeProxy("100.89.95.68:22", fake.port); | |
| 303 | }); | |
| 304 | afterAll(() => { | |
| 305 | fake.server.close(); | |
| 306 | proxy.server.close(); | |
| 307 | }); | |
| 308 | const env = () => ({ HTTPS_PROXY: `http://srt:[email protected]:${proxy.port}` }); | |
| 309 | ||
| 310 | test("goes through the sandbox's proxy to a granted host:port", async () => { | |
| 311 | const { socket, head } = await tunnel(env(), "100.89.95.68", 22); | |
| 312 | const got = await new Promise<string>((resolve) => { | |
| 313 | let text = head.toString(); | |
| 314 | socket.on("data", (c) => (text += c.toString())); | |
| 315 | socket.on("close", () => resolve(text)); | |
| 316 | }); | |
| 317 | expect(got).toBe("SSH-2.0-fake_device\r\n"); | |
| 318 | expect(proxy.seen.at(-1)).toStartWith("CONNECT 100.89.95.68:22 HTTP/1.1"); | |
| 319 | }); | |
| 320 | ||
| 321 | test("an ungranted host is refused by the proxy, and the tunnel says so", async () => { | |
| 322 | await expect(tunnel(env(), "100.89.95.69", 22)).rejects.toThrow("refused 100.89.95.69:22 (403)"); | |
| 323 | await expect(tunnel(env(), "100.89.95.68", 2222)).rejects.toThrow("(403)"); | |
| 324 | }); | |
| 325 | }); | |
| 326 | ||
| 327 | describe("the brief and the log's reader", () => { | |
| 328 | test("the brief names the device and the rules only when there is one", () => { | |
| 329 | expect(deviceLines([])).toEqual([]); | |
| 330 | const text = deviceLines([{ alias: "pi", user: "crew", host: "100.89.95.68", port: 22 }]).join("\n"); | |
| 331 | expect(text).toContain("`ssh pi`"); | |
| 332 | expect(text).toContain("Never change the device's users, SSH keys, network"); | |
| 333 | expect(text).toContain("Restart only the services sudo allows"); | |
| 334 | }); | |
| 335 | ||
| 336 | test("a command names a device by alias or address, beside an ssh tool", () => { | |
| 337 | const pi = { alias: "pi", user: "crew", host: "100.89.95.68", port: 22 }; | |
| 338 | expect(namesDevice("ssh pi uptime", pi)).toBe(true); | |
| 339 | expect(namesDevice("scp a.py pi:/home/dietpi/so101/", pi)).toBe(true); | |
| 340 | expect(namesDevice("ssh [email protected] ls", pi)).toBe(true); | |
| 341 | expect(namesDevice("cat pi.txt", pi)).toBe(false); | |
| 342 | expect(namesDevice("ssh pip install", pi)).toBe(false); | |
| 343 | }); | |
| 344 | }); | |
| 345 | ||
| 346 | describe("a run that ends before its sandbox", () => { | |
| 347 | let dataDir = ""; | |
| 348 | let app: App; | |
| 349 | let servers: Servers; | |
| 350 | ||
| 351 | beforeAll(async () => { | |
| 352 | dataDir = await mkdtemp(join(tmpdir(), "forge-devices-early-")); | |
| 353 | app = createApp({ dataDir, port: 0 }); | |
| 354 | servers = await serve(app); | |
| 355 | }); | |
| 356 | afterAll(async () => { | |
| 357 | servers.stop(); | |
| 358 | app.close(); | |
| 359 | await rm(dataDir, { recursive: true, force: true }); | |
| 360 | }); | |
| 361 | ||
| 362 | test("leaves no key behind", async () => { | |
| 363 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 364 | if (!a.ok) throw new Error("ada"); | |
| 365 | const ada = a.value; | |
| 366 | const r = await createRepo(app, ada, { name: "arm" }); | |
| 367 | if (!r.ok) throw new Error(String(r.error)); | |
| 368 | const repo = r.value; | |
| 369 | await commitToBranch(app, ada, repo, { message: "seed", files: [{ path: "README.md", content: "hi\n" }] }); | |
| 370 | const agent = await createAgent(app, ada, { username: "bot", model: "", brief: "" }); | |
| 371 | if (!agent.ok) throw new Error(String(agent.error)); | |
| 372 | addToCrew(app, ada, repo, "bot"); | |
| 373 | expect(addRepoDevice(app, ada, repo, { alias: "pi", entry: "[email protected]", secretName: "ARM_PI_SSH_KEY" }).ok).toBe(true); | |
| 374 | expect((await grantRepoDevice(app, ada, repo, "pi", HOST_KEY)).ok).toBe(true); | |
| 375 | setSecret(app.db, dataDir, "repo", repo.id, "ARM_PI_SSH_KEY", KEY); | |
| 376 | const issue = openIssue(app, ada, repo, { title: "Check the arm" }); | |
| 377 | if (!issue.ok) throw new Error("issue"); | |
| 378 | assignIssue(app, ada, repo, issue.value, agent.value.user); | |
| 379 | const run = createRun(app.db, { repoId: repo.id, kind: "agent", issueId: issue.value.id, actorId: agent.value.user.id, reason: "assigned" }); | |
| 380 | ||
| 381 | // A per-run ceiling too small to start: the run fails after the devices | |
| 382 | // are prepared and before the sandbox (and the run's temp directory | |
| 383 | // with it) is set up, whatever account the machine would pick. | |
| 384 | expect(setAccountCeiling(app.db, repo.ownerId, 10, 0.01, ada.id, new Date())).toBe(true); | |
| 385 | await executeAgentRun(app, run, { | |
| 386 | forgeUrl: servers.url, | |
| 387 | localUrl: servers.url, | |
| 388 | binary: join(dataDir, "no-such-claude"), | |
| 389 | concurrency: 1, | |
| 390 | budgetUsd: 1, | |
| 391 | runTimeoutMs: 20_000, | |
| 392 | }); | |
| 393 | expect(getRun(app.db, run.id)?.state).toBe("failed"); | |
| 394 | expect(getRun(app.db, run.id)?.summary).toContain("per-run ceiling"); | |
| 395 | const logged = readRunLog(dataDir, run.id).lines.join("\n"); | |
| 396 | expect(logged).toContain("device: ssh pi"); | |
| 397 | const tmp = runTmpDir(dataDir, "bot", run.id); | |
| 398 | expect(existsSync(join(tmp, "ssh", "id_pi"))).toBe(false); | |
| 399 | expect(existsSync(join(tmp, "ssh"))).toBe(false); | |
| 400 | }, 30_000); | |
| 401 | }); | |
| 402 | ||
| 403 | describe("the Devices page", () => { | |
| 404 | let dataDir = ""; | |
| 405 | let app: App; | |
| 406 | let servers: Servers; | |
| 407 | let cookie = ""; | |
| 408 | beforeAll(async () => { | |
| 409 | dataDir = await mkdtemp(join(tmpdir(), "forge-devices-web-")); | |
| 410 | app = createApp({ dataDir, port: 0 }); | |
| 411 | servers = await serve(app); | |
| 412 | cookie = await adminCookie(app, { username: "olive", email: "[email protected]", password: "settings-password" }); | |
| 413 | await fetch(`${servers.url}/new`, { | |
| 414 | method: "POST", | |
| 415 | headers: { cookie }, | |
| 416 | body: new URLSearchParams({ name: "arm", visibility: "private" }), | |
| 417 | redirect: "manual", | |
| 418 | }); | |
| 419 | }); | |
| 420 | afterAll(async () => { | |
| 421 | servers.stop(); | |
| 422 | app.close(); | |
| 423 | await rm(dataDir, { recursive: true, force: true }); | |
| 424 | }); | |
| 425 | ||
| 426 | test("adds and grants from the page, and is nobody else's", async () => { | |
| 427 | const base = `${servers.url}/olive/arm/settings/devices`; | |
| 428 | const post = (path: string, fields: Record<string, string>) => | |
| 429 | fetch(`${base}${path}`, { method: "POST", headers: { cookie }, body: new URLSearchParams(fields), redirect: "manual" }); | |
| 430 | expect((await post("", { alias: "pi", entry: "[email protected]:22", secretName: "ARM_PI_SSH_KEY" })).status).toBe(303); | |
| 431 | expect((await post("", { alias: "jetson", entry: "[email protected]:22", secretName: "ARM_JETSON_KEY" })).status).toBe(303); | |
| 432 | // Two devices waiting: each says so with a badge, each Grant form is a | |
| 433 | // row's fields, and the page keeps one primary — Add. | |
| 434 | const waiting = await (await fetch(base, { headers: { cookie } })).text(); | |
| 435 | expect(waiting.match(/<span\s+class="badge"\s+data-variant="attn"\s*>waiting for a forge admin/g)?.length).toBe(2); | |
| 436 | expect(waiting.match(/<form class="row-fields" method="post" action="[^"]*\/grant"/g)?.length).toBe(2); | |
| 437 | expect(waiting.match(/data-variant="primary"/g)?.length).toBe(1); | |
| 438 | expect((await post("/pi/grant", { hostKey: `100.89.95.68 ${HOST_KEY}` })).status).toBe(303); | |
| 439 | const page = await (await fetch(base, { headers: { cookie } })).text(); | |
| 440 | expect(page).toContain("ssh pi"); | |
| 441 | expect(page).toContain("[email protected]:22"); | |
| 442 | expect(page).toContain("ssh-ed25519"); | |
| 443 | expect(page).toContain(hostKeyFingerprint(HOST_KEY)); | |
| 444 | expect((await fetch(base)).status).toBe(404); | |
| 445 | // A cross-site form is refused before anything changes. | |
| 446 | const cross = await fetch(`${base}/pi/remove`, { | |
| 447 | method: "POST", | |
| 448 | headers: { cookie, origin: "https://evil.example" }, | |
| 449 | body: new URLSearchParams({}), | |
| 450 | redirect: "manual", | |
| 451 | }); | |
| 452 | expect(cross.status).toBe(403); | |
| 453 | }); | |
| 454 | }); | |
| 455 | ||
| 456 | describe("the run's tool calls", () => { | |
| 457 | test("runClaude hands each tool call to onTool, as the agent asked for it", async () => { | |
| 458 | const dir = await mkdtemp(join(tmpdir(), "forge-devices-tool-")); | |
| 459 | const fake = join(dir, "fake-claude"); | |
| 460 | writeFileSync( | |
| 461 | fake, | |
| 462 | `#!/bin/sh | |
| 463 | IFS= read -r first | |
| 464 | echo '{"type":"system","subtype":"init","session_id":"s1","model":"fake"}' | |
| 465 | echo '{"type":"assistant","message":{"content":[{"type":"text","text":"looking"},{"type":"tool_use","name":"Bash","input":{"command":"ssh pi uptime"}}]}}' | |
| 466 | echo '{"type":"result","subtype":"success","is_error":false,"result":"ok","total_cost_usd":0.01,"num_turns":1}' | |
| 467 | `, | |
| 468 | { mode: 0o755 }, | |
| 469 | ); | |
| 470 | const calls: [string, unknown][] = []; | |
| 471 | await runClaude({ | |
| 472 | binary: fake, | |
| 473 | cwd: dir, | |
| 474 | prompt: "go", | |
| 475 | appendSystemPrompt: "", | |
| 476 | budgetUsd: 1, | |
| 477 | env: {}, | |
| 478 | sandbox: sandboxPolicy({ dataDir: dir, agentName: "bot", urls: [] }), | |
| 479 | timeoutMs: 10_000, | |
| 480 | log: () => {}, | |
| 481 | signal: new AbortController().signal, | |
| 482 | onTool: (name, input) => calls.push([name, input]), | |
| 483 | }); | |
| 484 | expect(calls).toEqual([["Bash", { command: "ssh pi uptime" }]]); | |
| 485 | await rm(dir, { recursive: true, force: true }); | |
| 486 | }, 20_000); | |
| 487 | }); |
True for
commandrows.connectrows come fromsessions.log, which the agent can edit; please say so.