Public: anyone can read this; the crew can change it.
Member, not owner: what a trusted account can do, in one table, and enforced so nobody takes over by accident #2259
scout/forge:scout/673-member-not-owner-what-a-trusted-account → main 4 commits fork 3 threads · 3 unresolved
28 files
changed +923
−5
README.md +2
| @@ -691,6 +691,8 @@ an organization (its page), down to one crew member: a work plan pays for | ||
| 691 | 691 | the work repositories and nothing else. Two on one grant take turns, and |
| 692 | 692 | one the provider rests hands its runs to the other until the reset. |
| 693 | 693 | **Model budget.** A new account has none: its repositories' crew does not run, spends nothing, and says "This repository has no model account". A person adds their own subscription at Settings → Model (or the terminal's **Model budget** command, `a`); it is sealed, granted to their own repositories only, and one per account. A forge admin who is a person gives an account a capped grant, in dollars a month spent on the forge's own credential, from the account's page, the terminal's **Model grant** command, `POST /api/v1/admin/accounts/:name/model-grant` (`{"usdPerMonth": 20}`, `null` takes it back) or the MCP `model_grant` tool; each change is in the audit. The cap is the UTC month's spend in the usage ledger, checked when a run starts and on every spend tick: a run past it stops, and its page says the grant is spent. Two runs that start together each begin with the whole remainder; the tick check ends both once the sum crosses the cap, so the overshoot is at most what they spend between ticks. |
| 694 | ||
| 695 | **Roles.** Three, in one table (`docs/ROLES.md`, `src/core/roles.ts`): a **guest** (a fresh account) reads what is public, comments, follows and reports; a **member** also owns repositories, apps and a crew; an **admin** administers the forge. The role is read at every act: a guest is refused creating, forking, copying a repository and so making an app (`not_member`, 403), and the same account is let in once promoted. A forge admin who is a person promotes at Settings → People (with a starter allowance, none by default), the terminal's **Set a role** command, or `POST /api/v1/admin/accounts/:name/role` (`{"role":"member","usdPerMonth":5}`); everyone sees their own role at Settings → People, the terminal's **Roles** command and the MCP `can_i` tool. A vouched account (`trusted` at creation) and any account that already owned a repository when this shipped start as members; an agent holds its maker's role, at most member. Not gated by role yet: starting runs and the sandbox proofs for a member's code (see `docs/ROLES.md`). | |
| 694 | 696 | **Sandbox.** An agent's shell is held to a policy — the network is the forge |
| 695 | 697 | and the package registry, writes stay in the clone, the forge's data and the |
| 696 | 698 | operator's credentials are unreadable — by bubblewrap and socat on Linux |
docs/ROLES.md added +40
| @@ -0,0 +1,40 @@ | ||
| 1 | # Roles — guest, member, admin | |
| 2 | ||
| 3 | One table, the same one `/settings/people` shows and the MCP tool `can_i` | |
| 4 | returns (`src/core/roles.ts`; `test/roles.test.ts` fails if this page drifts). | |
| 5 | ||
| 6 | | Can | Guest | Member | Admin | | |
| 7 | | --- | --- | --- | --- | | |
| 8 | | Read what is public, comment, follow, report | yes | yes | yes | | |
| 9 | | Own repositories, apps and a crew | — | yes | yes | | |
| 10 | | Run apps, previews and checks, inside a sandbox and quotas | — | yes | yes | | |
| 11 | | Spend a model budget: their own subscription, or a capped grant | — | yes | yes | | |
| 12 | | Mint tokens for their own things only | — | yes | yes | | |
| 13 | | Change forge settings, other accounts, the crew's standing instructions or releases | — | — | yes | | |
| 14 | | Promote or demote accounts, and give a grant | — | — | yes | | |
| 15 | | Spend the forge's own credential without a cap | — | — | yes | | |
| 16 | ||
| 17 | A fresh account is a guest. A forge admin who is a person promotes it from | |
| 18 | `/settings/people` (or `POST /api/v1/admin/accounts/:username/role` with | |
| 19 | `{"role":"member","usdPerMonth":5}`), choosing a starter allowance; none by | |
| 20 | default. The allowance is a `model_grant` (a hard monthly cap on the forge's | |
| 21 | credential). Demoting to guest takes any grant back, and says so. An agent counts as a member; an admin is never changed here. | |
| 22 | ||
| 23 | ## What is enforced today, and what is not | |
| 24 | ||
| 25 | Enforced, with tests that fail without it (`test/roles.test.ts`): creating, | |
| 26 | forking and copying a repository (so `newApp` too) need a member or admin — | |
| 27 | the same account is refused as a guest and let in once promoted, and refused | |
| 28 | again if demoted. An agent holds its maker's role, at most member, so a | |
| 29 | guest's crew is not above the guest. Forge, account and grant administration | |
| 30 | are admin-only (existing `isAdmin` checks, exercised with a member actor). | |
| 31 | Sandboxing of apps/checks/crew shells is `apps/contain.ts` (#658) and the | |
| 32 | model budget is `core/model_grant.ts`. | |
| 33 | ||
| 34 | Not yet: starting runs is not gated by role (a guest owns no repository, so | |
| 35 | has none to run, but a member's crew is only as safe as the cell); the member | |
| 36 | actor does not yet try to read forge data from an app, a check or a crew | |
| 37 | shell, and the proofs do not yet run after every release. Accounts vouched at | |
| 38 | creation and accounts that already owned a repository, and people on a write or | |
| 39 | admin team of an organization that owns one, were made members, so | |
| 40 | nobody who was working is shut out. |
src/actions/make_it_yours.ts +9
| @@ -23,6 +23,8 @@ | ||
| 23 | 23 | * already made does not count. |
| 24 | 24 | */ |
| 25 | 25 | |
| 26 | import { requireVerified } from "./verify.ts"; | |
| 27 | import { roleOf } from "../core/roles.ts"; | |
| 26 | 28 | import { storageLimitMessage } from "../core/storage.ts"; |
| 27 | 29 | import type { App } from "../app.ts"; |
| 28 | 30 | import { |
| @@ -67,6 +69,8 @@ export type MakeItYoursError = | ||
| 67 | 69 | | { readonly kind: "not_found" } |
| 68 | 70 | | { readonly kind: "unauthorized" } |
| 69 | 71 | | { readonly kind: "unverified" } |
| 72 | /** A guest: the same refusal, in the same words, as every other way to own something. */ | |
| 73 | | { readonly kind: "not_member" } | |
| 70 | 74 | | { readonly kind: "own" } |
| 71 | 75 | /** Today's copies are made; another may be made from `resetsAt`. */ |
| 72 | 76 | | { readonly kind: "limit"; readonly resetsAt: string } |
| @@ -148,6 +152,11 @@ export async function makeItYours( | ||
| 148 | 152 | kind: "invalid", |
| 149 | 153 | message: "an agent does not make apps its own", |
| 150 | 154 | }); |
| 155 | // Proof of the email comes before the role: a guest is told to prove it | |
| 156 | // first, and only then that the owner must make them a member. | |
| 157 | if (!requireVerified(app, actor).ok) return err({ kind: "unverified" }); | |
| 158 | if (roleOf(app.db, actor) === "guest") | |
| 159 | return err({ kind: "not_member" }); | |
| 151 | 160 | if (source.ownerId === actor.id) return err({ kind: "own" }); |
| 152 | 161 | const dryRun = input.dryRun !== false; |
| 153 | 162 | const name = input.name?.trim() || source.name; |
src/actions/migrate.ts +2
| @@ -197,6 +197,8 @@ export function migrateMessage(error: MigrateError, limit = "at the repositories | ||
| 197 | 197 | return "Verify your email first: follow the link we sent, or ask for another under Settings."; |
| 198 | 198 | case "refused": |
| 199 | 199 | return "New accounts cannot create repositories yet."; |
| 200 | case "not_member": | |
| 201 | return "This account is a guest. Ask the forge's owner to make you a member."; | |
| 200 | 202 | case "repository_limit": |
| 201 | 203 | return `Not made: ${limit}.`; |
| 202 | 204 | case "storage_limit": |
src/actions/repos.ts +7 −1
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import { requireVerified } from "./verify.ts"; |
| 8 | import { requireMember } from "./roles.ts"; | |
| 8 | 9 | import type { App } from "../app.ts"; |
| 9 | 10 | import { canSeeSealed } from "../core/sealed.ts"; |
| 10 | 11 | import { capacityValue } from "../core/capacity.ts"; |
| @@ -72,6 +73,7 @@ export type CreateRepoActionError = | ||
| 72 | 73 | | "unauthorized" |
| 73 | 74 | | "forbidden_owner" |
| 74 | 75 | | "refused" |
| 76 | | "not_member" | |
| 75 | 77 | | "repository_limit" |
| 76 | 78 | | "storage_limit"; |
| 77 | 79 | |
| @@ -140,6 +142,8 @@ export async function createRepo( | ||
| 140 | 142 | // An agent owns nothing it was not given (docs/APPS.md): it works on the |
| 141 | 143 | // repositories whose crew it is on, and cannot make itself a new one. |
| 142 | 144 | if (user.value.kind === "agent") return err("forbidden_owner"); |
| 145 | const member = requireMember(app, user.value); | |
| 146 | if (!member.ok) return member; | |
| 143 | 147 | const guarded = requireNewAccountGuard(app, user.value); |
| 144 | 148 | if (!guarded.ok) return guarded; |
| 145 | 149 | const ownerId = resolveOwner(app, user.value, input.owner ?? ""); |
| @@ -179,11 +183,13 @@ export async function forkRepo( | ||
| 179 | 183 | parent: Repo, |
| 180 | 184 | name?: string, |
| 181 | 185 | options: { visibility?: "public" | "private"; now?: number } = {}, |
| 182 | ): Promise<Result<Repo, ForkRepoError | "not_found" | "unauthorized" | "unverified" | "refused" | "repository_limit" | "storage_limit">> { | |
| 186 | ): Promise<Result<Repo, ForkRepoError | "not_found" | "unauthorized" | "unverified" | "refused" | "not_member" | "repository_limit" | "storage_limit">> { | |
| 183 | 187 | const user = requireParticipant(app, actor, parent); |
| 184 | 188 | if (!user.ok) return user; |
| 185 | 189 | const proven = requireVerified(app, user.value); |
| 186 | 190 | if (!proven.ok) return proven; |
| 191 | const member = requireMember(app, user.value); | |
| 192 | if (!member.ok) return member; | |
| 187 | 193 | const guarded = requireNewAccountGuard(app, user.value); |
| 188 | 194 | if (!guarded.ok) return guarded; |
| 189 | 195 | if (repositoryLimitRefusal(app, user.value) !== undefined) return err("repository_limit"); |
src/actions/roles.ts added +59
| @@ -0,0 +1,59 @@ | ||
| 1 | /** | |
| 2 | * Guest to member, in one act: a forge admin who is a person promotes a | |
| 3 | * person, with a starter allowance they choose (default none), or demotes | |
| 4 | * them. Each change is an event on the outbox, so the audit has it. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { getModelGrant, setModelGrant, validGrant } from "../core/model_grant.ts"; | |
| 9 | import { demote, promote, roleOf, type Role } from "../core/roles.ts"; | |
| 10 | import { getUserByName, type User } from "../core/users.ts"; | |
| 11 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 12 | ||
| 13 | import { requireUser } from "./access.ts"; | |
| 14 | ||
| 15 | export type RoleError = "not_found" | "not_allowed" | "invalid_amount"; | |
| 16 | ||
| 17 | export function setRole( | |
| 18 | app: App, | |
| 19 | actor: User | undefined, | |
| 20 | username: string, | |
| 21 | to: "guest" | "member", | |
| 22 | allowanceUsd: number | null = null, | |
| 23 | ): Result<{ username: string; role: Role; usdPerMonth: number | null; grantTakenBack: boolean }, RoleError> { | |
| 24 | const admin = requireUser(actor); | |
| 25 | if (!admin.ok || !admin.value.isAdmin || admin.value.kind !== "user") | |
| 26 | return err("not_found"); | |
| 27 | const user = getUserByName(app.db, username); | |
| 28 | if (user === undefined || user.kind === "org") return err("not_found"); | |
| 29 | if (user.kind === "agent" || user.isAdmin) return err("not_allowed"); | |
| 30 | if (allowanceUsd !== null && !validGrant(allowanceUsd)) return err("invalid_amount"); | |
| 31 | const now = new Date(); | |
| 32 | // Going back to guest takes any model grant with it; the caller says so. | |
| 33 | const grantTakenBack = to === "guest" && getModelGrant(app.db, user.id) !== undefined; | |
| 34 | if (to === "member") { | |
| 35 | promote(app.db, user.id, admin.value.id, now); | |
| 36 | if (allowanceUsd !== null) setModelGrant(app.db, user.id, allowanceUsd, admin.value.id, now); | |
| 37 | } else { | |
| 38 | demote(app.db, user.id); | |
| 39 | setModelGrant(app.db, user.id, null, admin.value.id, now); | |
| 40 | } | |
| 41 | const usd = allowanceUsd === null ? null : Math.round(allowanceUsd * 100) / 100; | |
| 42 | app.bus.append({ | |
| 43 | kind: "account.role_set", | |
| 44 | actorId: admin.value.id, | |
| 45 | payload: { username: user.username, role: roleOf(app.db, user), usdPerMonth: usd, grantTakenBack }, | |
| 46 | }); | |
| 47 | return ok({ username: user.username, role: roleOf(app.db, user), usdPerMonth: usd, grantTakenBack }); | |
| 48 | } | |
| 49 | ||
| 50 | /** | |
| 51 | * The role gate: a guest owns nothing, so creating, forking and copying a | |
| 52 | * repository (and so a new app) need a member or an admin. Refused in words | |
| 53 | * that say how to get in (`not_member`). | |
| 54 | */ | |
| 55 | export function requireMember(app: App, user: User): Result<User, "not_member"> { | |
| 56 | // An organization never signs in: the person acting for it is the one gated. | |
| 57 | if (user.kind === "org") return ok(user); | |
| 58 | return roleOf(app.db, user) === "guest" ? err("not_member") : ok(user); | |
| 59 | } |
src/core/migrations/20261016180000-member-role.ts added +8
| @@ -0,0 +1,8 @@ | ||
| 1 | // A guest is a fresh account; a member is one the owner promoted (#673). | |
| 2 | export default ` | |
| 3 | CREATE TABLE member ( | |
| 4 | user_id TEXT PRIMARY KEY REFERENCES user(id) ON DELETE CASCADE, | |
| 5 | promoted_by TEXT, | |
| 6 | promoted_at TEXT NOT NULL | |
| 7 | ) WITHOUT ROWID; | |
| 8 | `; |
src/core/migrations/20261016180100-member-grandfather.ts added +16
| @@ -0,0 +1,16 @@ | ||
| 1 | // Accounts that already worked were let in before roles existed: they start | |
| 2 | // as members, so the role gate shuts nobody out (#673). That is a person who | |
| 3 | // owns a repository, and a person on a team that can write to (or administer) | |
| 4 | // an organization that owns one; a read-only team member never made anything. | |
| 5 | export default ` | |
| 6 | INSERT OR IGNORE INTO member (user_id, promoted_by, promoted_at) | |
| 7 | SELECT DISTINCT r.owner_id, 'migration', strftime('%Y-%m-%dT%H:%M:%fZ','now') | |
| 8 | FROM repo r JOIN user u ON u.id = r.owner_id WHERE u.kind = 'user'; | |
| 9 | ||
| 10 | INSERT OR IGNORE INTO member (user_id, promoted_by, promoted_at) | |
| 11 | SELECT DISTINCT tm.user_id, 'migration', strftime('%Y-%m-%dT%H:%M:%fZ','now') | |
| 12 | FROM team_member tm | |
| 13 | JOIN team t ON t.id = tm.team_id AND t.permission IN ('write','admin') | |
| 14 | JOIN user u ON u.id = tm.user_id AND u.kind = 'user' | |
| 15 | WHERE EXISTS (SELECT 1 FROM repo r WHERE r.owner_id = t.org_id); | |
| 16 | `; |
src/core/roles.ts added +85
| @@ -0,0 +1,85 @@ | ||
| 1 | /** | |
| 2 | * The three roles an account can hold, and what each may do: one table, read | |
| 3 | * by the page, the docs and the MCP tool alike. A guest is a fresh account; a | |
| 4 | * member was promoted by a forge admin; an admin administers the forge. An | |
| 5 | * agent is the crew of a person and holds the role of the person it works for | |
| 6 | * at most — a member — never admin. Pure data; who may promote is the | |
| 7 | * caller's to decide (`actions/roles.ts`). | |
| 8 | */ | |
| 9 | ||
| 10 | import type { Database } from "bun:sqlite"; | |
| 11 | ||
| 12 | export type Role = "guest" | "member" | "admin"; | |
| 13 | ||
| 14 | export const ROLES: readonly Role[] = ["guest", "member", "admin"]; | |
| 15 | ||
| 16 | export interface Ability { | |
| 17 | readonly can: string; | |
| 18 | readonly guest: boolean; | |
| 19 | readonly member: boolean; | |
| 20 | readonly admin: boolean; | |
| 21 | } | |
| 22 | ||
| 23 | const row = (can: string, guest: boolean, member: boolean, admin = true): Ability => ({ | |
| 24 | can, | |
| 25 | guest, | |
| 26 | member, | |
| 27 | admin, | |
| 28 | }); | |
| 29 | ||
| 30 | /** What each role can do. The one table; `docs/ROLES.md` is checked against it. */ | |
| 31 | export const ABILITIES: readonly Ability[] = [ | |
| 32 | row("Read what is public, comment, follow, report", true, true), | |
| 33 | row("Own repositories, apps and a crew", false, true), | |
| 34 | row("Run apps, previews and checks, inside a sandbox and quotas", false, true), | |
| 35 | row("Spend a model budget: their own subscription, or a capped grant", false, true), | |
| 36 | row("Mint tokens for their own things only", false, true), | |
| 37 | row("Change forge settings, other accounts, the crew's standing instructions or releases", false, false), | |
| 38 | row("Promote or demote accounts, and give a grant", false, false), | |
| 39 | row("Spend the forge's own credential without a cap", false, false), | |
| 40 | ]; | |
| 41 | ||
| 42 | export function roleOf( | |
| 43 | db: Database, | |
| 44 | user: { id: string; isAdmin: boolean; kind: string }, | |
| 45 | ): Role { | |
| 46 | if (user.isAdmin) return "admin"; | |
| 47 | if (user.kind === "org") return "guest"; | |
| 48 | // An agent holds the role of the person who made it, at most a member; one | |
outdated
An agent becomes a member whatever its owner's role is. The docstring says "the role of the person it works for at most". Resolve the agent's owner and return |
||
| 49 | // the forge made itself (no creator) is the forge's crew. | |
| 50 | if (user.kind === "agent") { | |
| 51 | const made = db | |
| 52 | .query<{ created_by: string | null }, [string]>("SELECT created_by FROM agent WHERE user_id = ?1") | |
| 53 | .get(user.id); | |
| 54 | if (made === null || made.created_by === null) return "member"; | |
| 55 | const maker = db | |
| 56 | .query<{ id: string; is_admin: number; kind: string }, [string]>( | |
| 57 | "SELECT id, is_admin, kind FROM user WHERE id = ?1", | |
| 58 | ) | |
| 59 | .get(made.created_by); | |
| 60 | if (maker === null || maker.kind === "agent") return "guest"; | |
| 61 | return roleOf(db, { id: maker.id, isAdmin: maker.is_admin === 1, kind: maker.kind }) === "guest" | |
| 62 | ? "guest" | |
| 63 | : "member"; | |
| 64 | } | |
| 65 | const found = db | |
| 66 | .query<{ n: number }, [string]>("SELECT 1 AS n FROM member WHERE user_id = ?1") | |
| 67 | .get(user.id); | |
| 68 | return found === null ? "guest" : "member"; | |
| 69 | } | |
| 70 | ||
| 71 | export function promote(db: Database, userId: string, by: string, now: Date): void { | |
| 72 | db.query( | |
| 73 | `INSERT INTO member (user_id, promoted_by, promoted_at) VALUES (?1, ?2, ?3) | |
| 74 | ON CONFLICT(user_id) DO NOTHING`, | |
| 75 | ).run(userId, by, now.toISOString()); | |
| 76 | } | |
| 77 | ||
| 78 | export function demote(db: Database, userId: string): void { | |
| 79 | db.query("DELETE FROM member WHERE user_id = ?1").run(userId); | |
| 80 | } | |
| 81 | ||
| 82 | /** What the account can do as itself: its role and the table's rows it holds. */ | |
| 83 | export function abilitiesFor(role: Role): string[] { | |
| 84 | return ABILITIES.filter((a) => a[role]).map((a) => a.can); | |
| 85 | } |
src/core/users.ts +6 −2
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | * narrower; there is no second identity system. |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | import { promote } from "./roles.ts"; | |
| 6 | 7 | import { markUnproven, markVerified } from "./verify.ts"; |
| 7 | 8 | import type { Database } from "bun:sqlite"; |
| 8 | 9 | import { isSafeName } from "../git/guard.ts"; |
| @@ -225,8 +226,11 @@ export async function createUser( | ||
| 225 | 226 | } |
| 226 | 227 | // Every person gets a row: proven when the caller vouches, else not yet. |
| 227 | 228 | if (!agent) { |
| 228 | if (input.trusted === true) markVerified(db, userId, new Date().toISOString()); | |
| 229 | else markUnproven(db, userId); | |
| 229 | // The caller's word is also its word that this is a member (#673). | |
| 230 | if (input.trusted === true) { | |
| 231 | markVerified(db, userId, new Date().toISOString()); | |
| 232 | promote(db, userId, "vouched", new Date()); | |
| 233 | } else markUnproven(db, userId); | |
| 230 | 234 | } |
| 231 | 235 | return ok(getUserById(db, userId)!); |
| 232 | 236 | } |
src/http/api.ts +22
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | 11 | import { setAccountGrant } from "../actions/model_grant.ts"; |
| 12 | import { setRole } from "../actions/roles.ts"; | |
| 12 | 13 | import { storageLimitMessage } from "../core/storage.ts"; |
| 13 | 14 | import { voteVariant } from "../actions/variants.ts"; |
| 14 | 15 | import { parentForgeFor } from "../core/parent_releases.ts"; |
| @@ -367,6 +368,7 @@ import { | ||
| 367 | 368 | publicUser, |
| 368 | 369 | requireAccount, |
| 369 | 370 | requireScope, |
| 371 | NOT_MEMBER_MESSAGE, | |
| 370 | 372 | respondAccess, |
| 371 | 373 | str, |
| 372 | 374 | unauthorized, |
| @@ -1587,6 +1589,24 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1587 | 1589 | return done.ok ? json({ username: done.value.username, suspendedAt: done.value.suspendedAt }) : accountError(done.error); |
| 1588 | 1590 | }); |
| 1589 | 1591 | |
| 1592 | // Guest to member and back, with an optional starter allowance (#673). | |
| 1593 | router.add("POST", "/api/v1/admin/accounts/:username/role", async (ctx) => { | |
| 1594 | const denied = accountAdmin(ctx, "admin"); | |
| 1595 | if (denied) return denied; | |
| 1596 | const input = await body(ctx.request); | |
| 1597 | const to = input.role; | |
| 1598 | const usd = input.usdPerMonth ?? null; | |
| 1599 | if ((to !== "member" && to !== "guest") || (usd !== null && (typeof usd !== "number" || !Number.isFinite(usd)))) | |
| 1600 | return apiError("invalid", 422, "role is member or guest; usdPerMonth is a number of dollars or absent"); | |
| 1601 | const done = setRole(ctx.app, ctx.auth.user, ctx.params.username!, to, usd === 0 ? null : usd); | |
| 1602 | if (done.ok) return json(done.value); | |
| 1603 | return done.error === "invalid_amount" | |
| 1604 | ? apiError("invalid", 422, "usdPerMonth is from 0.01 to 10000 dollars") | |
| 1605 | : done.error === "not_allowed" | |
| 1606 | ? apiError("not_allowed", 422, "an admin or an agent has no role to change") | |
| 1607 | : notFound(); | |
| 1608 | }); | |
| 1609 | ||
| 1590 | 1610 | // A capped model grant, dollars a month; null (or 0) takes it back. |
| 1591 | 1611 | router.add("POST", "/api/v1/admin/accounts/:username/model-grant", async (ctx) => { |
| 1592 | 1612 | const denied = accountAdmin(ctx, "admin"); |
| @@ -4398,6 +4418,8 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 4398 | 4418 | ? apiError("storage_limit", 403, made.error.message) |
| 4399 | 4419 | : made.error.kind === "invalid" |
| 4400 | 4420 | ? apiError("invalid", 422, made.error.message) |
| 4421 | : made.error.kind === "not_member" | |
| 4422 | ? apiError("not_member", 403, NOT_MEMBER_MESSAGE) | |
| 4401 | 4423 | : made.error.kind === "own" |
| 4402 | 4424 | ? apiError("own", 409, "this app is already yours") |
| 4403 | 4425 | : made.error.kind === "unverified" |
src/http/mcp.ts +15 −1
| @@ -62,6 +62,7 @@ import { | ||
| 62 | 62 | cardFor, |
| 63 | 63 | } from "../web/studio/cards.ts"; |
| 64 | 64 | import { setAccountGrant } from "../actions/model_grant.ts"; |
| 65 | import { ABILITIES, abilitiesFor, roleOf } from "../core/roles.ts"; | |
| 65 | 66 | import { keepThought } from "../actions/thought.ts"; |
| 66 | 67 | import { |
| 67 | 68 | FROM_WORDS, |
| @@ -162,7 +163,7 @@ import { running } from "../kernel/version.ts"; | ||
| 162 | 163 | import { parentForgeFor } from "../core/parent_releases.ts"; |
| 163 | 164 | import { COPIES_PER_DAY, makeItYours } from "../actions/make_it_yours.ts"; |
| 164 | 165 | import { resourceMetadataUrl } from "./oauth.ts"; |
| 165 | import { body, boundedBody, json } from "./respond.ts"; | |
| 166 | import { NOT_MEMBER_MESSAGE, body, boundedBody, json } from "./respond.ts"; | |
| 166 | 167 | import type { Router } from "./router.ts"; |
| 167 | 168 | import { mayReadRuns } from "../actions/runs.ts"; |
| 168 | 169 | import { manifestFor } from "../actions/here.ts"; |
| @@ -955,6 +956,17 @@ const TOOLS: readonly Tool[] = [ | ||
| 955 | 956 | ); |
| 956 | 957 | }, |
| 957 | 958 | }, |
| 959 | { | |
| 960 | name: "can_i", | |
| 961 | description: | |
| 962 | "What you can do on this forge as yourself: your role (guest, member or admin), what it allows, and the table of all three roles. Read-only.", | |
| 963 | inputSchema: { type: "object", properties: {} }, | |
| 964 | writes: false, | |
| 965 | run(ctx, user) { | |
| 966 | const role = roleOf(ctx.app.db, user); | |
| 967 | return good({ role, can: abilitiesFor(role), table: ABILITIES }); | |
| 968 | }, | |
| 969 | }, | |
| 958 | 970 | { |
| 959 | 971 | name: "model_grant", |
| 960 | 972 | description: |
| @@ -1593,6 +1605,8 @@ const TOOLS: readonly Tool[] = [ | ||
| 1593 | 1605 | ? bad("storage_limit", made.error.message) |
| 1594 | 1606 | : made.error.kind === "invalid" |
| 1595 | 1607 | ? bad("invalid", made.error.message) |
| 1608 | : made.error.kind === "not_member" | |
| 1609 | ? bad("not_member", NOT_MEMBER_MESSAGE) | |
| 1596 | 1610 | : made.error.kind === "own" |
| 1597 | 1611 | ? bad("own", "this app is already yours") |
| 1598 | 1612 | : made.error.kind === "unverified" |
src/http/respond.ts +6
| @@ -154,11 +154,17 @@ export function respondAccess(error: string, status: number): Response { | ||
| 154 | 154 | // clients see no difference between the trigger and the setting. |
| 155 | 155 | if (error === "refused") |
| 156 | 156 | return json({ error, message: NEW_ACCOUNT_GUARD_MESSAGE }, 403); |
| 157 | if (error === "not_member") | |
| 158 | return json({ error, message: NOT_MEMBER_MESSAGE }, 403); | |
| 157 | 159 | if (error === "unauthorized") return unauthorized(); |
| 158 | 160 | if (error === "forbidden") return forbidden(); |
| 159 | 161 | return json({ error }, status); |
| 160 | 162 | } |
| 161 | 163 | |
| 164 | /** What a guest is told when it tries to own something (#673). */ | |
| 165 | export const NOT_MEMBER_MESSAGE = | |
| 166 | "This account is a guest: it can read, comment, follow and report. Ask the forge's owner to make you a member."; | |
| 167 | ||
| 162 | 168 | /** Bytes as a JSON object, or `{}` for anything else — malformed input is not a 500. */ |
| 163 | 169 | function asObject(bytes: Uint8Array): Record<string, unknown> { |
| 164 | 170 | let value: unknown; |
src/http/server.ts +3
| @@ -154,6 +154,7 @@ import { | ||
| 154 | 154 | subscriptionWake, |
| 155 | 155 | } from "../web/pages/subscriptions.ts"; |
| 156 | 156 | import { grantAct, modelAdd, modelPage } from "../web/pages/model.ts"; |
| 157 | import { peopleAct, peoplePage } from "../web/pages/people.ts"; | |
| 157 | 158 | import { |
| 158 | 159 | changePassword, |
| 159 | 160 | iconPng, |
| @@ -795,6 +796,8 @@ export function buildRouter(): Router<Handler> { | ||
| 795 | 796 | router.add("POST", "/settings/backups/mirror/clear", backupsMirrorClear); |
| 796 | 797 | router.add("POST", "/settings/backups/mirror/now", backupsMirrorNow); |
| 797 | 798 | router.add("GET", "/settings/accounts", accountsPage); |
| 799 | router.add("GET", "/settings/people", peoplePage); | |
| 800 | router.add("POST", "/settings/people/:username", peopleAct); | |
| 798 | 801 | router.add("GET", "/settings/model", modelPage); |
| 799 | 802 | router.add("POST", "/settings/model", modelAdd); |
| 800 | 803 | router.add("POST", "/settings/accounts/:username/model", grantAct); |
src/tui/forge.ts +16
| @@ -48,6 +48,7 @@ import { flagsScreen } from "./screens/flags.ts"; | ||
| 48 | 48 | import { cloudScreen } from "./screens/cloud.ts"; |
| 49 | 49 | import { usageScreen } from "./screens/usage.ts"; |
| 50 | 50 | import { modelGrantPrompt, modelScreen } from "./screens/model.ts"; |
| 51 | import { peopleScreen, rolePrompt } from "./screens/people.ts"; | |
| 51 | 52 | import { proposalTokensPrompt } from "./screens/proposal_tokens.ts"; |
| 52 | 53 | import { quotasScreen } from "./screens/quotas.ts"; |
| 53 | 54 | import { domainsScreen } from "./screens/domains.ts"; |
| @@ -379,6 +380,21 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] { | ||
| 379 | 380 | hint: "what your crew may spend, and add your own subscription", |
| 380 | 381 | run: () => ctx.push(modelScreen(session, ctx)), |
| 381 | 382 | }); |
| 383 | // Roles, as /settings/people has them (#673). | |
| 384 | if (session.user?.kind === "user") | |
| 385 | commands.push({ | |
| 386 | id: "roles", | |
| 387 | title: "Roles", | |
| 388 | hint: "guest, member, admin: what each can do, and which you are", | |
| 389 | run: () => ctx.push(peopleScreen(session, ctx)), | |
| 390 | }); | |
| 391 | if (session.user?.isAdmin === true && session.user.kind === "user") | |
| 392 | commands.push({ | |
| 393 | id: "role-set", | |
| 394 | title: "Set a role", | |
| 395 | hint: "make an account a member (with an allowance) or a guest", | |
| 396 | run: () => ctx.push(rolePrompt(session, ctx, blank("Set a role"))), | |
| 397 | }); | |
| 382 | 398 | // A capped monthly grant to an account: a forge admin who is a person (#1145). |
| 383 | 399 | if (session.user?.isAdmin === true && session.user.kind === "user") |
| 384 | 400 | commands.push({ |
src/tui/screens/people.ts added +91
| @@ -0,0 +1,91 @@ | ||
| 1 | /** | |
| 2 | * Roles in the terminal, as `/settings/people` has them: a person sees the | |
| 3 | * role they hold and what it allows; a forge admin who is a person has a | |
| 4 | * second command that makes an account a member (with an optional starter | |
| 5 | * allowance) or a guest. Every rule is the action's (`actions/roles.ts`). | |
| 6 | */ | |
| 7 | ||
| 8 | import { setRole } from "../../actions/roles.ts"; | |
| 9 | import { ABILITIES, abilitiesFor, roleOf } from "../../core/roles.ts"; | |
| 10 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 11 | import { binding } from "../app/keys.ts"; | |
| 12 | import { style } from "../term/style.ts"; | |
| 13 | import { truncate } from "../term/width.ts"; | |
| 14 | import type { Session } from "../session.ts"; | |
| 15 | import { later, promptScreen } from "./common.ts"; | |
| 16 | ||
| 17 | /** The signed-in person's role, and the table of what each role can do. */ | |
| 18 | export function peopleScreen(f: Session, ctx: Ctx): Screen { | |
| 19 | return { | |
| 20 | title: "Roles", | |
| 21 | keys: [binding(["esc"], "back")], | |
| 22 | render(area, s) { | |
| 23 | const c = ctx.theme.c; | |
| 24 | const user = f.user; | |
| 25 | const mine = user === undefined ? undefined : roleOf(f.app.db, user); | |
| 26 | const lines = [ | |
| 27 | mine === undefined ? "Sign in to see your role." : `You are a ${mine}: ${abilitiesFor(mine).join("; ").toLowerCase()}.`, | |
| 28 | "", | |
| 29 | " guest member admin", | |
| 30 | ...ABILITIES.map( | |
| 31 | (a) => `${a.can.slice(0, 46).padEnd(46)} ${a.guest ? "yes" : "- "} ${a.member ? "yes" : "- "} ${a.admin ? "yes" : "-"}`, | |
| 32 | ), | |
| 33 | ]; | |
| 34 | // Who holds which role, as the page lists it: for an admin who is a person. | |
| 35 | if (user?.isAdmin === true && user.kind === "user") { | |
| 36 | lines.push("", "Who holds which role"); | |
| 37 | const rows = f.app.db | |
| 38 | .query<{ id: string; username: string; is_admin: number; kind: string }, []>( | |
| 39 | "SELECT id, username, is_admin, kind FROM user WHERE kind = 'user' ORDER BY created_at DESC, username LIMIT 200", | |
| 40 | ) | |
| 41 | .all(); | |
| 42 | for (const p of rows) | |
| 43 | lines.push(` ${p.username} ${roleOf(f.app.db, { id: p.id, isAdmin: p.is_admin === 1, kind: p.kind })}`); | |
| 44 | } | |
| 45 | lines.slice(0, area.h).forEach((l, i) => | |
| 46 | s.text(area.x, area.y + i, truncate(l, area.w), style(c.mutedFg, c.bg), area.x + area.w), | |
| 47 | ); | |
| 48 | }, | |
| 49 | key: () => false, | |
| 50 | }; | |
| 51 | } | |
| 52 | ||
| 53 | /** Admin: an account's name, member or guest, then (for a member) an optional dollars a month. */ | |
| 54 | export function rolePrompt(f: Session, ctx: Ctx, parent: Screen): Screen { | |
| 55 | return promptScreen(ctx, parent, { | |
| 56 | title: "Set a role", | |
| 57 | label: "account name", | |
| 58 | onSubmit: (name) => | |
| 59 | later(ctx, () => | |
| 60 | promptScreen(ctx, parent, { | |
| 61 | title: `Role for ${name.trim()}`, | |
| 62 | label: "member or guest", | |
| 63 | onSubmit: (to) => { | |
| 64 | const role = to.trim().toLowerCase(); | |
| 65 | if (role === "guest") return finish(f, ctx, name.trim(), "guest", null); | |
| 66 | if (role !== "member") return "Say member or guest."; | |
| 67 | return later(ctx, () => | |
| 68 | promptScreen(ctx, parent, { | |
| 69 | title: `Allowance for ${name.trim()}`, | |
| 70 | label: "dollars a month (empty or none for no allowance)", | |
| 71 | onSubmit: (raw) => { | |
| 72 | const text = raw.trim().toLowerCase(); | |
| 73 | const usd = text === "" || text === "none" || text === "0" ? null : Number(text); | |
| 74 | if (usd !== null && !Number.isFinite(usd)) return "Dollars a month, like 5 — or none."; | |
| 75 | return finish(f, ctx, name.trim(), "member", usd); | |
| 76 | }, | |
| 77 | }), | |
| 78 | ); | |
| 79 | }, | |
| 80 | }), | |
| 81 | ), | |
| 82 | }); | |
| 83 | } | |
| 84 | ||
| 85 | function finish(f: Session, ctx: Ctx, name: string, to: "guest" | "member", usd: number | null): string | undefined { | |
| 86 | const done = setRole(f.app, f.user, name, to, usd); | |
| 87 | if (!done.ok) | |
| 88 | return done.error === "invalid_amount" ? "That amount will not do." : done.error === "not_allowed" ? "An admin or an agent has no role to change." : "No such account."; | |
| 89 | ctx.toast(`${name} is a ${done.value.role}${done.value.grantTakenBack ? "; its model grant is taken back" : ""}.`); | |
| 90 | return undefined; | |
| 91 | } |
src/web/pages/origins.ts +7
| @@ -74,6 +74,7 @@ export type AccountSection = | ||
| 74 | 74 | | "tokens" |
| 75 | 75 | | "keys" |
| 76 | 76 | | "model" |
| 77 | | "people" | |
| 77 | 78 | | "passkeys" |
| 78 | 79 | | "origins" |
| 79 | 80 | | "usage" |
| @@ -189,6 +190,12 @@ export function accountSections( | ||
| 189 | 190 | icon: "user", |
| 190 | 191 | current: current === "profile", |
| 191 | 192 | }, |
| 193 | { | |
| 194 | label: "People", | |
| 195 | href: "/settings/people", | |
| 196 | icon: "users", | |
| 197 | current: current === "people", | |
| 198 | }, | |
| 192 | 199 | { |
| 193 | 200 | label: "Model", |
| 194 | 201 | href: "/settings/model", |
src/web/pages/people.ts added +126
| @@ -0,0 +1,126 @@ | ||
| 1 | /** | |
| 2 | * People — what each role can do, in one table, and the role you hold. A | |
| 3 | * forge admin also sees every person with a promote or demote button, and | |
| 4 | * the starter allowance to give on promoting (default none). | |
| 5 | */ | |
| 6 | ||
| 7 | import { setRole } from "../../actions/roles.ts"; | |
| 8 | import { ABILITIES, abilitiesFor, roleOf } from "../../core/roles.ts"; | |
| 9 | import { GRANT_MAX_USD } from "../../core/model_grant.ts"; | |
| 10 | import type { Ctx } from "../../http/context.ts"; | |
| 11 | import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts"; | |
| 12 | import { field, readForm } from "../form.ts"; | |
| 13 | import { html, type Html } from "../html.ts"; | |
| 14 | import { flashTo, page } from "../layout.ts"; | |
| 15 | import { btn, card } from "../ui.ts"; | |
| 16 | import { accountOnly, accountSections } from "./origins.ts"; | |
| 17 | ||
| 18 | const mark = (yes: boolean): string => (yes ? "yes" : "—"); | |
| 19 | ||
| 20 | export function rolesTable(): Html { | |
| 21 | return html`<table class="table" id="roles-table"> | |
| 22 | <thead> | |
| 23 | <tr><th>Can</th><th>Guest</th><th>Member</th><th>Admin</th></tr> | |
| 24 | </thead> | |
| 25 | <tbody> | |
| 26 | ${ABILITIES.map( | |
| 27 | (a) => html`<tr> | |
| 28 | <td>${a.can}</td><td>${mark(a.guest)}</td><td>${mark(a.member)}</td><td>${mark(a.admin)}</td> | |
| 29 | </tr>`, | |
| 30 | )} | |
| 31 | </tbody> | |
| 32 | </table>`; | |
| 33 | } | |
| 34 | ||
| 35 | // GET /settings/people | |
| 36 | export function peoplePage(ctx: Ctx): Response { | |
| 37 | const denied = accountOnly(ctx); | |
| 38 | if (denied) return denied; | |
| 39 | const db = ctx.app.db; | |
| 40 | const me = ctx.auth.user!; | |
| 41 | const mine = roleOf(db, me); | |
| 42 | const rows = me.isAdmin | |
| 43 | ? db | |
| 44 | .query<{ username: string; is_admin: number; id: string; kind: string }, []>( | |
| 45 | "SELECT id, username, is_admin, kind FROM user WHERE kind = 'user' ORDER BY created_at DESC, username", | |
| 46 | ) | |
| 47 | .all() | |
| 48 | : []; | |
| 49 | const people = me.isAdmin | |
| 50 | ? card( | |
| 51 | html`<ul class="rows"> | |
| 52 | ${rows.map((p) => { | |
| 53 | const role = roleOf(db, { id: p.id, isAdmin: p.is_admin === 1, kind: p.kind }); | |
| 54 | const at = `/settings/people/${encodeURIComponent(p.username)}`; | |
| 55 | return html`<li class="row"> | |
| 56 | <div class="row-main"><strong>${p.username}</strong> <span class="muted">${role}</span></div> | |
| 57 | ${role === "admin" | |
| 58 | ? null | |
| 59 | : role === "guest" | |
| 60 | ? html`<form class="row-actions" method="post" action="${at}"> | |
| 61 | <input type="hidden" name="role" value="member" /> | |
| 62 | <input class="input" name="usd" inputmode="decimal" autocomplete="off" | |
| 63 | aria-label="Starter allowance, dollars a month" placeholder="allowance $/month (none)" /> | |
| 64 | ${btn("Make member", { type: "submit", size: "sm", variant: "primary" })} | |
| 65 | </form>` | |
| 66 | : html`<form class="row-actions" method="post" action="${at}"> | |
| 67 | <input type="hidden" name="role" value="guest" /> | |
| 68 | ${btn("Make guest", { type: "submit", size: "sm" })} | |
| 69 | </form>`} | |
| 70 | </li>`; | |
| 71 | })} | |
| 72 | </ul>`, | |
| 73 | { | |
| 74 | head: html`<h2>Who holds which role</h2> | |
| 75 | <p class="muted">Promoting is one act. The allowance is optional, up to | |
| 76 | $${GRANT_MAX_USD} a month on the forge's credential; none by default.</p>`, | |
| 77 | }, | |
| 78 | ) | |
| 79 | : null; | |
| 80 | return page({ | |
| 81 | ctx, | |
| 82 | title: "People", | |
| 83 | body: html`<div class="page-head"><h1>People</h1></div> | |
| 84 | ${settingsLayout( | |
| 85 | accountSections("people", { admin: me.isAdmin }), | |
| 86 | html`${card( | |
| 87 | html`${rolesTable()} | |
| 88 | <p id="my-role">You are a <strong>${mine}</strong>: you can | |
| 89 | ${abilitiesFor(mine).join("; ").toLowerCase()}.</p>`, | |
| 90 | { | |
| 91 | head: html`<h2>Guest, member, admin</h2> | |
| 92 | <p class="muted">What an account can do on this forge. A guest cannot | |
| 93 | create, fork or copy a repository; a member can.</p>`, | |
outdated
"A member cannot take over: not by intent, not by accident" is shown to every account. With no role gate and no member-run cell-escape proofs, it isn't true yet. Remove it until it is enforced and tested. |
||
| 94 | }, | |
| 95 | )}${people}`, | |
| 96 | "Account settings", | |
| 97 | )}`, | |
| 98 | }); | |
| 99 | } | |
| 100 | ||
| 101 | // POST /settings/people/:username | |
| 102 | export async function peopleAct(ctx: Ctx): Promise<Response> { | |
| 103 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 104 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); | |
| 105 | const form = await readForm(ctx, "admin"); | |
| 106 | if (form instanceof Response) return form; | |
| 107 | const username = ctx.params.username ?? ""; | |
| 108 | const to = field(form, "role"); | |
| 109 | if (to !== "member" && to !== "guest") return notFoundPage(ctx); | |
| 110 | const raw = field(form, "usd").trim().replace(/^\$/, ""); | |
| 111 | const usd = raw === "" || Number(raw) === 0 ? null : /^\d{1,6}(\.\d{1,2})?$/.test(raw) ? Number(raw) : NaN; | |
| 112 | const done = setRole(ctx.app, ctx.auth.user, username, to, usd); | |
| 113 | if (!done.ok) { | |
| 114 | if (done.error === "not_found") return notFoundPage(ctx); | |
| 115 | return flashTo(ctx, "/settings/people", { | |
| 116 | tone: "danger", | |
| 117 | message: | |
| 118 | done.error === "invalid_amount" | |
| 119 | ? `An allowance is dollars a month, from 0.01 to ${GRANT_MAX_USD}.` | |
| 120 | : "An admin or an agent has no role to change here.", | |
| 121 | }); | |
| 122 | } | |
| 123 | return flashTo(ctx, "/settings/people", { | |
| 124 | message: `${username} is a ${done.value.role}${done.value.usdPerMonth === null ? "" : `, with $${done.value.usdPerMonth.toFixed(2)} a month`}${done.value.grantTakenBack ? "; its model grant is taken back" : ""}.`, | |
| 125 | }); | |
| 126 | } |
src/web/studio/make_it_yours.ts +6 −1
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | |
| 8 | 8 | import { COPIES_PER_DAY, makeItYours } from "../../actions/make_it_yours.ts"; |
| 9 | 9 | import type { Ctx } from "../../http/context.ts"; |
| 10 | import { NOT_MEMBER_MESSAGE } from "../../http/respond.ts"; | |
| 10 | 11 | import { |
| 11 | 12 | loadRepo, |
| 12 | 13 | notFoundPage, |
| @@ -39,7 +40,9 @@ export async function makeItYoursPage(ctx: Ctx): Promise<Response> { | ||
| 39 | 40 | message: |
| 40 | 41 | plan.error.kind === "invalid" |
| 41 | 42 | ? plan.error.message |
| 42 | : "That could not be made yours.", | |
| 43 | : plan.error.kind === "not_member" | |
| 44 | ? NOT_MEMBER_MESSAGE | |
| 45 | : "That could not be made yours.", | |
| 43 | 46 | }); |
| 44 | 47 | } |
| 45 | 48 | const p = plan.value; |
| @@ -128,6 +131,8 @@ export async function makeItYoursSubmit(ctx: Ctx): Promise<Response> { | ||
| 128 | 131 | const message = !made.ok |
| 129 | 132 | ? made.error.kind === "invalid" |
| 130 | 133 | ? made.error.message |
| 134 | : made.error.kind === "not_member" | |
| 135 | ? NOT_MEMBER_MESSAGE | |
| 131 | 136 | : made.error.kind === "repository_limit" || made.error.kind === "storage_limit" |
| 132 | 137 | ? `Not made: ${made.error.message}.` |
| 133 | 138 | : made.error.kind === "own" |
test/accounts.test.ts +2
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 2 | import { promote } from "../src/core/roles.ts"; | |
| 2 | 3 | import { existsSync, renameSync } from "node:fs"; |
| 3 | 4 | import { mkdtemp, rm } from "node:fs/promises"; |
| 4 | 5 | import { tmpdir } from "node:os"; |
| @@ -626,6 +627,7 @@ describe("accounts: the owner sees, suspends and removes", () => { | ||
| 626 | 627 | const create = () => |
| 627 | 628 | api("/api/v1/repos", { method: "POST", token, body: JSON.stringify({ name: "first" }) }); |
| 628 | 629 | expect((await create()).status).toBe(403); |
| 630 | promote(app.db, made.value.id, made.value.id, new Date()); | |
| 629 | 631 | |
| 630 | 632 | // Nobody but the owner may say so. |
| 631 | 633 | expect( |
test/asks.test.ts +2
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | * in the header. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { promote } from "../src/core/roles.ts"; | |
| 7 | 8 | import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; |
| 8 | 9 | import { mkdtemp, rm } from "node:fs/promises"; |
| 9 | 10 | import { tmpdir } from "node:os"; |
| @@ -401,6 +402,7 @@ describe("the asks page", () => { | ||
| 401 | 402 | const carol = await signUp("carol"); |
| 402 | 403 | const carolUser = getUserByName(app.db, "carol")!; |
| 403 | 404 | markVerified(app.db, carolUser.id, new Date().toISOString()); |
| 405 | promote(app.db, carolUser.id, carolUser.id, new Date()); | |
| 404 | 406 | const plot = await createRepo(app, carolUser, { name: "plot", visibility: "public" }); |
| 405 | 407 | if (!plot.ok) throw new Error(String(plot.error)); |
| 406 | 408 | away("cells.egress", "report"); |
test/helpers/verified.ts +8
| @@ -6,6 +6,8 @@ import { signUp as signUpAction } from "../../src/actions/users.ts"; | ||
| 6 | 6 | * something else (forks, origins, migration) whose people sign up over |
| 7 | 7 | * HTTP and then make things: verification has its own suite |
| 8 | 8 | * (`test/verify-email.test.ts`), and here it would only be in the way. |
| 9 | * They are also made members, for the same reason: creating a repository | |
| 10 | * needs the role, which `test/roles.test.ts` proves on its own. | |
| 9 | 11 | */ |
| 10 | 12 | export function proveAll(app: App): void { |
| 11 | 13 | app.db |
| @@ -13,6 +15,12 @@ export function proveAll(app: App): void { | ||
| 13 | 15 | "UPDATE email_check SET verified_at = ?1 WHERE verified_at IS NULL", |
| 14 | 16 | ) |
| 15 | 17 | .run(new Date().toISOString()); |
| 18 | app.db | |
| 19 | .query( | |
| 20 | `INSERT OR IGNORE INTO member (user_id, promoted_by, promoted_at) | |
| 21 | SELECT id, 'test', ?1 FROM user WHERE kind = 'user'`, | |
| 22 | ) | |
| 23 | .run(new Date().toISOString()); | |
| 16 | 24 | } |
| 17 | 25 | |
| 18 | 26 | /** `signUp`, with the new account's email already proven. */ |
test/mcp.test.ts +1
| @@ -177,6 +177,7 @@ describe("the forge over MCP", () => { | ||
| 177 | 177 | "stop", |
| 178 | 178 | "health", |
| 179 | 179 | "audit", |
| 180 | "can_i", | |
| 180 | 181 | "model_grant", |
| 181 | 182 | "outsiders", |
| 182 | 183 | "decisions_by", |
test/member-grandfather.test.ts added +22
| @@ -0,0 +1,22 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 2 | import { Database } from "bun:sqlite"; | |
| 3 | import migration from "../src/core/migrations/20261016180100-member-grandfather.ts"; | |
| 4 | ||
| 5 | test("owners and the writers of an org that owns a repository are grandfathered; others stay guests", () => { | |
| 6 | const db = new Database(":memory:"); | |
| 7 | db.run(` | |
| 8 | CREATE TABLE user (id TEXT PRIMARY KEY, kind TEXT NOT NULL); | |
| 9 | CREATE TABLE repo (id TEXT PRIMARY KEY, owner_id TEXT NOT NULL); | |
| 10 | CREATE TABLE team (id TEXT PRIMARY KEY, org_id TEXT NOT NULL, permission TEXT NOT NULL); | |
| 11 | CREATE TABLE team_member (team_id TEXT NOT NULL, user_id TEXT NOT NULL); | |
| 12 | CREATE TABLE member (user_id TEXT PRIMARY KEY, promoted_by TEXT, promoted_at TEXT); | |
| 13 | INSERT INTO user VALUES ('owner','user'),('writer','user'),('admin','user'),('reader','user'), | |
| 14 | ('idle','user'),('emptyorgwriter','user'),('acme','org'),('empty','org'); | |
| 15 | INSERT INTO repo VALUES ('r1','owner'),('r2','acme'); | |
| 16 | INSERT INTO team VALUES ('tw','acme','write'),('ta','acme','admin'),('tr','acme','read'),('te','empty','write'); | |
| 17 | INSERT INTO team_member VALUES ('tw','writer'),('ta','admin'),('tr','reader'),('te','emptyorgwriter'); | |
| 18 | `); | |
| 19 | db.run(migration); | |
| 20 | const members = db.query<{ user_id: string }, []>("SELECT user_id FROM member ORDER BY user_id").all().map((r) => r.user_id); | |
| 21 | expect(members).toEqual(["admin", "owner", "writer"]); | |
| 22 | }); |
test/roles.test.ts added +256
| @@ -0,0 +1,256 @@ | ||
| 1 | /** | |
| 2 | * Guest, member, admin (#673): the table, the one-act promotion, the MCP | |
| 3 | * read, and a member actor who tries each takeover that is reachable over | |
| 4 | * HTTP and is refused. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, readFile, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { getModelGrant } from "../src/core/model_grant.ts"; | |
| 14 | import { ABILITIES, demote, roleOf } from "../src/core/roles.ts"; | |
| 15 | import { forkRepo } from "../src/actions/repos.ts"; | |
| 16 | import { makeItYours } from "../src/actions/make_it_yours.ts"; | |
| 17 | import { newApp } from "../src/actions/apps.ts"; | |
| 18 | import { createAgentRow } from "../src/core/agents.ts"; | |
| 19 | import { createToken } from "../src/core/tokens.ts"; | |
| 20 | import { getRepo } from "../src/core/repos.ts"; | |
| 21 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 22 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 23 | import { quietLogs } from "./helpers/globals.ts"; | |
| 24 | ||
| 25 | quietLogs(); | |
| 26 | ||
| 27 | const PASS = "a-long-roles-passphrase"; | |
| 28 | ||
| 29 | describe("roles", () => { | |
| 30 | let dataDir = ""; | |
| 31 | let app: App; | |
| 32 | let servers: Servers; | |
| 33 | const tokens: Record<string, string> = {}; | |
| 34 | ||
| 35 | const signIn = async (username: string) => { | |
| 36 | const res = await fetch(`${servers.url}/signin`, { | |
| 37 | method: "POST", | |
| 38 | body: new URLSearchParams({ username, password: PASS }), | |
| 39 | redirect: "manual", | |
| 40 | }); | |
| 41 | return (res.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 42 | }; | |
| 43 | const api = (who: string, method: string, path: string, body?: unknown) => | |
| 44 | fetch(`${servers.url}${path}`, { | |
| 45 | method, | |
| 46 | headers: { authorization: `Bearer ${tokens[who]}`, "content-type": "application/json" }, | |
| 47 | ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 48 | }); | |
| 49 | const mcp = async (who: string, name: string, args: unknown = {}) => { | |
| 50 | const res = await fetch(`${servers.url}/mcp`, { | |
| 51 | method: "POST", | |
| 52 | headers: { | |
| 53 | authorization: `Bearer ${tokens[who]}`, | |
| 54 | "content-type": "application/json", | |
| 55 | accept: "application/json, text/event-stream", | |
| 56 | }, | |
| 57 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }), | |
| 58 | }); | |
| 59 | return (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } }; | |
| 60 | }; | |
| 61 | ||
| 62 | beforeAll(async () => { | |
| 63 | dataDir = await mkdtemp(join(tmpdir(), "forge-roles-")); | |
| 64 | app = createApp({ dataDir, port: 0 }); | |
| 65 | servers = await serve(app); | |
| 66 | for (const [username, isAdmin] of [["alice", true], ["bob", false], ["carol", false], ["dave", false]] as const) { | |
| 67 | const made = await createUser(app.db, { | |
| 68 | trusted: true, | |
| 69 | username, | |
| 70 | email: `${username}@x.test`, | |
| 71 | password: PASS, | |
| 72 | isAdmin, | |
| 73 | }); | |
| 74 | if (!made.ok) throw new Error(username); | |
| 75 | tokens[username] = createToken(app.db, made.value.id, "t", "admin").token; | |
| 76 | } | |
| 77 | const carol = getUserByName(app.db, "carol")!; | |
| 78 | const made = await createRepo(app, carol, { name: "secret", visibility: "private" }); | |
| 79 | if (!made.ok) throw new Error(made.error); | |
| 80 | const garden = await newApp(app, carol, { name: "garden", visibility: "public" }); | |
| 81 | if (!garden.ok) throw new Error(String(garden.error)); | |
| 82 | // A vouched fixture is a member; these start where a fresh account does. | |
| 83 | for (const name of ["bob", "carol", "dave"]) demote(app.db, getUserByName(app.db, name)!.id); | |
| 84 | }, 30_000); | |
| 85 | ||
| 86 | afterAll(async () => { | |
| 87 | servers.stop(); | |
| 88 | app.close(); | |
| 89 | await rm(dataDir, { recursive: true, force: true }); | |
| 90 | }); | |
| 91 | ||
| 92 | const role = (name: string) => roleOf(app.db, getUserByName(app.db, name)!); | |
| 93 | ||
| 94 | test("a fresh account is a guest, an admin is an admin", () => { | |
| 95 | expect(role("bob")).toBe("guest"); | |
| 96 | expect(role("alice")).toBe("admin"); | |
| 97 | }); | |
| 98 | ||
| 99 | test("the docs carry every row of the table", async () => { | |
| 100 | const doc = await readFile(join(import.meta.dir, "../docs/ROLES.md"), "utf8"); | |
| 101 | for (const a of ABILITIES) expect(doc).toContain(a.can); | |
| 102 | }); | |
| 103 | ||
| 104 | test("the page shows the table and the role you hold", async () => { | |
| 105 | const html = await (await fetch(`${servers.url}/settings/people`, { headers: { cookie: await signIn("bob") } })).text(); | |
| 106 | expect(html).toContain('id="roles-table"'); | |
| 107 | expect(html).toContain("You are a <strong>guest</strong>"); | |
| 108 | expect(html).not.toContain("Make member"); | |
| 109 | }); | |
| 110 | ||
| 111 | test("a guest cannot promote anyone, by page or API", async () => { | |
| 112 | const cookie = await signIn("bob"); | |
| 113 | const res = await fetch(`${servers.url}/settings/people/dave`, { | |
| 114 | method: "POST", | |
| 115 | headers: { cookie, origin: servers.url }, | |
| 116 | body: new URLSearchParams({ role: "member" }), | |
| 117 | redirect: "manual", | |
| 118 | }); | |
| 119 | expect(res.status).toBe(404); | |
| 120 | expect((await api("bob", "POST", "/api/v1/admin/accounts/bob/role", { role: "member" })).status).toBe(404); | |
| 121 | expect(role("bob")).toBe("guest"); | |
| 122 | }); | |
| 123 | ||
| 124 | test("the role gates owning: a guest is refused, the same account let in once promoted", async () => { | |
| 125 | const dave = () => getUserByName(app.db, "dave")!; | |
| 126 | expect(role("dave")).toBe("guest"); | |
| 127 | const refused = await createRepo(app, dave(), { name: "mine" }); | |
| 128 | expect(!refused.ok && refused.error).toBe("not_member"); | |
| 129 | // A public repository with a public app: dave can read it, so only the role refuses. | |
| 130 | const garden = getRepo(app.db, "carol", "garden")!; | |
| 131 | const forked = await forkRepo(app, dave(), garden); | |
| 132 | expect(!forked.ok && forked.error).toBe("not_member"); | |
| 133 | const app1 = await newApp(app, dave(), { name: "thing" }); | |
| 134 | expect(!app1.ok && app1.error).toBe("not_member"); | |
| 135 | const copy = await makeItYours(app, dave(), garden, { dryRun: true }); | |
| 136 | expect(!copy.ok && copy.error.kind).toBe("not_member"); | |
| 137 | const viaApi = await api("dave", "POST", "/api/v1/repos/carol/garden/make-it-yours", {}); | |
| 138 | expect(viaApi.status).toBe(403); | |
| 139 | expect(((await viaApi.json()) as { error: string }).error).toBe("not_member"); | |
| 140 | ||
| 141 | expect((await api("alice", "POST", "/api/v1/admin/accounts/dave/role", { role: "member" })).status).toBe(200); | |
| 142 | const let_in = await createRepo(app, dave(), { name: "mine" }); | |
| 143 | expect(let_in.ok).toBe(true); | |
| 144 | expect((await forkRepo(app, dave(), garden)).ok).toBe(true); | |
| 145 | const planned = await makeItYours(app, dave(), garden, { dryRun: true }); | |
| 146 | expect(planned.ok).toBe(true); | |
| 147 | ||
| 148 | // and back: the role is read at every act, not remembered | |
| 149 | await api("alice", "POST", "/api/v1/admin/accounts/dave/role", { role: "guest" }); | |
| 150 | const again = await createRepo(app, dave(), { name: "second" }); | |
| 151 | expect(!again.ok && again.error).toBe("not_member"); | |
| 152 | }); | |
| 153 | ||
| 154 | test("the API says why a guest is refused", async () => { | |
| 155 | const res = await api("dave", "POST", "/api/v1/repos", { name: "viaapi" }); | |
| 156 | expect(res.status).toBe(403); | |
| 157 | expect(((await res.json()) as { error: string }).error).toBe("not_member"); | |
| 158 | }); | |
| 159 | ||
| 160 | test("an agent holds its maker's role, never more", async () => { | |
| 161 | const mk = async (name: string, by: string) => { | |
| 162 | const r = await createUser(app.db, { username: name, email: `${name}@x.test`, password: PASS, agent: true }); | |
| 163 | if (!r.ok) throw new Error(name); | |
| 164 | createAgentRow(app.db, { userId: r.value.id, createdBy: getUserByName(app.db, by)!.id }); | |
| 165 | return roleOf(app.db, r.value); | |
| 166 | }; | |
| 167 | expect(await mk("gcrew", "dave")).toBe("guest"); | |
| 168 | expect(await mk("acrew", "alice")).toBe("member"); | |
| 169 | }); | |
| 170 | ||
| 171 | test("the owner promotes in one act; the allowance defaults to none", async () => { | |
| 172 | const res = await api("alice", "POST", "/api/v1/admin/accounts/bob/role", { role: "member" }); | |
| 173 | expect(res.status).toBe(200); | |
| 174 | expect(role("bob")).toBe("member"); | |
| 175 | expect(getModelGrant(app.db, getUserByName(app.db, "bob")!.id)).toBeUndefined(); | |
| 176 | ||
| 177 | const cookie = await signIn("alice"); | |
| 178 | const page = await fetch(`${servers.url}/settings/people/dave`, { | |
| 179 | method: "POST", | |
| 180 | headers: { cookie, origin: servers.url }, | |
| 181 | body: new URLSearchParams({ role: "member", usd: "5" }), | |
| 182 | redirect: "manual", | |
| 183 | }); | |
| 184 | expect(page.status).toBeLessThan(400); | |
| 185 | expect(role("dave")).toBe("member"); | |
| 186 | expect(getModelGrant(app.db, getUserByName(app.db, "dave")!.id)?.usdPerMonth).toBe(5); | |
| 187 | }); | |
| 188 | ||
| 189 | test("an allowance out of range promotes no one", async () => { | |
| 190 | const res = await api("alice", "POST", "/api/v1/admin/accounts/carol/role", { role: "member", usdPerMonth: 99999999 }); | |
| 191 | expect(res.status).toBe(422); | |
| 192 | expect(role("carol")).toBe("guest"); | |
| 193 | }); | |
| 194 | ||
| 195 | test("MCP can_i says the role and what it allows", async () => { | |
| 196 | const out = await mcp("bob", "can_i"); | |
| 197 | const said = JSON.parse(out.result.content[0]!.text); | |
| 198 | expect(said.role).toBe("member"); | |
| 199 | expect(said.can.join(" ")).toContain("Own repositories"); | |
| 200 | expect(said.can.join(" ")).not.toContain("Change forge settings"); | |
| 201 | }); | |
| 202 | ||
| 203 | describe("a member actor tries each takeover over HTTP and is refused", () => { | |
| 204 | test("forge administration: accounts, grants, roles", async () => { | |
| 205 | for (const [path, body] of [ | |
| 206 | ["/api/v1/admin/accounts/carol/model-grant", { usdPerMonth: 9000 }], | |
| 207 | ["/api/v1/admin/accounts/carol/suspend", {}], | |
| 208 | ["/api/v1/admin/accounts/bob/model-grant", { usdPerMonth: 9000 }], | |
| 209 | ["/api/v1/admin/accounts/carol/role", { role: "member" }], | |
| 210 | ] as const) | |
| 211 | expect((await api("bob", "POST", path, body)).status).toBe(404); | |
| 212 | expect(getModelGrant(app.db, getUserByName(app.db, "bob")!.id)).toBeUndefined(); | |
| 213 | expect(role("carol")).toBe("guest"); | |
| 214 | }); | |
| 215 | ||
| 216 | test("the model_grant MCP tool is refused", async () => { | |
| 217 | const out = await mcp("bob", "model_grant", { username: "bob", usdPerMonth: 500, dryRun: false }); | |
| 218 | expect(out.result.isError).toBe(true); | |
| 219 | expect(getModelGrant(app.db, getUserByName(app.db, "bob")!.id)).toBeUndefined(); | |
| 220 | }); | |
| 221 | ||
| 222 | test("another account's private repository is not found", async () => { | |
| 223 | expect((await api("bob", "GET", "/api/v1/repos/carol/secret")).status).toBe(404); | |
| 224 | }); | |
| 225 | ||
| 226 | test("a token a member mints acts as the member, not wider", async () => { | |
| 227 | const minted = await api("bob", "POST", "/api/v1/tokens", { name: "wide", scope: "admin", username: "bob", password: PASS }); | |
| 228 | const wide = ((await minted.json()) as { token: string }).token; | |
| 229 | const res = await fetch(`${servers.url}/api/v1/admin/accounts/carol/suspend`, { | |
| 230 | method: "POST", | |
| 231 | headers: { authorization: `Bearer ${wide}`, "content-type": "application/json" }, | |
| 232 | body: "{}", | |
| 233 | }); | |
| 234 | expect(res.status).toBe(404); | |
| 235 | expect((await fetch(`${servers.url}/api/v1/repos/carol/secret`, { headers: { authorization: `Bearer ${wide}` } })).status).toBe(404); | |
| 236 | }); | |
| 237 | ||
| 238 | test("forge settings pages are not found", async () => { | |
| 239 | const cookie = await signIn("bob"); | |
| 240 | for (const path of ["/settings/accounts", "/settings/secrets", "/settings/backups"]) | |
| 241 | expect((await fetch(`${servers.url}${path}`, { headers: { cookie } })).status).toBe(404); | |
| 242 | }); | |
| 243 | }); | |
| 244 | ||
| 245 | test("demoting says when it took a model grant back", async () => { | |
| 246 | const eve = await createUser(app.db, { trusted: true, username: "eve", email: "[email protected]", password: PASS }); | |
| 247 | if (!eve.ok) throw new Error("eve"); | |
| 248 | const withGrant = (await api("alice", "POST", "/api/v1/admin/accounts/eve/role", { role: "member", usdPerMonth: 5 })); | |
| 249 | expect(withGrant.status).toBe(200); | |
| 250 | const down = (await (await api("alice", "POST", "/api/v1/admin/accounts/eve/role", { role: "guest" })).json()) as { grantTakenBack: boolean }; | |
| 251 | expect(down.grantTakenBack).toBe(true); | |
| 252 | const again = (await (await api("alice", "POST", "/api/v1/admin/accounts/eve/role", { role: "guest" })).json()) as { grantTakenBack: boolean }; | |
| 253 | expect(again.grantTakenBack).toBe(false); | |
| 254 | }); | |
| 255 | ||
| 256 | }); |
test/tui-onyou.test.ts +2
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * latest set can be undone inside its day. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { promote } from "../src/core/roles.ts"; | |
| 8 | 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 9 | 10 | import { mkdtemp, rm } from "node:fs/promises"; |
| 10 | 11 | import { tmpdir } from "node:os"; |
| @@ -86,6 +87,7 @@ describe("terminal On you: mutes and many in one move", () => { | ||
| 86 | 87 | alice = a.value; |
| 87 | 88 | bob = b.value; |
| 88 | 89 | markVerified(forge.db, bob.id, new Date().toISOString()); |
| 90 | promote(forge.db, bob.id, alice.id, new Date()); | |
| 89 | 91 | const mk = async (name: string) => { |
| 90 | 92 | const r = await createRepo(forge, alice, { name, visibility: "public" }); |
| 91 | 93 | if (!r.ok) throw new Error("repo failed"); |
test/tui-people.test.ts added +102
| @@ -0,0 +1,102 @@ | ||
| 1 | /** | |
| 2 | * Roles in the terminal (#673): a person sees their role; an admin sets one. | |
| 3 | */ | |
| 4 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 5 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 6 | import { tmpdir } from "node:os"; | |
| 7 | import { join } from "node:path"; | |
| 8 | import { createApp, type App as Forge } from "../src/app.ts"; | |
| 9 | import { demote, roleOf } from "../src/core/roles.ts"; | |
| 10 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 11 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 12 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 13 | import type { TuiIdentity } from "../src/tui/session.ts"; | |
| 14 | import { quietLogs } from "./helpers/globals.ts"; | |
| 15 | import { settleApp } from "./helpers/tui.ts"; | |
| 16 | ||
| 17 | quietLogs(); | |
| 18 | ||
| 19 | describe("roles in the terminal", () => { | |
| 20 | let dataDir: string; | |
| 21 | let forge: Forge; | |
| 22 | ||
| 23 | function boot(username: string) { | |
| 24 | const terminal = headlessTerminal(140, 32); | |
| 25 | const user = getUserByName(forge.db, username)!; | |
| 26 | const identity: TuiIdentity = { sshUsername: "t", remoteAddress: "127.0.0.1", user }; | |
| 27 | const { app } = createForgeApp(forge, identity, { terminal, exitHooks: false }); | |
| 28 | app.start(); | |
| 29 | const key = (k: string) => app.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false }); | |
| 30 | return { | |
| 31 | text: () => app.screen.toText(), | |
| 32 | press: async (...keys: string[]) => { | |
| 33 | keys.forEach(key); | |
| 34 | await settleApp(app); | |
| 35 | }, | |
| 36 | ctrl: async (k: string) => { | |
| 37 | app.dispatch({ type: "key", key: k, ctrl: true, alt: false, shift: false }); | |
| 38 | await settleApp(app); | |
| 39 | }, | |
| 40 | type: async (t: string) => { | |
| 41 | for (const ch of t) key(ch); | |
| 42 | await settleApp(app); | |
| 43 | }, | |
| 44 | stop: () => app.stop(), | |
| 45 | }; | |
| 46 | } | |
| 47 | ||
| 48 | beforeAll(async () => { | |
| 49 | dataDir = await mkdtemp(join(tmpdir(), "forge-tui-people-")); | |
| 50 | forge = createApp({ dataDir, port: 0 }); | |
| 51 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { | |
| 52 | const made = await createUser(forge.db, { | |
| 53 | trusted: true, | |
| 54 | username, | |
| 55 | email: `${username}@forge.local`, | |
| 56 | password: "a-good-passphrase", | |
| 57 | adminIfFirst, | |
| 58 | }); | |
| 59 | if (!made.ok) throw new Error(made.error); | |
| 60 | } | |
| 61 | demote(forge.db, getUserByName(forge.db, "bob")!.id); | |
| 62 | }); | |
| 63 | afterAll(async () => { | |
| 64 | forge.close(); | |
| 65 | await rm(dataDir, { recursive: true, force: true }); | |
| 66 | }); | |
| 67 | ||
| 68 | const open = async (h: ReturnType<typeof boot>, title: string) => { | |
| 69 | await h.ctrl("k"); | |
| 70 | await h.type(title); | |
| 71 | await h.press("enter"); | |
| 72 | }; | |
| 73 | ||
| 74 | test("a person sees their role and the table", async () => { | |
| 75 | const h = boot("bob"); | |
| 76 | await open(h, "Roles"); | |
| 77 | expect(h.text()).toContain("You are a guest"); | |
| 78 | expect(h.text()).toContain("Own repositories"); | |
| 79 | h.stop(); | |
| 80 | }); | |
| 81 | ||
| 82 | test("an admin makes a member with an allowance; a guest has no such command", async () => { | |
| 83 | const h = boot("alice"); | |
| 84 | await open(h, "Set a role"); | |
| 85 | await h.type("bob"); | |
| 86 | await h.press("enter"); | |
| 87 | await h.type("member"); | |
| 88 | await h.press("enter"); | |
| 89 | await h.type("5"); | |
| 90 | await h.press("enter"); | |
| 91 | const bob = getUserByName(forge.db, "bob")!; | |
| 92 | expect(roleOf(forge.db, bob)).toBe("member"); | |
| 93 | h.stop(); | |
| 94 | ||
| 95 | demote(forge.db, bob.id); | |
| 96 | const p = boot("bob"); | |
| 97 | await p.ctrl("k"); | |
| 98 | await p.type("Set a role"); | |
| 99 | expect(p.text()).not.toContain("make an account a member"); | |
| 100 | p.stop(); | |
| 101 | }); | |
| 102 | }); |
test/verify-email.test.ts +2
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 2 | import { promote } from "../src/core/roles.ts"; | |
| 2 | 3 | import { mkdtemp, rm } from "node:fs/promises"; |
| 3 | 4 | import { tmpdir } from "node:os"; |
| 4 | 5 | import { join } from "node:path"; |
| @@ -136,6 +137,7 @@ describe("verified email", () => { | ||
| 136 | 137 | expect(followed.status).toBe(200); |
| 137 | 138 | expect(await followed.text()).toContain("verified"); |
| 138 | 139 | expect(emailVerified(app.db, user.id)).toBe(true); |
| 140 | promote(app.db, user.id, user.id, new Date()); | |
| 139 | 141 | const after = await api("/api/v1/repos", token, { |
| 140 | 142 | method: "POST", |
| 141 | 143 | body: JSON.stringify({ name: "first" }), |
new above
offline
This paragraph admits the gap that matters. Nothing reads the role yet, so guest and member are just labels, and the table above shows as fact what is not enforced. Gate repo/app creation and run starts on
roleOf(...) !== "guest"and test both sides (guest refused, the same account let in once promoted).