Public: anyone can read this; the crew can change it.
A member adds their own machine; it takes runs only for repositories whose owner allowed it, and an admin marks a machine trusted #18621
Its check is queued, place 7 of 13
torque/forge:torque/18505-a-member-adds-their-own-machine-it-takes → main 9 commits fork
29 files
changed +810
−30
- docs/design/audit.md
- docs/features/own-machines.md
- src/actions/environments.ts
- src/checks/runner_jobs.ts
- src/core/account_purge.ts
- src/core/empty_words.ts
- src/core/event_audience.ts
- src/core/may.ts
- src/core/migration-pins/20261206190000-own-machines.pin
- src/core/migrations/20261206190000-own-machines.ts
- src/http/api/runners.ts
- src/http/lazy_lists.ts
- src/http/marks/settings.json
- src/http/routes/repo_settings.ts
- src/http/settings_routes.ts
- src/machines/own.ts
- src/machines/report.ts
- src/tui/forge_parts.ts
- src/tui/screens/machines.ts
- src/tui/screens/runners.ts
- src/web/pages/machine-allow.ts
- src/web/pages/machines.ts
- src/web/pages/origins.ts
- src/web/pages/own-machines.ts
- src/web/pages/runners.ts
- test/may.test.ts
- test/own-machines-pages.test.ts
- test/own-machines.test.ts
- test/palette-roster.test.ts
docs/design/audit.md +1
| @@ -151,6 +151,7 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 151 | 151 | - `/settings/usage` — `pages/usage.ts` · route patterns by use, unused first · `/settings/telemetry`, `/board/returns` · none seen. Not about cost, despite the name. |
| 152 | 152 | - `/settings/telemetry` — `pages/telemetry.ts` · which agents may read telemetry · `/settings/crew` (agent grants) · none seen. |
| 153 | 153 | - `/settings/trusted` — `pages/trusted.ts` · who may fold in without review, until when, and the kill switch · `/review`, `/settings/crew` · none seen. |
| 154 | - `/settings/machines` — `pages/own-machines.ts` · the machines you added, each with trusted or not, last seen and what it said of itself, and a form to add one (its token shown once) · `/settings/runners` · none seen. | |
| 154 | 155 | - `/settings/runners` — `pages/runners.ts` · the check runners with state, last asked, capacity, jobs held and jobs run, and a Remove for a hand-made one · `/settings/trusted` · none seen. |
| 155 | 156 | - `/settings/runners/live` — `pages/runners.ts` · the runner rows' moving part (connected, busy or idle, the run held and its log), refetched when a `runner.*` event arrives; an admin's only · `/settings/backups/live` · none seen. |
| 156 | 157 | - `/settings/runners/lending/live` — `pages/runners.ts` · the Lending block's moving part (the room to lend and each offer), refetched when a `lending.*` event arrives; an admin's only · `/settings/backups/live` · none seen. |
docs/features/own-machines.md added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | --- | |
| 2 | topic: Ship and undo | |
| 3 | row: Your machines: a member adds one, a repository's owner allows it, an admin trusts it | |
| 4 | --- | |
| 5 | # Your machines (#18505) | |
| 6 | ||
| 7 | A member adds a machine of their own at **Settings → Your machines** (`/settings/machines`, **Your | |
| 8 | machines** in the terminal's command palette, `n` adds). They give a name and the labels they say it | |
| 9 | holds (`macos`, `arm64`); the token is shown once, and the machine is listed under their name. The | |
| 10 | machine then speaks the [](runners.md) as any [](outside-runner.md). | |
| 11 | ||
| 12 | Three decisions, each asked of `may()` (`src/core/may.ts`) and each an event: | |
| 13 | ||
| 14 | - **Add** (`machine.add`): any person's account; a crew member cannot. At most 8 each. | |
| 15 | - **Allow** (`machine.allow`): the repository's administrator, one row on **Settings → Machines** | |
| 16 | (`/<owner>/<repo>/settings/machines`, or `a`/`x` on that repository's Machines screen in the | |
| 17 | terminal). A machine takes a run **only for a repository that allowed it**: one never asked, and | |
| 18 | one refused, are sent nothing. An admin-enrolled runner and the forge's own are not gated. | |
| 19 | - **Trust** (`machine.trust`): a forge admin, on Settings → Runners (`t` in the terminal). Trusted | |
| 20 | machines are sent a main job's secrets ([](environments.md)). Trust is a person's | |
| 21 | decision: a claim that says `trusted` changes nothing. | |
| 22 | ||
| 23 | What a machine reports in its claim's `machine` (`os` darwin/linux/windows, `arch` arm64/x64, | |
| 24 | `docker`, `xcode`) only narrows routing: a label its owner gave it that the report contradicts is | |
| 25 | not held, so a job naming that label is not sent there. The report never adds a label, a | |
| 26 | repository or trust (`src/machines/report.ts`). | |
| 27 | ||
| 28 | The rules are in `src/machines/own.ts`; the page, the terminal and the tests call the same. | |
| 29 | ||
| 30 | **Both doors.** The pages are `src/web/pages/own-machines.ts` (add, list) and | |
| 31 | `src/web/pages/machine-allow.ts` (the repository's row); their terminal doors are | |
| 32 | `src/tui/screens/ownmachines.ts` (**Your machines**, `n` adds) and `src/tui/screens/machines.ts` | |
| 33 | (`a` allows and `x` refuses the member's machine under the cursor). |
src/actions/environments.ts +4 −1
| @@ -4,6 +4,8 @@ | ||
| 4 | 4 | * secrets. Each is an event: who, which name; never a value. |
| 5 | 5 | */ |
| 6 | 6 | import type { App } from "../app.ts"; |
| 7 | import { holds } from "../core/may.ts"; | |
| 8 | import { principalOfUser } from "../core/principal.ts"; | |
| 7 | 9 | import { canAdmin, type Repo } from "../core/repos.ts"; |
| 8 | 10 | import type { User } from "../core/users.ts"; |
| 9 | 11 | import { err, ok, type Result } from "../kernel/result.ts"; |
| @@ -32,8 +34,9 @@ export function removeEnvironmentEntry(app: App, actor: User | undefined, repo: | ||
| 32 | 34 | |
| 33 | 35 | export function setRunnerTrust(app: App, actor: User | undefined, runnerId: string, trusted: boolean): Result<{ id: string; name: string; trusted: boolean }, "not_found" | "local"> { |
| 34 | 36 | const runner = getRunner(app.db, runnerId); |
| 37 | // `machine.trust` (`core/may.ts`): an admin's own decision, never what a machine reports. | |
| 35 | 38 | // A browser tab is never trusted (#18526): it is not a machine this forge's admin can vouch for. |
| 36 | if (actor === undefined || !actor.isAdmin || runner === undefined || runner.kind === "tab") return err("not_found"); | |
| 39 | if (actor === undefined || !holds(app.db, principalOfUser(actor), "machine.trust") || runner === undefined || runner.kind === "tab") return err("not_found"); | |
| 37 | 40 | // The forge's own `local-N` runners hold the forge's data already; trust is for machines it does |
| 38 | 41 | // not own. |
| 39 | 42 | if (runner.name.startsWith("local-")) return err("local"); |
src/checks/runner_jobs.ts +31 −18
| @@ -27,6 +27,7 @@ import { background } from "../perf/jobs.ts"; | ||
| 27 | 27 | import { TAB_TTL_MS, isTabSafe } from "../machines/tab_safe.ts"; |
| 28 | 28 | import { DONE_ENV, keepDone } from "./shard_event.ts"; |
| 29 | 29 | import { canaryCommand, canaryDue, coreMs, lentName, outOfScope, readScope, scopeFrom, utcDay, type LendInput, type LentScope } from "./lent_scope.ts"; |
| 30 | import { heldLabels } from "../machines/report.ts"; | |
| 30 | 31 | |
| 31 | 32 | export const RUNNER_TOKEN_PREFIX = "forge_runner_"; |
| 32 | 33 | export const JOB_TOKEN_PREFIX = "forge_job_"; |
| @@ -166,6 +167,10 @@ export interface Enrolled { | ||
| 166 | 167 | readonly state: string; |
| 167 | 168 | /** Whether a site admin marked it trusted for secrets (`environment.ts`). */ |
| 168 | 169 | readonly trusted: boolean; |
| 170 | /** | |
| 171 | * The member who added it (`machines/own.ts`); "" for one an admin enrolled or the forge owns. | |
| 172 | */ | |
| 173 | readonly ownerId: string; | |
| 169 | 174 | /** |
| 170 | 175 | * `tab` for a browser tab that enrolled itself (`machines/tab_runner.ts`); `machine` for any |
| 171 | 176 | * other. |
| @@ -194,9 +199,10 @@ type RunnerRow = { | ||
| 194 | 199 | repos: string; |
| 195 | 200 | state: string; |
| 196 | 201 | trusted_at: number; |
| 202 | owner_id: string; | |
| 197 | 203 | kind: string; |
| 198 | 204 | }; |
| 199 | const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus, labels, repos, state, trusted_at, kind"; | |
| 205 | const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus, labels, repos, state, trusted_at, owner_id, kind"; | |
| 200 | 206 | |
| 201 | 207 | /** A JSON array of strings as kept in a column; anything else is none. */ |
| 202 | 208 | const stringList = (raw: string): string[] => { |
| @@ -227,6 +233,7 @@ const toEnrolled = (r: RunnerRow, now: number = Date.now()): Enrolled => { | ||
| 227 | 233 | repos: stringList(r.repos), |
| 228 | 234 | state: r.state, |
| 229 | 235 | trusted: r.trusted_at > 0, |
| 236 | ownerId: r.owner_id, | |
| 230 | 237 | kind: r.kind === "tab" ? "tab" : "machine", |
| 231 | 238 | }; |
| 232 | 239 | }; |
| @@ -358,17 +365,16 @@ export function noteHeartbeat(db: Database, runnerId: string, said: { state: str | ||
| 358 | 365 | * within `SEEN_FRESH_MS`, not revoked, not paused, holding the label and serving the repository. |
| 359 | 366 | */ |
| 360 | 367 | export function labelServed(db: Database, repoId: string, label: string, now: number): boolean { |
| 361 | return ( | |
| 362 | db | |
| 363 | .query<{ n: number }, [number, string, string]>( | |
| 364 | `SELECT COUNT(*) AS n FROM check_runner | |
| 365 | WHERE seen_at > ?1 - ${SEEN_FRESH_MS} AND revoked_at = 0 AND paused = '' AND state != 'paused' | |
| 366 | AND EXISTS (SELECT 1 FROM json_each(labels) WHERE value = ?3) | |
| 367 | AND (repos = '[]' OR EXISTS (SELECT 1 FROM json_each(repos) WHERE value = ?2)) | |
| 368 | AND (scope IS NULL OR EXISTS (SELECT 1 FROM repo r WHERE r.id = ?2 AND r.visibility = 'public'))`, | |
| 369 | ) | |
| 370 | .get(now, repoId, label)!.n > 0 | |
| 371 | ); | |
| 368 | return db | |
| 369 | .query<{ id: string; labels: string; report: string; owner_id: string }, [number, string]>( | |
| 370 | `SELECT id, labels, report, owner_id FROM check_runner | |
| 371 | WHERE seen_at > ?1 - ${SEEN_FRESH_MS} AND revoked_at = 0 AND paused = '' AND state != 'paused' | |
| 372 | AND (repos = '[]' OR EXISTS (SELECT 1 FROM json_each(repos) WHERE value = ?2)) | |
| 373 | AND (scope IS NULL OR EXISTS (SELECT 1 FROM repo r WHERE r.id = ?2 AND r.visibility = 'public')) | |
| 374 | AND (owner_id = '' OR EXISTS (SELECT 1 FROM repo_machine m WHERE m.repo_id = ?2 AND m.runner_id = check_runner.id AND m.allowed = 1))`, | |
| 375 | ) | |
| 376 | .all(now, repoId) | |
| 377 | .some((r) => heldLabels(r.labels, r.report).includes(label)); | |
| 372 | 378 | } |
| 373 | 379 | |
| 374 | 380 | /** Let a paused runner claim again. False when it was not paused. */ |
| @@ -547,6 +553,8 @@ type ClaimRow = { | ||
| 547 | 553 | labels: string; |
| 548 | 554 | repos: string; |
| 549 | 555 | state: string; |
| 556 | report: string; | |
| 557 | owner_id: string; | |
| 550 | 558 | kind: string; |
| 551 | 559 | }; |
| 552 | 560 | |
| @@ -562,7 +570,7 @@ export function claimJob( | ||
| 562 | 570 | ): Claim | undefined { |
| 563 | 571 | const me = db |
| 564 | 572 | .query<ClaimRow, [string]>( |
| 565 | "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id, labels, repos, state, kind FROM check_runner WHERE id = ?1", | |
| 573 | "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id, labels, repos, state, report, owner_id, kind FROM check_runner WHERE id = ?1", | |
| 566 | 574 | ) |
| 567 | 575 | .get(runner.id); |
| 568 | 576 | // A runner that said `paused` in its heartbeat (a Mac on battery) takes nothing until it says |
| @@ -581,8 +589,11 @@ export function claimJob( | ||
| 581 | 589 | // which is 0 while a server wakes (`games/lend_fit.ts`); -1 for one that is not. |
| 582 | 590 | // A job naming a label goes only to a runner holding it, and a runner that lists repositories |
| 583 | 591 | // serves only those (#18037); both are `[]` for a runner as it always was. |
| 584 | const labels = me.labels; | |
| 592 | // A member's machine (`machines/own.ts`) takes a job only where the repository's owner allowed | |
| 593 | // it. | |
| 594 | const labels = JSON.stringify(heldLabels(me.labels, me.report)); | |
| 585 | 595 | const repos = me.repos; |
| 596 | const gate = me.owner_id === "" ? "" : runner.id; | |
| 586 | 597 | const spareMiB = me.box_id === "" ? -1 : boxSpareMiB(db, me.box_id, now); |
| 587 | 598 | const queued = |
| 588 | 599 | me.kind === "tab" |
| @@ -599,15 +610,16 @@ export function claimJob( | ||
| 599 | 610 | .all() |
| 600 | 611 | : scope === undefined |
| 601 | 612 | ? db |
| 602 | .query<{ id: string }, [number, string, string]>( | |
| 613 | .query<{ id: string }, [number, string, string, string]>( | |
| 603 | 614 | `SELECT id FROM check_job WHERE state = 'queued' AND canary_for IS NULL AND (needs_cell = 0 OR ?1 = 1) |
| 604 | 615 | AND (label = '' OR label IN (SELECT value FROM json_each(?2))) |
| 605 | 616 | AND (?3 = '[]' OR repo_id IN (SELECT value FROM json_each(?3))) |
| 617 | AND (?4 = '' OR EXISTS (SELECT 1 FROM repo_machine m WHERE m.repo_id = check_job.repo_id AND m.runner_id = ?4 AND m.allowed = 1)) | |
| 606 | 618 | ORDER BY id LIMIT 8`, |
| 607 | 619 | ) |
| 608 | .all(runner.cells ? 1 : 0, labels, repos) | |
| 620 | .all(runner.cells ? 1 : 0, labels, repos, gate) | |
| 609 | 621 | : db |
| 610 | .query<{ id: string }, [string, string, number, number, string, string]>( | |
| 622 | .query<{ id: string }, [string, string, number, number, string, string, string]>( | |
| 611 | 623 | `SELECT j.id FROM check_job j JOIN repo r ON r.id = j.repo_id |
| 612 | 624 | WHERE j.state = 'queued' AND r.visibility = 'public' AND (j.canary_for IS NULL OR j.canary_for = ?1) |
| 613 | 625 | AND (?3 = 0 OR j.author IN (SELECT value FROM json_each(?2))) |
| @@ -617,9 +629,10 @@ export function claimJob( | ||
| 617 | 629 | AND (?6 = '[]' OR j.repo_id IN (SELECT value FROM json_each(?6))) |
| 618 | 630 | -- A game box's runner (?4 >= 0, its spare memory now) takes only a job that declares memory and fits. |
| 619 | 631 | AND (?4 < 0 OR COALESCE(json_extract(j.spec, '$.limits.memoryMiB'), 0) BETWEEN 1 AND ?4) |
| 632 | AND (?7 = '' OR EXISTS (SELECT 1 FROM repo_machine m WHERE m.repo_id = j.repo_id AND m.runner_id = ?7 AND m.allowed = 1)) | |
| 620 | 633 | ORDER BY j.id LIMIT 8`, |
| 621 | 634 | ) |
| 622 | .all(runner.id, JSON.stringify(scope.authors), scope.authors.length, spareMiB, labels, repos); | |
| 635 | .all(runner.id, JSON.stringify(scope.authors), scope.authors.length, spareMiB, labels, repos, gate); | |
| 623 | 636 | if (scope !== undefined && queued.length > 0 && canaryDue(saltOf(me), me.canary_at, me.ran)) { |
| 624 | 637 | const canary = offerCanary(db, runner.id, queued[0]!.id, now, leaseMs); |
| 625 | 638 | if (canary !== undefined) return canary; |
src/core/account_purge.ts +4
| @@ -103,6 +103,9 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 103 | 103 | "bet.backed_by": FORMER, |
| 104 | 104 | "check_proven.proven_by": FORMER, |
| 105 | 105 | "check_runner.created_by": FORMER, |
| 106 | // A member's own machine (#18505) is theirs: it goes with them, and takes no run again. | |
| 107 | "check_runner.owner_id": DELETE, | |
| 108 | "repo_machine.by": { do: "none", why: "a username, not an id: `purgeAccount` rewrites it to the placeholder's name" }, | |
| 106 | 109 | "check_job.author": { do: "none", why: "the login a lent runner's authors scope matches, copied from the pull while its check is in flight" }, |
| 107 | 110 | "child_reach_ask.asked_by": FORMER, |
| 108 | 111 | "child_reach_ask.answered_by": FORMER, |
| @@ -410,6 +413,7 @@ export function purgeAccount(db: Database, userId: string, now: Date, dataDir = | ||
| 410 | 413 | // `repo_env.set_by` and `check_runner.trusted_by` hold usernames: the entry and the trust stay, |
| 411 | 414 | // as the former account's. |
| 412 | 415 | if (name !== "") kept += db.query("UPDATE repo_env SET set_by = ?2 WHERE set_by = ?1").run(name, FORMER_NAME).changes; |
| 416 | if (name !== "") kept += db.query("UPDATE repo_machine SET by = ?2 WHERE by = ?1").run(name, FORMER_NAME).changes; | |
| 413 | 417 | if (name !== "") kept += db.query("UPDATE check_runner SET trusted_by = ?2 WHERE trusted_by = ?1").run(name, FORMER_NAME).changes; |
| 414 | 418 | // `entitlement.payer` is an address, not an id: an ended plan forgets who paid. |
| 415 | 419 | const email = db.query<{ email: string }, [string]>("SELECT email FROM user WHERE id = ?1").get(userId)?.email ?? ""; |
src/core/empty_words.ts +2
| @@ -90,6 +90,8 @@ const TABLE = { | ||
| 90 | 90 | // Lists drawn as one line (`emptyLine`, and `emptyText` in the terminal). A reason names the |
| 91 | 91 | // step, never where it sits: a phone lays the page out differently. |
| 92 | 92 | gifts: { sentence: "No gift yet.", reason: "Make a gift link and send it to a friend." }, |
| 93 | ownMachines: { sentence: "You have added no machine.", reason: "Add one below; it takes nothing until a repository's owner allows it." }, | |
| 94 | memberMachines: { sentence: "No member has added a machine.", reason: "One a member adds appears here, refused until you allow it." }, | |
| 93 | 95 | readGrants: { sentence: "No one else reads it.", reason: "Grant read to one of your apps or one crew member." }, |
| 94 | 96 | // The forge's own flags are declared in code; an app's in its repository. One sentence for both. |
| 95 | 97 | flags: { sentence: NO_FLAG }, |
src/core/event_audience.ts +4
| @@ -244,6 +244,10 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 244 | 244 | if (kind === "webhook.failing") return "writers"; |
| 245 | 245 | // What a repository's beat did says how its autonomy and week's share stand (`crew/beat.ts`). |
| 246 | 246 | if (kind === "beat.ran") return "writers"; |
| 247 | // A member adding their machine is theirs and the admins\' to hear; allowing it on a repository | |
| 248 | // is that repository\'s admins\' (`machines/own.ts`, #18505). | |
| 249 | if (kind === "machine.added") return "actor"; | |
| 250 | if (kind === "machine.allowed" || kind === "machine.refused") return "admins"; | |
| 247 | 251 | // Who took which grant from whom is the admins' record (`actions/take_away.ts`). |
| 248 | 252 | if (kind === "grant.removed") return "admins"; |
| 249 | 253 | if ( |
src/core/may.ts +10 −1
| @@ -77,6 +77,13 @@ export const ACTIONS = { | ||
| 77 | 77 | scope: "rw", |
| 78 | 78 | }, |
| 79 | 79 | "account.manage": { says: "Change your own account: password, profile and tokens, as yourself and not by a token", over: "forge", scope: "ro" }, |
| 80 | "machine.add": { says: "Add your own machine, to take runs for the repositories whose owners allow it", over: "forge", scope: "rw" }, | |
| 81 | "machine.allow": { says: "Allow or refuse a member's machine for a repository you administer", over: "repo", scope: "rw" }, | |
| 82 | "machine.trust": { | |
| 83 | says: "Mark a machine trusted, to be sent secrets: an admin's own decision, never what the machine says of itself", | |
| 84 | over: "forge", | |
| 85 | scope: "rw", | |
| 86 | }, | |
| 80 | 87 | "game.view": { says: "See a game box or one server of it: its state, people, logs and settings", over: "game", scope: "ro" }, |
| 81 | 88 | "game.operate": { says: "Operate a game server: its console, players, worlds, restarts and settings", over: "game", scope: "rw" }, |
| 82 | 89 | "game.own": { says: "Own a game box: its shell, machine, lending and who holds a role on it", over: "game", scope: "rw" }, |
| @@ -148,7 +155,9 @@ function forgeRuleHolds(db: Database, action: Action, p: Principal): boolean { | ||
| 148 | 155 | const user = userOf(p); |
| 149 | 156 | if (user === undefined) return false; |
| 150 | 157 | if (ability === "administer") return user.isAdmin; |
| 151 | if (action === "forge.administer_person") return user.isAdmin && user.kind !== "agent"; | |
| 158 | if (action === "forge.administer_person" || action === "machine.trust") return user.isAdmin && user.kind !== "agent"; | |
| 159 | // `machine.add`: a person's account, a member's own machine; a crew member does not add one. | |
| 160 | if (action === "machine.add") return user.kind === "user"; | |
| 152 | 161 | // `forge.write`: any account may change what is its own to change; the scope says the rest. |
| 153 | 162 | if (action === "forge.write") return true; |
| 154 | 163 | if (ability !== undefined) return !lacks(db, user, ability); |
src/core/migration-pins/20261206190000-own-machines.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 0ce6d5ab716a980a4d87e98eb56aac0833f9eea822cb04accf5356b104a62cab |
src/core/migrations/20261206190000-own-machines.ts added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | // A member's own machine (#18505): who added it (`owner_id`, '' for one an admin enrolled or the | |
| 2 | // forge started, which every repository may use as before), what it last said its machine is | |
| 3 | // (`report`, a JSON object: only ever narrows routing), and the repositories whose owner allowed | |
| 4 | // or refused it. A machine with an owner takes a run only where a row says allowed. Additive. | |
| 5 | export default ` | |
| 6 | ALTER TABLE check_runner ADD COLUMN owner_id TEXT NOT NULL DEFAULT ''; | |
| 7 | ALTER TABLE check_runner ADD COLUMN report TEXT NOT NULL DEFAULT '{}'; | |
| 8 | CREATE TABLE repo_machine ( | |
| 9 | repo_id TEXT NOT NULL, | |
| 10 | runner_id TEXT NOT NULL, | |
| 11 | allowed INTEGER NOT NULL CHECK (allowed IN (0, 1)), | |
| 12 | by TEXT NOT NULL, | |
| 13 | at INTEGER NOT NULL, | |
| 14 | PRIMARY KEY (repo_id, runner_id) | |
| 15 | ); | |
| 16 | `; |
src/http/api/runners.ts +2
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | * stranger's header: no page, no API route and no git door knows them. |
| 10 | 10 | */ |
| 11 | 11 | |
| 12 | import { noteRunnerReport } from "../../machines/report.ts"; | |
| 12 | 13 | import { noteUse } from "../../machines/agent_use.ts"; |
| 13 | 14 | import { tellRunners } from "../../machines/runner_signal.ts"; |
| 14 | 15 | import { dropHands, takeHand } from "../../checks/runner_hands.ts"; |
| @@ -279,6 +280,7 @@ export function runnerRoutes(router: Router<Handler>, record = true): void { | ||
| 279 | 280 | if (runner.wasQuiet === true) tellRunners(ctx.app, "seen", runner.id); |
| 280 | 281 | noteRunnerJobs(ctx.app.db, runner.id, input.jobs); |
| 281 | 282 | noteRunnerMachine(ctx.app.db, runner.id, input.machine); |
| 283 | noteRunnerReport(ctx.app.db, runner.id, input.machine); | |
| 282 | 284 | const wait = |
| 283 | 285 | Math.min(Math.max(Number(input.wait) || 0, 0), CLAIM_WAIT_MAX_S) * 1000; |
| 284 | 286 | const until = Date.now() + wait; |
src/http/lazy_lists.ts +4
| @@ -26,6 +26,8 @@ export const SETTINGS_ROUTES = [ | ||
| 26 | 26 | ["POST", "/settings/trusted/stop"], |
| 27 | 27 | ["POST", "/settings/trusted/revert"], |
| 28 | 28 | ["POST", "/settings/trusted/:id/remove"], |
| 29 | ["GET", "/settings/machines"], | |
| 30 | ["POST", "/settings/machines"], | |
| 29 | 31 | ["GET", "/settings/runners"], |
| 30 | 32 | ["GET", "/settings/runners/live"], |
| 31 | 33 | ["POST", "/settings/runners/:id/remove"], |
| @@ -1083,6 +1085,8 @@ export const REPO_SETTINGS_ROUTES = [ | ||
| 1083 | 1085 | ["GET", "/:owner/:name/settings/app/statement"], |
| 1084 | 1086 | ["GET", "/:owner/:name/settings/app/statement.csv"], |
| 1085 | 1087 | ["GET", "/:owner/:name/settings/machines"], |
| 1088 | ["POST", "/:owner/:name/settings/machines/:id/allow"], | |
| 1089 | ["POST", "/:owner/:name/settings/machines/:id/refuse"], | |
| 1086 | 1090 | ["GET", "/:owner/:name/machines/:machine/shell"], |
| 1087 | 1091 | ["POST", "/:owner/:name/settings/app"], |
| 1088 | 1092 | ["POST", "/:owner/:name/settings/app/disable"], |
src/http/marks/settings.json +1
src/http/routes/repo_settings.ts +3
| @@ -10,6 +10,7 @@ import { appSecretGrant, appSecretRevoke } from "../../web/pages/app_secrets.ts" | ||
| 10 | 10 | import { crewDevicesPage, crewDeviceAdd, crewDeviceGrant, crewDeviceRemove } from "../../web/pages/crew_devices.ts"; |
| 11 | 11 | import { crewSettingsPage, crewSeatFragment, crewAdd, crewSubscriptionsSave, crewRemove, crewRoleUpdate, pillarUpdate } from "../../web/pages/crew-settings.ts"; |
| 12 | 12 | import { forgeTemplateUpdate } from "../../web/pages/forge-template-setting.ts"; |
| 13 | import { machineAllow, machineRefuse } from "../../web/pages/machine-allow.ts"; | |
| 13 | 14 | import { machinesSettingsPage, machineShellPage } from "../../web/pages/machines.ts"; |
| 14 | 15 | import { promptsSettingsPage, promptSourceAdd, promptSourceRun, promptSourceDelete } from "../../web/pages/prompts.ts"; |
| 15 | 16 | import { proposalTokenMint, proposalTokenRevoke, contributeOpenSet, reportsOpenSet, contributeTokenRevoke } from "../../web/pages/proposal-tokens.ts"; |
| @@ -76,6 +77,8 @@ export function repoSettingsRoutes(router: Router<Handler>): void { | ||
| 76 | 77 | router.add("GET", "/:owner/:name/settings/app/statement", statementPage); |
| 77 | 78 | router.add("GET", "/:owner/:name/settings/app/statement.csv", statementCsvDownload); |
| 78 | 79 | router.add("GET", "/:owner/:name/settings/machines", machinesSettingsPage); |
| 80 | router.add("POST", "/:owner/:name/settings/machines/:id/allow", machineAllow); | |
| 81 | router.add("POST", "/:owner/:name/settings/machines/:id/refuse", machineRefuse); | |
| 79 | 82 | // The shell page; an upgrade at the same path is the socket (`machines/shell.ts`). |
| 80 | 83 | router.add("GET", "/:owner/:name/machines/:machine/shell", machineShellPage); |
| 81 | 84 | router.add("POST", "/:owner/:name/settings/app", appSettingsUpdate); |
src/http/settings_routes.ts +3
| @@ -27,6 +27,7 @@ import { paymentsCsv, paymentsPage } from "../web/pages/payments.ts"; | ||
| 27 | 27 | import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts"; |
| 28 | 28 | import { economicsPage, economicsSet } from "../web/pages/economics.ts"; |
| 29 | 29 | import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts"; |
| 30 | import { ownMachineAdd, ownMachinesPage } from "../web/pages/own-machines.ts"; | |
| 30 | 31 | import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnerTab, runnerTrust, runnersLive, runnersPage } from "../web/pages/runners.ts"; |
| 31 | 32 | import { usagePage } from "../web/pages/usage.ts"; |
| 32 | 33 | import { spendPage } from "../web/pages/spend-tab.ts"; |
| @@ -177,6 +178,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 177 | 178 | router.add("POST", "/settings/trusted/stop", trustedStop); |
| 178 | 179 | router.add("POST", "/settings/trusted/revert", trustedRevert); |
| 179 | 180 | router.add("POST", "/settings/trusted/:id/remove", trustedRemove); |
| 181 | router.add("GET", "/settings/machines", ownMachinesPage); | |
| 182 | router.add("POST", "/settings/machines", ownMachineAdd); | |
| 180 | 183 | router.add("GET", "/settings/runners", runnersPage); |
| 181 | 184 | router.add("GET", "/settings/runners/live", runnersLive); |
| 182 | 185 | router.add("POST", "/settings/runners/:id/remove", runnerRemove); |
src/machines/own.ts added +90
| @@ -0,0 +1,90 @@ | ||
| 1 | /** | |
| 2 | * A member's own machines (#18505). A member adds one (`machine.add`), and it is theirs: listed | |
| 3 | * under their name, taking nothing until a repository's owner allows it (`machine.allow`, one | |
| 4 | * row on that repository's settings). A repository that never allowed it, or refused it, is never | |
| 5 | * sent to it (`checks/runner_jobs.ts` `claimJob`, `labelServed`, in the claim's own query). Trust | |
| 6 | * for secrets is a different decision, an admin's (`machine.trust`, `actions/environments.ts`). | |
| 7 | * Each of the three asks `may()` and nothing else, and each is an event. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { App } from "../app.ts"; | |
| 11 | import { enrolRunner, getRunner, LABEL_RE, MAX_LABELS, type Enrolled } from "../checks/runner_jobs.ts"; | |
| 12 | import { may } from "../core/may.ts"; | |
| 13 | import { principalOfUser } from "../core/principal.ts"; | |
| 14 | import type { Repo } from "../core/repos.ts"; | |
| 15 | import type { User } from "../core/users.ts"; | |
| 16 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 17 | ||
| 18 | /** How many machines one member may hold. */ | |
| 19 | export const MAX_OWN = 8; | |
| 20 | ||
| 21 | /** | |
| 22 | * Add a machine: a name and the labels its owner says it holds. The token is returned once. The | |
| 23 | * labels are the owner's word; what the machine reports only narrows them (`report.ts`). | |
| 24 | */ | |
| 25 | export function addMachine( | |
| 26 | app: App, | |
| 27 | actor: User | undefined, | |
| 28 | name: string, | |
| 29 | labels: readonly string[], | |
| 30 | ): Result<{ machine: Enrolled; token: string }, "not_found" | { invalid: string }> { | |
| 31 | if (actor === undefined || !may(app.db, principalOfUser(actor), "machine.add").ok) return err("not_found"); | |
| 32 | const clean = name.trim(); | |
| 33 | if (clean === "" || clean.length > 40 || /[^\x21-\x7e]/.test(clean)) return err({ invalid: "name: 1 to 40 characters, no spaces" }); | |
| 34 | if (clean.startsWith("lent-") || clean.startsWith("local-")) return err({ invalid: "name: lent- and local- are the forge's own" }); | |
| 35 | const held = [...new Set(labels)]; | |
| 36 | if (held.length > MAX_LABELS || held.some((l) => !LABEL_RE.test(l))) | |
| 37 | return err({ invalid: `labels: at most ${MAX_LABELS}, each lower-case letters, digits, . _ - (up to 32)` }); | |
| 38 | if (ownedBy(app, actor.id).length >= MAX_OWN) return err({ invalid: `at most ${MAX_OWN} machines each` }); | |
| 39 | const made = enrolRunner(app.db, clean, actor.id, undefined, Date.now(), { labels: held, repos: [] }); | |
| 40 | app.db.query("UPDATE check_runner SET owner_id = ?2 WHERE id = ?1").run(made.runner.id, actor.id); | |
| 41 | app.bus.append({ kind: "machine.added", actorId: actor.id, payload: { id: made.runner.id, name: made.runner.name, labels: held } }); | |
| 42 | return ok({ machine: { ...made.runner, ownerId: actor.id }, token: made.token }); | |
| 43 | } | |
| 44 | ||
| 45 | /** The machines a member added, newest last. */ | |
| 46 | export function ownedBy(app: App, ownerId: string): Enrolled[] { | |
| 47 | const ids = app.db.query<{ id: string }, [string]>("SELECT id FROM check_runner WHERE owner_id = ?1 AND revoked_at = 0 ORDER BY id").all(ownerId); | |
| 48 | return ids.flatMap(({ id }) => getRunner(app.db, id) ?? []); | |
| 49 | } | |
| 50 | ||
| 51 | /** A member's machine as a repository's settings list it: whose, and what this repository said. */ | |
| 52 | export interface MachineRow { | |
| 53 | readonly id: string; | |
| 54 | readonly name: string; | |
| 55 | readonly ownerName: string; | |
| 56 | readonly allowed: boolean; | |
| 57 | } | |
| 58 | ||
| 59 | /** | |
| 60 | * Every member's machine with this repository's answer; a machine nobody answered for is refused. | |
| 61 | */ | |
| 62 | export function machinesFor(app: App, repo: Repo): MachineRow[] { | |
| 63 | return app.db | |
| 64 | .query<{ id: string; name: string; owner: string; allowed: number | null }, [string]>( | |
| 65 | `SELECT c.id, c.name, COALESCE(u.username, '') AS owner, m.allowed AS allowed | |
| 66 | FROM check_runner c LEFT JOIN user u ON u.id = c.owner_id | |
| 67 | LEFT JOIN repo_machine m ON m.runner_id = c.id AND m.repo_id = ?1 | |
| 68 | WHERE c.owner_id != '' AND c.revoked_at = 0 ORDER BY c.id LIMIT 200`, | |
| 69 | ) | |
| 70 | .all(repo.id) | |
| 71 | .map((r) => ({ id: r.id, name: r.name, ownerName: r.owner, allowed: r.allowed === 1 })); | |
| 72 | } | |
| 73 | ||
| 74 | /** | |
| 75 | * A repository's owner allows or refuses a machine. Asking `machine.allow` over the repository: a | |
| 76 | * person who cannot administer it is told it is not there. | |
| 77 | */ | |
| 78 | export function allowMachine(app: App, actor: User | undefined, repo: Repo, runnerId: string, allowed: boolean): Result<Enrolled, "not_found"> { | |
| 79 | if (actor === undefined || !may(app.db, principalOfUser(actor), "machine.allow", { repo }).ok) return err("not_found"); | |
| 80 | const machine = getRunner(app.db, runnerId); | |
| 81 | if (machine === undefined || machine.ownerId === "" || machine.revokedAt !== 0) return err("not_found"); | |
| 82 | app.db | |
| 83 | .query( | |
| 84 | `INSERT INTO repo_machine (repo_id, runner_id, allowed, by, at) VALUES (?1, ?2, ?3, ?4, ?5) | |
| 85 | ON CONFLICT (repo_id, runner_id) DO UPDATE SET allowed = ?3, by = ?4, at = ?5`, | |
| 86 | ) | |
| 87 | .run(repo.id, runnerId, allowed ? 1 : 0, actor.username, Date.now()); | |
| 88 | app.bus.append({ kind: allowed ? "machine.allowed" : "machine.refused", actorId: actor.id, repoId: repo.id, payload: { id: runnerId, name: machine.name } }); | |
| 89 | return ok(machine); | |
| 90 | } |
src/machines/report.ts added +100
| @@ -0,0 +1,100 @@ | ||
| 1 | /** | |
| 2 | * What a machine says of itself (#18505): its operating system, architecture, and whether it has | |
| 3 | * Docker and Xcode. The report only ever narrows routing. A label its owner gave it (`macos`, | |
| 4 | * `arm64`, `docker`, `xcode`) is dropped while the report contradicts it, so a job naming that | |
| 5 | * label is not sent there; the report never adds a label, never marks a machine trusted, and | |
| 6 | * never widens which repositories it serves. Trust is a person's decision (`machine.trust`, | |
| 7 | * `checks/environment.ts` `trustRunner`), and nothing here reads or writes it. | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | ||
| 12 | export interface Report { | |
| 13 | readonly os?: "darwin" | "linux" | "windows"; | |
| 14 | readonly arch?: "arm64" | "x64"; | |
| 15 | readonly docker?: boolean; | |
| 16 | readonly xcode?: boolean; | |
| 17 | } | |
| 18 | ||
| 19 | const OS = ["darwin", "linux", "windows"] as const; | |
| 20 | const ARCH = ["arm64", "x64"] as const; | |
| 21 | ||
| 22 | /** | |
| 23 | * A report from anything a machine sent: the four known facts, each of a known kind, and no more. | |
| 24 | */ | |
| 25 | export function readReport(said: unknown): Report { | |
| 26 | if (typeof said !== "object" || said === null) return {}; | |
| 27 | const m = said as Record<string, unknown>; | |
| 28 | const os = OS.find((v) => v === m["os"]); | |
| 29 | const arch = ARCH.find((v) => v === m["arch"]); | |
| 30 | return { | |
| 31 | ...(os === undefined ? {} : { os }), | |
| 32 | ...(arch === undefined ? {} : { arch }), | |
| 33 | ...(typeof m["docker"] === "boolean" ? { docker: m["docker"] } : {}), | |
| 34 | ...(typeof m["xcode"] === "boolean" ? { xcode: m["xcode"] } : {}), | |
| 35 | }; | |
| 36 | } | |
| 37 | ||
| 38 | /** A report as kept in its column; a column that is not one is no report. */ | |
| 39 | export function parseReport(raw: string): Report { | |
| 40 | try { | |
| 41 | return readReport(JSON.parse(raw)); | |
| 42 | } catch { | |
| 43 | return {}; | |
| 44 | } | |
| 45 | } | |
| 46 | ||
| 47 | /** | |
| 48 | * Whether the report contradicts a label: said, and said otherwise. A fact not said contradicts | |
| 49 | * nothing. | |
| 50 | */ | |
| 51 | function contradicts(r: Report, label: string): boolean { | |
| 52 | switch (label) { | |
| 53 | case "macos": | |
| 54 | return r.os !== undefined && r.os !== "darwin"; | |
| 55 | case "linux": | |
| 56 | return r.os !== undefined && r.os !== "linux"; | |
| 57 | case "windows": | |
| 58 | return r.os !== undefined && r.os !== "windows"; | |
| 59 | case "arm64": | |
| 60 | return r.arch !== undefined && r.arch !== "arm64"; | |
| 61 | case "x64": | |
| 62 | return r.arch !== undefined && r.arch !== "x64"; | |
| 63 | case "docker": | |
| 64 | return r.docker === false; | |
| 65 | case "xcode": | |
| 66 | return r.xcode === false; | |
| 67 | default: | |
| 68 | return false; | |
| 69 | } | |
| 70 | } | |
| 71 | ||
| 72 | /** The labels its owner gave it that its report does not contradict: a subset, never more. */ | |
| 73 | export function heldLabels(labelsJson: string, reportJson: string): string[] { | |
| 74 | let labels: unknown; | |
| 75 | try { | |
| 76 | labels = JSON.parse(labelsJson); | |
| 77 | } catch { | |
| 78 | return []; | |
| 79 | } | |
| 80 | if (!Array.isArray(labels)) return []; | |
| 81 | const report = parseReport(reportJson); | |
| 82 | return labels.filter((l): l is string => typeof l === "string" && !contradicts(report, l)); | |
| 83 | } | |
| 84 | ||
| 85 | /** Keep what a claim's `machine` says; an unchanged report writes nothing. */ | |
| 86 | export function noteRunnerReport(db: Database, runnerId: string, said: unknown): void { | |
| 87 | const report = JSON.stringify(readReport(said)); | |
| 88 | db.query("UPDATE check_runner SET report = ?2 WHERE id = ?1 AND report != ?2").run(runnerId, report); | |
| 89 | } | |
| 90 | ||
| 91 | /** The report in words, for the page and the terminal; "" when nothing was said. */ | |
| 92 | export function reportWords(r: Report): string { | |
| 93 | const parts = [ | |
| 94 | ...(r.os === undefined ? [] : [r.os]), | |
| 95 | ...(r.arch === undefined ? [] : [r.arch]), | |
| 96 | ...(r.docker === undefined ? [] : [r.docker ? "docker" : "no docker"]), | |
| 97 | ...(r.xcode === undefined ? [] : [r.xcode ? "xcode" : "no xcode"]), | |
| 98 | ]; | |
| 99 | return parts.join(", "); | |
| 100 | } |
src/tui/forge_parts.ts +9 −1
| @@ -91,7 +91,7 @@ import { passkeysScreen } from "./screens/passkeys.ts"; | ||
| 91 | 91 | import { confirmsScreen } from "./screens/confirms.ts"; |
| 92 | 92 | import { receiptsScreen } from "./screens/receipts.ts"; |
| 93 | 93 | import { trustedScreen } from "./screens/trusted.ts"; |
| 94 | import { runnersScreen } from "./screens/runners.ts"; | |
| 94 | import { ownMachinesScreen, runnersScreen } from "./screens/runners.ts"; | |
| 95 | 95 | import { proposalTokensPrompt } from "./screens/proposal_tokens.ts"; |
| 96 | 96 | import { signInsScreen } from "./screens/signins.ts"; |
| 97 | 97 | import { oauthGrantsScreen } from "./screens/oauthgrants.ts"; |
| @@ -545,6 +545,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] { | ||
| 545 | 545 | hint: "the machines that take this forge's checks; x removes a hand-made one", |
| 546 | 546 | run: () => ctx.push(runnersScreen(session, ctx)), |
| 547 | 547 | }); |
| 548 | // A member's own machines, as Settings → Your machines lists them (#18505). | |
| 549 | if (session.signedIn && holds(session.db, principalOfUser(session.user), "machine.add")) | |
| 550 | commands.push({ | |
| 551 | id: "own-machines", | |
| 552 | title: "Your machines", | |
| 553 | hint: "the machines you added; n adds one", | |
| 554 | run: () => ctx.push(ownMachinesScreen(session, ctx)), | |
| 555 | }); | |
| 548 | 556 | // The forge's agent keeps many conversations, as /talk lists them (#8814). |
| 549 | 557 | if (session.signedIn && session.user?.kind !== "agent") |
| 550 | 558 | commands.push({ |
src/tui/screens/machines.ts +18 −3
| @@ -7,6 +7,9 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import { readMachine } from "../../actions/disk_readings.ts"; |
| 10 | import { holds } from "../../core/may.ts"; | |
| 11 | import { principalOfUser } from "../../core/principal.ts"; | |
| 12 | import { allowMachine, machinesFor } from "../../machines/own.ts"; | |
| 10 | 13 | import { canWrite, type Repo } from "../../core/repos.ts"; |
| 11 | 14 | import { repoMachines } from "../../crew/machines_read.ts"; |
| 12 | 15 | import type { Machine } from "../../crew/machines.ts"; |
| @@ -58,9 +61,14 @@ export function machinesScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 58 | 61 | let disks: string[] = []; |
| 59 | 62 | const may = (): boolean => f.user !== undefined && canWrite(f.db, repo, f.user); |
| 60 | 63 | const rows = (): SessionRecord[] => (may() ? lastSessions(f.db, repo.id) : []); |
| 64 | // Members' machines, the repository's administrator's to allow (`machine.allow`, #18505). | |
| 65 | const decides = (): boolean => f.user !== undefined && holds(f.db, principalOfUser(f.user), "machine.allow", { repo }); | |
| 66 | const members = () => (decides() ? machinesFor(f.app, repo) : []); | |
| 67 | const memberRows = (): ListRow[] => | |
| 68 | members().map((m) => ({ title: `${m.name} · ${m.ownerName === "" ? "a member" : m.ownerName}`, secondary: m.allowed ? "allowed" : "refused", meta: "a member's machine" })); | |
| 61 | 69 | return { |
| 62 | 70 | title: "The crew's machines", |
| 63 | keys: [binding(["j", "k"], "move cursor"), binding(["esc"], "back")], | |
| 71 | keys: [binding(["j", "k"], "move cursor"), binding(["a"], "allow a member's machine"), binding(["x"], "refuse it"), binding(["esc"], "back")], | |
| 64 | 72 | async load() { |
| 65 | 73 | if (may()) { |
| 66 | 74 | machines = (await repoMachines(f.app, repo)).machines; |
| @@ -84,10 +92,17 @@ export function machinesScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | ||
| 84 | 92 | lines.forEach((line, i) => |
| 85 | 93 | s.text(head!.x, head!.y + i, truncate(line, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w), |
| 86 | 94 | ); |
| 87 | drawList(s, list!, c, state, listed.map(sessionRow)); | |
| 95 | drawList(s, list!, c, state, [...memberRows(), ...listed.map(sessionRow)]); | |
| 88 | 96 | }, |
| 89 | 97 | key(e) { |
| 90 | return state.key(e, rows().length); | |
| 98 | const at = members()[state.index]; | |
| 99 | if (at !== undefined && !e.ctrl && !e.alt && (e.key === "a" || e.key === "x")) { | |
| 100 | const done = allowMachine(f.app, f.user, repo, at.id, e.key === "a"); | |
| 101 | ctx.toast(done.ok ? (e.key === "a" ? `${at.name} may take this repository's runs.` : `${at.name} takes none of this repository's runs.`) : "That is not a member's machine.", done.ok ? "success" : "danger"); | |
| 102 | ctx.invalidate(); | |
| 103 | return true; | |
| 104 | } | |
| 105 | return state.key(e, members().length + rows().length); | |
| 91 | 106 | }, |
| 92 | 107 | }; |
| 93 | 108 | } |
src/tui/screens/runners.ts +64 −1
| @@ -18,6 +18,8 @@ import { yieldNote, yieldState } from "../../checks/lent_yield.ts"; | ||
| 18 | 18 | import { runnerLines } from "../../machines/live_runners.ts"; |
| 19 | 19 | import { protocolWordsFor } from "../../machines/agent_use.ts"; |
| 20 | 20 | import { heldByRunner, lentIn, workByRunner, type Enrolled, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts"; |
| 21 | import { addMachine, ownedBy } from "../../machines/own.ts"; | |
| 22 | import { parseReport, reportWords } from "../../machines/report.ts"; | |
| 21 | 23 | import type { Ctx, Screen } from "../app/app.ts"; |
| 22 | 24 | import { binding } from "../app/keys.ts"; |
| 23 | 25 | import { style } from "../term/style.ts"; |
| @@ -37,7 +39,7 @@ function lendingLine(f: Session): string { | ||
| 37 | 39 | } |
| 38 | 40 | |
| 39 | 41 | /** A lent runner that still works: `x` revokes it rather than removing its ledger. */ |
| 40 | const revocable = (r: Enrolled): boolean => (r.scope !== undefined || r.labels.length > 0) && r.revokedAt === 0; | |
| 42 | const revocable = (r: Enrolled): boolean => (r.scope !== undefined || r.labels.length > 0 || r.ownerId !== "") && r.revokedAt === 0; | |
| 41 | 43 | |
| 42 | 44 | const stateWords = (r: Enrolled, now: number): string => |
| 43 | 45 | r.revokedAt !== 0 ? "revoked" : r.paused !== "" ? "paused" : STATE_WORDS[runnerState(r.seenAt, now, r.kind)]; |
| @@ -280,3 +282,64 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen { | ||
| 280 | 282 | }; |
| 281 | 283 | return screen; |
| 282 | 284 | } |
| 285 | ||
| 286 | /** | |
| 287 | * Your machines in the terminal (#18505), beside Settings → Your machines: the ones you added; `n` | |
| 288 | * adds one. A machine takes nothing until a repository's owner allows it, and is sent no secrets | |
| 289 | * until an admin trusts it. | |
| 290 | */ | |
| 291 | export function ownMachinesScreen(f: Session, ctx: Ctx): Screen { | |
| 292 | const state = new ListState(); | |
| 293 | const mine = () => (f.user === undefined ? [] : ownedBy(f.app, f.user.id)); | |
| 294 | const rows = (): ListRow[] => | |
| 295 | mine().map((m) => { | |
| 296 | const said = reportWords(parseReport(f.db.query<{ r: string }, [string]>("SELECT report AS r FROM check_runner WHERE id = ?1").get(m.id)?.r ?? "{}")); | |
| 297 | return { | |
| 298 | title: m.name, | |
| 299 | secondary: m.trusted ? "trusted" : "not trusted", | |
| 300 | meta: `${m.seenAt === 0 ? "never asked" : "seen " + new Date(m.seenAt).toISOString().slice(0, 16).replace("T", " ")} · labels ${m.labels.length === 0 ? "none" : m.labels.join(",")}${said === "" ? "" : ` · said ${said}`}`, | |
| 301 | }; | |
| 302 | }); | |
| 303 | const screen: Screen = { | |
| 304 | title: "Your machines", | |
| 305 | keys: [binding(["j", "k"], "move cursor"), binding(["n"], "add a machine"), binding(["esc"], "back")], | |
| 306 | render(area, s) { | |
| 307 | const c = ctx.theme.c; | |
| 308 | const [head, list] = split(area, "v", [len(2), fill(1)]); | |
| 309 | const lines = ["A machine takes a run only for a repository whose owner allowed it.", "It is sent no secrets until an admin marks it trusted."]; | |
| 310 | lines.forEach((line, i) => s.text(head!.x, head!.y + i, truncate(line, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w)); | |
| 311 | drawList(s, list!, c, state, rows()); | |
| 312 | }, | |
| 313 | key(e) { | |
| 314 | if (e.ctrl || e.alt) return false; | |
| 315 | if (state.key(e, mine().length)) return true; | |
| 316 | if (e.key !== "n") return false; | |
| 317 | ctx.push( | |
| 318 | promptScreen(ctx, screen, { | |
| 319 | title: "Add a machine", | |
| 320 | label: "A name, then its labels (comma-separated)", | |
| 321 | placeholder: "my-mac macos,arm64", | |
| 322 | onSubmit: (value) => { | |
| 323 | const [name, labels] = value.trim().split(/\s+/); | |
| 324 | const made = addMachine(f.app, f.user, name ?? "", (labels ?? "").split(",").filter((w) => w !== "")); | |
| 325 | if (!made.ok) return made.error === "not_found" ? "Your account may not add a machine." : `Not added: ${made.error.invalid}.`; | |
| 326 | ctx.invalidate(); | |
| 327 | return Promise.resolve().then(() => | |
| 328 | ctx.push( | |
| 329 | confirmScreen(ctx, screen, { | |
| 330 | title: `Machine ${made.value.machine.name} added`, | |
| 331 | body: ["Its token, shown this once:", made.value.token], | |
| 332 | actions: [{ label: "Done" }], | |
| 333 | onChoose: () => {}, | |
| 334 | width: 80, | |
| 335 | }), | |
| 336 | ), | |
| 337 | ); | |
| 338 | }, | |
| 339 | }), | |
| 340 | ); | |
| 341 | return true; | |
| 342 | }, | |
| 343 | }; | |
| 344 | return screen; | |
| 345 | } |
src/web/pages/machine-allow.ts added +65
| @@ -0,0 +1,65 @@ | ||
| 1 | /** | |
| 2 | * The row on a repository's Machines settings (#18505) where its owner allows or refuses each | |
| 3 | * member's machine. Refused is the answer until one is given: a machine takes a run only here | |
| 4 | * where it was allowed. The rules are `machines/own.ts` `allowMachine`'s, asked of `may()` as | |
| 5 | * `machine.allow`; the terminal screen (`tui/screens/machines.ts`) calls the same. | |
| 6 | */ | |
| 7 | import { machinesFor, allowMachine } from "../../machines/own.ts"; | |
| 8 | import { holds } from "../../core/may.ts"; | |
| 9 | import { principalOf } from "../../core/principal.ts"; | |
| 10 | import type { Repo } from "../../core/repos.ts"; | |
| 11 | import type { Ctx } from "../../http/context.ts"; | |
| 12 | import { forbiddenPage, loadRepo, NOT_YOURS_TO_DO, repoBase, repoNotFound } from "../chrome.ts"; | |
| 13 | import { readForm } from "../form.ts"; | |
| 14 | import { html, type Html } from "../html.ts"; | |
| 15 | import { flashTo } from "../layout.ts"; | |
| 16 | import { emptyLine } from "../empty_words.ts"; | |
| 17 | import { badge, btn, icon, row, rowList } from "../ui.ts"; | |
| 18 | ||
| 19 | /** The section, or null when the viewer may not decide it. */ | |
| 20 | export function machineAllowSection(ctx: Ctx, repo: Repo): Html | null { | |
| 21 | if (!holds(ctx.app.db, principalOf(ctx.auth), "machine.allow", { repo })) return null; | |
| 22 | const base = repoBase(repo); | |
| 23 | const machines = machinesFor(ctx.app, repo); | |
| 24 | const form = (id: string, verb: "allow" | "refuse", label: string, aria: string) => | |
| 25 | html`<form class="row-fields" method="post" action="${base}/settings/machines/${id}/${verb}">${btn(label, { size: "sm", variant: "outline", label: aria })}</form>`; | |
| 26 | return html`<section class="settings-block" id="member-machines"> | |
| 27 | <h2>Members' machines</h2> | |
| 28 | <p class="muted small">A member's machine takes a run of this repository only when you allow it here; until then it is refused.</p> | |
| 29 | ${machines.length === 0 | |
| 30 | ? emptyLine("memberMachines") | |
| 31 | : rowList( | |
| 32 | machines.map((m) => | |
| 33 | row({ | |
| 34 | lead: icon("activity"), | |
| 35 | title: html`${m.name} ${m.allowed ? badge("Allowed", { variant: "secondary", icon: "check" }) : badge("Refused", { variant: "outline" })}`, | |
| 36 | meta: html`${m.ownerName === "" ? "a member" : m.ownerName}'s machine`, | |
| 37 | trail: m.allowed ? form(m.id, "refuse", "Refuse", `Refuse ${m.name} for this repository`) : form(m.id, "allow", "Allow", `Allow ${m.name} for this repository`), | |
| 38 | data: { machine: m.name }, | |
| 39 | }), | |
| 40 | ), | |
| 41 | { bare: true, label: "Members' machines" }, | |
| 42 | )} | |
| 43 | </section>`; | |
| 44 | } | |
| 45 | ||
| 46 | const decide = (allowed: boolean) => async (ctx: Ctx): Promise<Response> => { | |
| 47 | const repo = loadRepo(ctx); | |
| 48 | if (!repo) return repoNotFound(ctx); | |
| 49 | const form = await readForm(ctx, "rw"); | |
| 50 | if (form instanceof Response) return form; | |
| 51 | if (!holds(ctx.app.db, principalOf(ctx.auth), "machine.allow", { repo })) return forbiddenPage(ctx, NOT_YOURS_TO_DO); | |
| 52 | const done = allowMachine(ctx.app, ctx.auth.user, repo, ctx.params.id ?? "", allowed); | |
| 53 | return flashTo( | |
| 54 | ctx, | |
| 55 | `${repoBase(repo)}/settings/machines-machines`, | |
| 56 | done.ok | |
| 57 | ? { message: allowed ? `${done.value.name} may take this repository's runs.` : `${done.value.name} takes none of this repository's runs.` } | |
| 58 | : { tone: "danger", message: "That is not a member's machine." }, | |
| 59 | ); | |
| 60 | }; | |
| 61 | ||
| 62 | // POST /:owner/:name/settings/machines/:id/allow | |
| 63 | export const machineAllow = decide(true); | |
| 64 | // POST /:owner/:name/settings/machines/:id/refuse | |
| 65 | export const machineRefuse = decide(false); |
src/web/pages/machines.ts +2 −1
| @@ -36,6 +36,7 @@ import { readMachine } from "../../actions/disk_readings.ts"; | ||
| 36 | 36 | import { WEAR_ALERT_PERCENT } from "../../machines/disk_health.ts"; |
| 37 | 37 | import type { DeviceSummary } from "../../machines/disk_readings.ts"; |
| 38 | 38 | import { ghosttyWasmAsset, machineTermAsset } from "../machine-term-asset.ts"; |
| 39 | import { machineAllowSection } from "./machine-allow.ts"; | |
| 39 | 40 | import { settingsPageResponse } from "./settings.ts"; |
| 40 | 41 | |
| 41 | 42 | /** The shell page's own rules: a terminal box that fills the window below the head and never moves. */ |
| @@ -189,7 +190,7 @@ function render(ctx: Ctx, repo: Repo, list: readonly Machine[], sessions: readon | ||
| 189 | 190 | )} |
| 190 | 191 | </ul>`} |
| 191 | 192 | </section>`; |
| 192 | const body = html`${machines}${ctx.auth.user?.isAdmin === true ? html`<p class="small"><a href="/infra">Machines on your cloud</a></p>` : null}${recent}`; | |
| 193 | const body = html`${machines}${machineAllowSection(ctx, repo)}${ctx.auth.user?.isAdmin === true ? html`<p class="small"><a href="/infra">Machines on your cloud</a></p>` : null}${recent}`; | |
| 193 | 194 | // The settings frame and its sections are an admin's; a writer who is not |
| 194 | 195 | // one sees this pane alone, so no link offers them a page that refuses. |
| 195 | 196 | if (canAdmin(ctx.app.db, repo, ctx.auth.user)) |
src/web/pages/origins.ts +2
| @@ -125,6 +125,7 @@ export type AccountSection = | ||
| 125 | 125 | | "accounts" |
| 126 | 126 | | "trusted" |
| 127 | 127 | | "runners" |
| 128 | | "machines" | |
| 128 | 129 | | "people" |
| 129 | 130 | | "subscriptions" |
| 130 | 131 | | "backups" |
| @@ -175,6 +176,7 @@ const SECTION_ROWS: readonly (readonly [ | ||
| 175 | 176 | ["Account", "Connected agents", "/settings/grants", "bot", (c) => c === "grants", false], |
| 176 | 177 | ["Account", "Who may do what", "/settings/who-can", "users", (c) => c === "who-can", false], |
| 177 | 178 | ["Account", "Confirms", "/settings/confirms", "check", (c) => c === "confirms", false], |
| 179 | ["Account", "Your machines", "/settings/machines", "activity", (c) => c === "machines", false], | |
| 178 | 180 | ["Account", "Brought in", "/settings/bring", "download", (c) => c === "bring", false], |
| 179 | 181 | ["Crew and AI", "Model", "/settings/model", "key", (c) => c === "model", false], |
| 180 | 182 | ["Crew and AI", "Crew", "/settings/crew", "bot", (c) => c === "crew", true], |
src/web/pages/own-machines.ts added +90
| @@ -0,0 +1,90 @@ | ||
| 1 | /** | |
| 2 | * Settings → Your machines (#18505), for any member: add a machine of your own and see the ones | |
| 3 | * you added. A machine takes nothing until a repository's owner allows it (on that repository's | |
| 4 | * Machines settings), and is sent no secrets until an admin marks it trusted; the page says both. | |
| 5 | * The rules are `machines/own.ts`'s, the ones `docs/features/own-machines.md` and the terminal | |
| 6 | * screen share. | |
| 7 | */ | |
| 8 | import { addMachine, ownedBy } from "../../machines/own.ts"; | |
| 9 | import { parseReport, reportWords } from "../../machines/report.ts"; | |
| 10 | import { holds } from "../../core/may.ts"; | |
| 11 | import { principalOf } from "../../core/principal.ts"; | |
| 12 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; | |
| 13 | import type { Ctx } from "../../http/context.ts"; | |
| 14 | import { signedInPage } from "../../http/page_may.ts"; | |
| 15 | import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts"; | |
| 16 | import { field, readForm } from "../form.ts"; | |
| 17 | import { html } from "../html.ts"; | |
| 18 | import { flashTo, page } from "../layout.ts"; | |
| 19 | import { emptyLine } from "../empty_words.ts"; | |
| 20 | import { badge, btn, field as formField, icon, row, rowList, time } from "../ui.ts"; | |
| 21 | import { sshOn } from "../../settings/ssh.ts"; | |
| 22 | import { accountSections } from "./origins.ts"; | |
| 23 | import type { Enrolled } from "../../checks/runner_jobs.ts"; | |
| 24 | import type { App } from "../../app.ts"; | |
| 25 | ||
| 26 | const HERE = "/settings/machines"; | |
| 27 | ||
| 28 | /** | |
| 29 | * A machine's row: its name, whether it was seen, what it said it is, and whether an admin trusts | |
| 30 | * it. | |
| 31 | */ | |
| 32 | function machineRow(app: App, m: Enrolled) { | |
| 33 | const said = reportWords(parseReport(app.db.query<{ r: string }, [string]>("SELECT report AS r FROM check_runner WHERE id = ?1").get(m.id)?.r ?? "{}")); | |
| 34 | return row({ | |
| 35 | lead: icon("activity"), | |
| 36 | title: html`${m.name} ${m.trusted ? badge("Trusted", { variant: "secondary", icon: "check" }) : badge("Not trusted", { variant: "outline" })}`, | |
| 37 | meta: html`${m.seenAt === 0 ? "Has not asked for work" : html`Last seen ${time(new Date(m.seenAt).toISOString())}`} · labels ${m.labels.length === 0 ? "none" : m.labels.join(", ")}${said === "" ? "" : ` · said ${said}`} · added ${time(m.createdAt, { date: true })}`, | |
| 38 | }); | |
| 39 | } | |
| 40 | ||
| 41 | // GET /settings/machines | |
| 42 | export function ownMachinesPage(ctx: Ctx): Response { | |
| 43 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 44 | if (!signedInPage(ctx)) return signInFirst(ctx); | |
| 45 | const user = ctx.auth.user; | |
| 46 | if (!holds(ctx.app.db, principalOf(ctx.auth), "machine.add")) return notFoundPage(ctx); | |
| 47 | const mine = ownedBy(ctx.app, user.id); | |
| 48 | const body = html`<section class="settings-block"> | |
| 49 | <h2>Your machines</h2> | |
| 50 | ${mine.length === 0 ? emptyLine("ownMachines") : rowList(mine.map((m) => machineRow(ctx.app, m)), { bare: true, label: "Your machines" })} | |
| 51 | </section> | |
| 52 | <section class="settings-block" id="add-machine"> | |
| 53 | <h2>Add a machine</h2> | |
| 54 | <form method="post" action="${HERE}" class="stack"> | |
| 55 | ${formField({ label: "Name", name: "name", required: true, maxlength: 40, placeholder: "my-mac", autocomplete: "off" })} | |
| 56 | ${formField({ label: "Labels it holds, separated by commas", name: "labels", mono: true, placeholder: "macos, arm64", autocomplete: "off" })} | |
| 57 | <div class="form-actions">${btn("Add machine", { variant: "primary" })}</div> | |
| 58 | </form> | |
| 59 | <p class="muted small">Assumptions: a machine takes a run only for a repository whose owner allowed it, on that repository's Machines settings. It is sent no secrets until an admin marks it trusted; what it says of itself (os, arch, docker, xcode) only narrows which jobs it is sent, never widens them.</p> | |
| 60 | </section>`; | |
| 61 | return timePhase(ctx.request, "render", () => | |
| 62 | page({ | |
| 63 | ctx, | |
| 64 | title: "Your machines", | |
| 65 | body: html`${pageHead("Your machines", { sub: "Machines you added to take checks, and which repositories let them." })} | |
| 66 | ${settingsLayout(accountSections("machines", { admin: ctx.auth.user.isAdmin, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`, | |
| 67 | }), | |
| 68 | ); | |
| 69 | } | |
| 70 | ||
| 71 | // POST /settings/machines | |
| 72 | export async function ownMachineAdd(ctx: Ctx): Promise<Response> { | |
| 73 | if (!signedInPage(ctx)) return signInFirst(ctx); | |
| 74 | const form = await readForm(ctx, "rw"); | |
| 75 | if (form instanceof Response) return form; | |
| 76 | const labels = field(form, "labels").split(",").map((w) => w.trim()).filter((w) => w !== ""); | |
| 77 | const made = addMachine(ctx.app, ctx.auth.user, field(form, "name"), labels); | |
| 78 | if (!made.ok) | |
| 79 | return flashTo(ctx, `${HERE}#add-machine`, { tone: "danger", message: made.error === "not_found" ? "Your account may not add a machine." : `Not added: ${made.error.invalid}.` }); | |
| 80 | // Shown once, here, never kept in a flash or a URL. | |
| 81 | const res = page({ | |
| 82 | ctx, | |
| 83 | title: "Machine added", | |
| 84 | body: html`${pageHead("Machine added", { sub: `${made.value.machine.name}: copy its token now; it is not shown again.` })} | |
| 85 | <section class="settings-block"><p><code class="mono" id="machine-token">${made.value.token}</code></p> | |
| 86 | <p class="muted small">Give it to the machine as its bearer token. It takes nothing until a repository's owner allows it. <a href="${HERE}">Back to your machines</a></p></section>`, | |
| 87 | }); | |
| 88 | res.headers.set("cache-control", "no-store"); | |
| 89 | return res; | |
| 90 | } |
src/web/pages/runners.ts +1 −1
| @@ -55,7 +55,7 @@ function runnerTrail(r: Enrolled) { | ||
| 55 | 55 | html`<form class="row-fields" method="post" action="${HERE}/${r.id}/${verb}"> |
| 56 | 56 | ${btn(label, { size: "sm", variant: "outline", label: `${label} runner ${r.name}` })} |
| 57 | 57 | </form>`; |
| 58 | if ((r.scope === undefined && r.labels.length === 0) || r.revokedAt !== 0) return form("remove", "Remove"); | |
| 58 | if ((r.scope === undefined && r.labels.length === 0 && r.ownerId === "") || r.revokedAt !== 0) return form("remove", "Remove"); | |
| 59 | 59 | return html`${r.trusted ? form("untrust", "Untrust") : form("trust", "Trust")}${r.paused === "" ? form("pause", "Pause") : form("resume", "Resume")}${form("revoke", "Revoke")}`; |
| 60 | 60 | } |
| 61 | 61 |
test/may.test.ts +3 −3
| @@ -155,8 +155,8 @@ test("the forge-wide actions follow the roles table", () => { | ||
| 155 | 155 | const can = (who: string | undefined, scope?: "ro" | "rw" | "admin") => capabilities(app.db, scope === undefined ? principalOfUser(as(who)) : bearer(as(who), scope)); |
| 156 | 156 | // No account may still make something as a visitor (`core/visitors.ts`, #18112). |
| 157 | 157 | expect(can(undefined)).toEqual(["forge.read", "visitor.make"]); |
| 158 | expect(can("gina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute"]); | |
| 159 | expect(can("nina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]); | |
| 158 | expect(can("gina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute", "machine.add"]); | |
| 159 | expect(can("nina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew", "machine.add"]); | |
| 160 | 160 | expect(can("boss")).toContain("forge.administer"); |
| 161 | 161 | expect(can("nina")).not.toContain("forge.administer"); |
| 162 | 162 | expect(can("boss", "ro")).toEqual(["forge.read"]); |
| @@ -172,7 +172,7 @@ const get = async (path: string, who?: string) => { | ||
| 172 | 172 | |
| 173 | 173 | test("GET /api/v1/user lists what the caller may do, by the registry's names", async () => { |
| 174 | 174 | const rw = await get("/api/v1/user", "wes:rw"); |
| 175 | expect(rw.body["can"]).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]); | |
| 175 | expect(rw.body["can"]).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew", "machine.add"]); | |
| 176 | 176 | expect((await get("/api/v1/user", "wes:ro")).body["can"]).toEqual(["forge.read"]); |
| 177 | 177 | }); |
| 178 | 178 |
test/own-machines-pages.test.ts added +87
| @@ -0,0 +1,87 @@ | ||
| 1 | /** | |
| 2 | * The pages of a member's own machine (#18505): a member adds one at /settings/machines and sees | |
| 3 | * it under their name; the repository's owner allows it on the repository's Machines settings; a | |
| 4 | * writer who does not administer sees no such row and cannot post it; a cross-origin post is | |
| 5 | * refused. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { createSession } from "../src/core/sessions.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { serve } from "../src/http/server.ts"; | |
| 16 | import { ownedBy, machinesFor } from "../src/machines/own.ts"; | |
| 17 | import { getRepo } from "../src/core/repos.ts"; | |
| 18 | import { seedAdmin } from "./helpers/admin.ts"; | |
| 19 | import { quietLogs } from "./helpers/globals.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | let dataDir = ""; | |
| 24 | let app: App; | |
| 25 | let alice: User; | |
| 26 | let bob: User; | |
| 27 | let servers: Awaited<ReturnType<typeof serve>>; | |
| 28 | ||
| 29 | beforeAll(async () => { | |
| 30 | dataDir = await mkdtemp(join(tmpdir(), "forge-own-machines-pages-")); | |
| 31 | app = createApp({ dataDir, port: 0, host: "forge.test" }); | |
| 32 | const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" }); | |
| 33 | if (!a.ok) throw new Error(a.error); | |
| 34 | alice = a.value; | |
| 35 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "correct-horse-battery" }); | |
| 36 | if (!b.ok) throw new Error(b.error); | |
| 37 | bob = b.value; | |
| 38 | const made = await createRepo(app, alice, { name: "lib", visibility: "public" }); | |
| 39 | if (!made.ok) throw new Error(JSON.stringify(made.error)); | |
| 40 | servers = await serve(app); | |
| 41 | }); | |
| 42 | ||
| 43 | afterAll(async () => { | |
| 44 | servers.stop(); | |
| 45 | app.close(); | |
| 46 | await rm(dataDir, { recursive: true, force: true }); | |
| 47 | }); | |
| 48 | ||
| 49 | const cookie = (who: User) => `forge_session=${createSession(app.db, who.id).token}`; | |
| 50 | const get = (who: User, path: string) => fetch(`${servers.url}${path}`, { headers: { cookie: cookie(who) } }); | |
| 51 | const post = (who: User, path: string, body = "", origin = servers.url) => | |
| 52 | fetch(`${servers.url}${path}`, { | |
| 53 | method: "POST", | |
| 54 | redirect: "manual", | |
| 55 | headers: { cookie: cookie(who), origin, "content-type": "application/x-www-form-urlencoded" }, | |
| 56 | body, | |
| 57 | }); | |
| 58 | ||
| 59 | test("a member adds a machine, is shown its token once, and sees it under their name", async () => { | |
| 60 | expect(await (await get(bob, "/settings/machines")).text()).toContain("Add a machine"); | |
| 61 | expect((await post(bob, "/settings/machines", "name=evil&labels=macos", "https://evil.example")).status).toBe(403); | |
| 62 | expect(ownedBy(app, bob.id)).toEqual([]); | |
| 63 | const added = await post(bob, "/settings/machines", "name=bobs-mac&labels=macos%2Carm64"); | |
| 64 | expect(added.status).toBe(200); | |
| 65 | expect(await added.text()).toContain("forge_runner_"); | |
| 66 | expect(ownedBy(app, bob.id).map((m) => m.name)).toEqual(["bobs-mac"]); | |
| 67 | const page = await (await get(bob, "/settings/machines")).text(); | |
| 68 | expect(page).toContain("bobs-mac"); | |
| 69 | expect(page).not.toContain("forge_runner_"); | |
| 70 | expect(await (await get(alice, "/settings/machines")).text()).not.toContain("bobs-mac"); | |
| 71 | }); | |
| 72 | ||
| 73 | test("the repository's owner allows it on the repository's settings; a member who is not its owner cannot", async () => { | |
| 74 | const repo = getRepo(app.db, "alice", "lib")!; | |
| 75 | const id = ownedBy(app, bob.id)[0]!.id; | |
| 76 | const seen = await (await get(alice, "/alice/lib/settings/machines")).text(); | |
| 77 | expect(seen).toContain("bobs-mac"); | |
| 78 | expect(seen).toContain("Refused"); | |
| 79 | expect((await post(bob, `/alice/lib/settings/machines/${id}/allow`)).status).toBeGreaterThanOrEqual(400); | |
| 80 | expect(machinesFor(app, repo)[0]?.allowed).toBe(false); | |
| 81 | expect((await post(alice, `/alice/lib/settings/machines/${id}/allow`, "", "https://evil.example")).status).toBe(403); | |
| 82 | expect((await post(alice, `/alice/lib/settings/machines/${id}/allow`)).status).toBe(303); | |
| 83 | expect(machinesFor(app, repo)[0]?.allowed).toBe(true); | |
| 84 | expect(await (await get(alice, "/alice/lib/settings/machines")).text()).toContain("Allowed"); | |
| 85 | expect((await post(alice, `/alice/lib/settings/machines/${id}/refuse`)).status).toBe(303); | |
| 86 | expect(machinesFor(app, repo)[0]?.allowed).toBe(false); | |
| 87 | }); |
test/own-machines.test.ts added +158
| @@ -0,0 +1,158 @@ | ||
| 1 | /** | |
| 2 | * A member's own machine (#18505): added by a member, it takes a run only for a repository whose | |
| 3 | * owner allowed it; an admin marks it trusted, and nothing it says of itself does; what it | |
| 4 | * reports (os, arch, docker, xcode) only narrows routing; `may()` decides all three actions. | |
| 5 | */ | |
| 6 | import { beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { allowMachine, addMachine, machinesFor, ownedBy } from "../src/machines/own.ts"; | |
| 8 | import { heldLabels, noteRunnerReport, readReport } from "../src/machines/report.ts"; | |
| 9 | import { setRunnerTrust } from "../src/actions/environments.ts"; | |
| 10 | import { runnerTrusted } from "../src/checks/environment.ts"; | |
| 11 | import { claimJob, labelServed, offerJob } from "../src/checks/runner_jobs.ts"; | |
| 12 | import { may } from "../src/core/may.ts"; | |
| 13 | import { principalOfUser } from "../src/core/principal.ts"; | |
| 14 | import { createRun } from "../src/core/runs.ts"; | |
| 15 | import { checksForge } from "./helpers/checks-forge.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | const f = checksForge("forge-own-machines-"); | |
| 21 | ||
| 22 | beforeAll(async () => { | |
| 23 | await f.checks.stop(); | |
| 24 | }); | |
| 25 | ||
| 26 | /** Queue one job for `lib`, with a label when asked. */ | |
| 27 | function offer(label = ""): string { | |
| 28 | const run = createRun(f.app.db, { repoId: f.repo.id, kind: "check", env: "main", commitOid: "a".repeat(40) }); | |
| 29 | return offerJob(f.app.db, { | |
| 30 | runId: run.id, | |
| 31 | repoId: f.repo.id, | |
| 32 | dir: f.dataDir, | |
| 33 | job: { | |
| 34 | run: run.id, | |
| 35 | repo: "alice/lib", | |
| 36 | commit: "a".repeat(40), | |
| 37 | depth: 1, | |
| 38 | steps: [{ name: "check", command: "true" }], | |
| 39 | env: { CI: "true" }, | |
| 40 | limits: {}, | |
| 41 | timeoutS: 60, | |
| 42 | egress: [], | |
| 43 | egressMode: "report", | |
| 44 | cell: "preferred", | |
| 45 | cache: { repo: f.repo.id, tree: "", base: "" }, | |
| 46 | ...(label === "" ? {} : { label }), | |
| 47 | }, | |
| 48 | }).id; | |
| 49 | } | |
| 50 | ||
| 51 | const add = (name: string, labels: string[] = []) => { | |
| 52 | const made = addMachine(f.app, f.bob, name, labels); | |
| 53 | if (!made.ok) throw new Error(JSON.stringify(made.error)); | |
| 54 | return made.value; | |
| 55 | }; | |
| 56 | const claim = (id: string) => claimJob(f.app.db, { id, cells: true }, Date.now()); | |
| 57 | const clear = () => f.app.db.query("DELETE FROM check_job").run(); | |
| 58 | ||
| 59 | describe("a member adds a machine", () => { | |
| 60 | test("it is listed under their name, and an agent or a visitor cannot add one", () => { | |
| 61 | const m = add("bobs-mac", ["macos"]); | |
| 62 | expect(m.machine.ownerId).toBe(f.bob.id); | |
| 63 | expect(ownedBy(f.app, f.bob.id).map((r) => r.name)).toEqual(["bobs-mac"]); | |
| 64 | expect(ownedBy(f.app, f.alice.id)).toEqual([]); | |
| 65 | expect(addMachine(f.app, undefined, "x", [])).toEqual({ ok: false, error: "not_found" }); | |
| 66 | expect(addMachine(f.app, f.bob, "bad name", []).ok).toBe(false); | |
| 67 | expect(addMachine(f.app, f.bob, "ok", ["Not A Label"]).ok).toBe(false); | |
| 68 | }); | |
| 69 | }); | |
| 70 | ||
| 71 | describe("a machine takes a run only for a repository that allowed it", () => { | |
| 72 | test("never asked and refused take nothing; allowed takes the run; refusing again stops it", () => { | |
| 73 | clear(); | |
| 74 | const m = add("gated").machine; | |
| 75 | offer(); | |
| 76 | expect(claim(m.id)).toBeUndefined(); | |
| 77 | expect(allowMachine(f.app, f.alice, f.repo, m.id, false).ok).toBe(true); | |
| 78 | expect(claim(m.id)).toBeUndefined(); | |
| 79 | expect(allowMachine(f.app, f.alice, f.repo, m.id, true).ok).toBe(true); | |
| 80 | expect(machinesFor(f.app, f.repo).find((r) => r.id === m.id)?.allowed).toBe(true); | |
| 81 | expect(claim(m.id)?.job.repo).toBe("alice/lib"); | |
| 82 | clear(); | |
| 83 | offer(); | |
| 84 | expect(allowMachine(f.app, f.alice, f.repo, m.id, false).ok).toBe(true); | |
| 85 | expect(claim(m.id)).toBeUndefined(); | |
| 86 | }); | |
| 87 | ||
| 88 | test("only the repository's administrator decides, and a labelled job is gated the same way", () => { | |
| 89 | clear(); | |
| 90 | const m = add("labelled", ["xcode"]).machine; | |
| 91 | expect(allowMachine(f.app, f.bob, f.repo, m.id, true)).toEqual({ ok: false, error: "not_found" }); | |
| 92 | offer("xcode"); | |
| 93 | f.app.db.query("UPDATE check_runner SET seen_at = ?2 WHERE id = ?1").run(m.id, Date.now()); | |
| 94 | expect(labelServed(f.app.db, f.repo.id, "xcode", Date.now())).toBe(false); | |
| 95 | expect(claim(m.id)).toBeUndefined(); | |
| 96 | expect(allowMachine(f.app, f.alice, f.repo, m.id, true).ok).toBe(true); | |
| 97 | expect(labelServed(f.app.db, f.repo.id, "xcode", Date.now())).toBe(true); | |
| 98 | expect(claim(m.id)?.job.repo).toBe("alice/lib"); | |
| 99 | }); | |
| 100 | ||
| 101 | test("a runner an admin enrolled is not gated, as before", async () => { | |
| 102 | clear(); | |
| 103 | const { enrolRunner } = await import("../src/checks/runner_jobs.ts"); | |
| 104 | const r = enrolRunner(f.app.db, "plain", f.alice.id).runner; | |
| 105 | offer(); | |
| 106 | expect(claim(r.id)?.job.repo).toBe("alice/lib"); | |
| 107 | }); | |
| 108 | }); | |
| 109 | ||
| 110 | describe("trust is a person's decision", () => { | |
| 111 | test("a report of 'trusted' changes nothing; an admin's decision does, and a member's does not", () => { | |
| 112 | const m = add("trust-me").machine; | |
| 113 | noteRunnerReport(f.app.db, m.id, { os: "darwin", trusted: true, trusted_at: 1, isTrusted: true }); | |
| 114 | expect(runnerTrusted(f.app.db, m.id)).toBe(false); | |
| 115 | expect(readReport({ os: "darwin", trusted: true })).toEqual({ os: "darwin" }); | |
| 116 | expect(setRunnerTrust(f.app, f.bob, m.id, true)).toEqual({ ok: false, error: "not_found" }); | |
| 117 | expect(runnerTrusted(f.app.db, m.id)).toBe(false); | |
| 118 | expect(setRunnerTrust(f.app, f.alice, m.id, true).ok).toBe(true); | |
| 119 | expect(runnerTrusted(f.app.db, m.id)).toBe(true); | |
| 120 | // Its trust survives a later report of anything. | |
| 121 | noteRunnerReport(f.app.db, m.id, { os: "linux", trusted: false }); | |
| 122 | expect(runnerTrusted(f.app.db, m.id)).toBe(true); | |
| 123 | }); | |
| 124 | }); | |
| 125 | ||
| 126 | describe("what a machine reports only narrows routing", () => { | |
| 127 | test("a label its report contradicts is dropped; none is ever added", () => { | |
| 128 | expect(heldLabels('["macos","arm64","docker"]', '{"os":"linux","arch":"arm64","docker":true}')).toEqual(["arm64", "docker"]); | |
| 129 | expect(heldLabels('["xcode"]', '{"xcode":false}')).toEqual([]); | |
| 130 | expect(heldLabels('["macos"]', "{}")).toEqual(["macos"]); | |
| 131 | expect(heldLabels("[]", '{"os":"darwin","xcode":true,"docker":true}')).toEqual([]); | |
| 132 | }); | |
| 133 | ||
| 134 | test("a machine owned as macos that reports linux is not sent a macos job, and one that reports darwin is", () => { | |
| 135 | clear(); | |
| 136 | const m = add("liar", ["macos"]).machine; | |
| 137 | expect(allowMachine(f.app, f.alice, f.repo, m.id, true).ok).toBe(true); | |
| 138 | offer("macos"); | |
| 139 | noteRunnerReport(f.app.db, m.id, { os: "linux" }); | |
| 140 | expect(claim(m.id)).toBeUndefined(); | |
| 141 | noteRunnerReport(f.app.db, m.id, { os: "darwin", arch: "arm64", docker: false, xcode: true }); | |
| 142 | expect(claim(m.id)?.job.repo).toBe("alice/lib"); | |
| 143 | }); | |
| 144 | }); | |
| 145 | ||
| 146 | describe("one table decides each of the three actions", () => { | |
| 147 | test("may() answers machine.add, machine.allow and machine.trust", () => { | |
| 148 | const db = f.app.db; | |
| 149 | const alice = principalOfUser(f.alice); | |
| 150 | const bob = principalOfUser(f.bob); | |
| 151 | expect(may(db, bob, "machine.add").ok).toBe(true); | |
| 152 | expect(may(db, { kind: "anonymous", refused: false }, "machine.add").ok).toBe(false); | |
| 153 | expect(may(db, alice, "machine.allow", { repo: f.repo }).ok).toBe(true); | |
| 154 | expect(may(db, bob, "machine.allow", { repo: f.repo }).ok).toBe(false); | |
| 155 | expect(may(db, alice, "machine.trust").ok).toBe(true); | |
| 156 | expect(may(db, bob, "machine.trust").ok).toBe(false); | |
| 157 | }); | |
| 158 | }); |
test/palette-roster.test.ts +2
| @@ -118,6 +118,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 118 | 118 | ["receipts", "Receipts", "what you confirmed in /talk; u undoes it once"], |
| 119 | 119 | ["trusted", "Trusted sources", "who folds in without review; a trusts, x removes, s stops all, v reverts"], |
| 120 | 120 | ["runners", "Runners", "the machines that take this forge's checks; x removes a hand-made one"], |
| 121 | ["own-machines", "Your machines", "the machines you added; n adds one"], | |
| 121 | 122 | ["conversations", "Conversations", "your talks with the forge's agent; n starts one, r renames, x archives"], |
| 122 | 123 | ["build-app", "Build an app", "say what to build; versions, diff, restore and publish. n starts one"], |
| 123 | 124 | ["fetch-page", "Read a web page", "paste an https link; the page as Markdown, as Talk's agent reads it"], |
| @@ -476,6 +477,7 @@ test("a member person is offered the signed-in roster without the admin entries" | ||
| 476 | 477 | ["notify", "Phone notifications", "where the crew reaches your phone; s sets, x turns off"], |
| 477 | 478 | ["confirms", "Confirms", "what the forge's agent asked to do; y does it once"], |
| 478 | 479 | ["receipts", "Receipts", "what you confirmed in /talk; u undoes it once"], |
| 480 | ["own-machines", "Your machines", "the machines you added; n adds one"], | |
| 479 | 481 | ["conversations", "Conversations", "your talks with the forge's agent; n starts one, r renames, x archives"], |
| 480 | 482 | ["build-app", "Build an app", "say what to build; versions, diff, restore and publish. n starts one"], |
| 481 | 483 | ["fetch-page", "Read a web page", "paste an https link; the page as Markdown, as Talk's agent reads it"], |
new above
offline