Public: anyone can read this; the crew can change it.
Access 2: one `may(principal, action, resource)`, with the repository checks behind it first #18065
Merged 8h 54m ago, live in production
mason/forge:mason/18048-access-2-one-may-principal-action-resour → main 0 commits fork 1 thread · 1 unresolved
26 files
changed +778
−198
- docs/ROLES.md
- docs/features/may.md
- src/actions/access.ts
- src/actions/roles.ts
- src/contract/openapi/routes/getApiV1May.ts
- src/contract/openapi/routes/getApiV1User.ts
- src/contract/openapi/routes/index.ts
- src/contract/tags.ts
- src/core/may.ts
- src/core/principal.ts
- src/core/repos.ts
- src/generated/marks.ts
- src/http/api.ts
- src/http/api/may.ts
- src/http/api/user.ts
- src/http/context.ts
- src/http/git_access.ts
- src/http/lazy_lists.ts
- src/http/marks/api-v1-may.json
- src/http/mcp/tools/profile.ts
- src/http/mcp/tools/whoami_can.ts
- src/tui/screens/can.ts
- src/web/pages/account.ts
- src/web/pages/proposal-tokens.ts
- test/may.test.ts
- test/tui-can.test.ts
docs/ROLES.md +3 −1
| @@ -16,7 +16,9 @@ who is asking from today's `Auth`: `anonymous` (a visitor), `session` (the | ||
| 16 | 16 | account itself), one of the token kinds (`ro_token`, `rw_token`, |
| 17 | 17 | `admin_token`, `proposal_token`, `run_token`, `contribute_token`, |
| 18 | 18 | `read_grant_token`, `via_token`), each with a subject (a person, an agent or an |
| 19 | app). Nothing decides on a principal yet, so no route answers differently. | |
| 19 | app); a token also carries its stored scope. `may(principal, action, resource)` | |
| 20 | (`src/core/may.ts`) takes this principal, so there is one way to say who is | |
| 21 | asking. | |
| 20 | 22 | |
| 21 | 23 | An account is a **guest**, a **member** or an **admin**. Admin is the |
| 22 | 24 | `is_admin` flag; a member is a row in the `member` table; everyone else is a |
docs/features/may.md added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | --- | |
| 2 | topic: Agents: MCP, git, or the terminal | |
| 3 | row: Ask what you may do | |
| 4 | --- | |
| 5 | # Ask what you may do | |
| 6 | ||
| 7 | A client asks the forge what it may do instead of reading a role. One function, `may(principal, action, resource)` | |
| 8 | (`src/core/may.ts`), answers for every door: yes, or no with the forge's own reason and the reason in words. | |
| 9 | ||
| 10 | - **`not_found`**: what you may not read does not exist for you, signed in or not. | |
| 11 | - **`unauthorized`**: sign in to do it. | |
| 12 | - **`forbidden`**: you are known, and it is not yours to do (or your token's scope is too low: `ro` reads, `rw` changes things). | |
| 13 | ||
| 14 | Actions are named in one registry (`ACTIONS`), each with one sentence: `repo.read`, `repo.write`, `repo.admin` (over a | |
| 15 | repository), `forge.read`, `forge.comment`, `forge.contribute`, `forge.make_it_yours`, `forge.run_crew`, | |
| 16 | `forge.administer`, and `account.manage` (the account itself, never a token). | |
| 17 | ||
| 18 | **API.** `GET /api/v1/user` carries `can`: the forge-wide actions you may take. | |
| 19 | ||
| 20 | ||
| 21 | curl -H "authorization: Bearer $TOKEN" "$FORGE/api/v1/may?action=repo.write&resource=alice/notes" | |
| 22 | { "action": "repo.write", "says": "Change a repository: push, merge, label, close", "resource": "alice/notes", | |
| 23 | "may": false, "why": "forbidden", "reason": "Your account may not do this." } | |
| 24 | ||
| 25 | ||
| 26 | A forge-wide action takes no `resource`. The call needs no account: anonymous gets anonymous's answers. A repository | |
| 27 | that is not there and one you may not read answer alike. | |
| 28 | ||
| 29 | **MCP.** `whoami_can` lists `actions`, the same names; `repo` adds read, write and admin there. | |
| 30 | ||
| 31 | **Terminal.** Open "What I can do": the last line is `You may:` and the same list. |
src/actions/access.ts +8 −6
| @@ -9,7 +9,9 @@ | ||
| 9 | 9 | |
| 10 | 10 | import type { App } from "../app.ts"; |
| 11 | 11 | import { accessAllows, orgAccess } from "../core/orgs.ts"; |
| 12 | import { canAdmin, canRead, canWrite, type Repo } from "../core/repos.ts"; | |
| 12 | import { holds } from "../core/may.ts"; | |
| 13 | import { principalOfUser } from "../core/principal.ts"; | |
| 14 | import type { Repo } from "../core/repos.ts"; | |
| 13 | 15 | import type { User } from "../core/users.ts"; |
| 14 | 16 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 15 | 17 | |
| @@ -28,7 +30,7 @@ export function requireReader( | ||
| 28 | 30 | actor: User | undefined, |
| 29 | 31 | repo: Repo, |
| 30 | 32 | ): Result<Repo, "not_found"> { |
| 31 | return canRead(app.db, repo, actor) ? ok(repo) : err("not_found"); | |
| 33 | return holds(app.db, principalOfUser(actor), "repo.read", { repo }) ? ok(repo) : err("not_found"); | |
| 32 | 34 | } |
| 33 | 35 | |
| 34 | 36 | /** A signed-in actor who may see the repo — the floor for opening issues, |
| @@ -38,7 +40,7 @@ export function requireParticipant( | ||
| 38 | 40 | actor: User | undefined, |
| 39 | 41 | repo: Repo, |
| 40 | 42 | ): Result<User, "not_found" | "unauthorized"> { |
| 41 | if (!canRead(app.db, repo, actor)) return err("not_found"); | |
| 43 | if (!holds(app.db, principalOfUser(actor), "repo.read", { repo })) return err("not_found"); | |
| 42 | 44 | return requireUser(actor); |
| 43 | 45 | } |
| 44 | 46 | |
| @@ -47,9 +49,9 @@ export function requireWriter( | ||
| 47 | 49 | actor: User | undefined, |
| 48 | 50 | repo: Repo, |
| 49 | 51 | ): Result<User, AccessError> { |
| 50 | if (!canRead(app.db, repo, actor)) return err("not_found"); | |
| 52 | if (!holds(app.db, principalOfUser(actor), "repo.read", { repo })) return err("not_found"); | |
| 51 | 53 | if (!actor) return err("unauthorized"); |
| 52 | return canWrite(app.db, repo, actor) ? ok(actor) : err("forbidden"); | |
| 54 | return holds(app.db, principalOfUser(actor), "repo.write", { repo }) ? ok(actor) : err("forbidden"); | |
| 53 | 55 | } |
| 54 | 56 | |
| 55 | 57 | export function requireRepoAdmin( |
| @@ -57,7 +59,7 @@ export function requireRepoAdmin( | ||
| 57 | 59 | actor: User | undefined, |
| 58 | 60 | repo: Repo, |
| 59 | 61 | ): Result<User, "not_found"> { |
| 60 | return actor && canAdmin(app.db, repo, actor) ? ok(actor) : err("not_found"); | |
| 62 | return actor && holds(app.db, principalOfUser(actor), "repo.admin", { repo }) ? ok(actor) : err("not_found"); | |
| 61 | 63 | } |
| 62 | 64 | |
| 63 | 65 | /** An admin of `org` (a user row of kind "org"). */ |
src/actions/roles.ts +4 −2
| @@ -7,14 +7,16 @@ | ||
| 7 | 7 | |
| 8 | 8 | import type { App } from "../app.ts"; |
| 9 | 9 | import { setModelGrant, validGrant } from "../core/model_grant.ts"; |
| 10 | import { lacks, roleOf, setMember, type Ability } from "../core/roles.ts"; | |
| 10 | import { may } from "../core/may.ts"; | |
| 11 | import { principalOfUser } from "../core/principal.ts"; | |
| 12 | import { roleOf, setMember, type Ability } from "../core/roles.ts"; | |
| 11 | 13 | import { getUserByName, type User } from "../core/users.ts"; |
| 12 | 14 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 13 | 15 | import { requireUser } from "./access.ts"; |
| 14 | 16 | |
| 15 | 17 | /** `user` unless the table withholds `ability` from their role: then `not_member`. */ |
| 16 | 18 | export function requireAbility(app: App, user: User, ability: Ability): Result<User, "not_member"> { |
| 17 | return lacks(app.db, user, ability) ? err("not_member") : ok(user); | |
| 19 | return may(app.db, principalOfUser(user), `forge.${ability}`).ok ? ok(user) : err("not_member"); | |
| 18 | 20 | } |
| 19 | 21 | |
| 20 | 22 | export type RoleError = "not_found" | "not_allowed" | "invalid_amount"; |
src/contract/openapi/routes/getApiV1May.ts added +23
| @@ -0,0 +1,23 @@ | ||
| 1 | import { bool, obj, str, words } from "../schema_kit.ts"; | |
| 2 | import type { Route } from "../shared.ts"; | |
| 3 | ||
| 4 | export const route: Route = { | |
| 5 | method: "get", | |
| 6 | path: "/api/v1/may", | |
| 7 | summary: "Ask whether you may take an action, with the reason in words", | |
| 8 | detail: | |
| 9 | "Ask whether the caller may take `action` (a name from the `can` list of GET /api/v1/user, or one over a repository: repo.read, repo.write, repo.admin), over `resource` (owner/name, for an action over a repository; none for one over the whole forge). Answers { action, says, resource?, may, why?, reason? }: `may` is yes or no, and a no carries `why` (not_found: it does not exist for you; unauthorized: sign in; forbidden) and `reason` in words. A repository that is not there and one you may not read answer alike. Never cached.", | |
| 10 | auth: false, | |
| 11 | role: "anonymous", | |
| 12 | query: { action: "string", resource: "string" }, | |
| 13 | response: obj( | |
| 14 | { action: str, says: str, resource: str, may: bool, why: words("not_found", "unauthorized", "forbidden"), reason: str }, | |
| 15 | ["resource", "why", "reason"], | |
| 16 | ), | |
| 17 | errorStatus: { 422: "`unknown_action` or `invalid`: the action or the resource is not one the registry takes" }, | |
| 18 | refusals: { | |
| 19 | invalid_token: "401, a bearer or basic credential was sent and matches no account or token: sign in again; send none to be anonymous", | |
| 20 | unknown_action: "422: action is not one of the registry's names", | |
| 21 | invalid: "422: resource is missing or malformed for an action over a repository, or sent for one over the whole forge", | |
| 22 | }, | |
| 23 | }; |
src/contract/openapi/routes/getApiV1User.ts +4 −1
| @@ -1,9 +1,12 @@ | ||
| 1 | import { bool, list, obj, str } from "../schema_kit.ts"; | |
| 1 | 2 | import type { Route } from "../shared.ts"; |
| 2 | 3 | |
| 3 | 4 | export const route: Route = { |
| 4 | 5 | method: "get", |
| 5 | 6 | path: "/api/v1/user", |
| 6 | summary: "Read your own profile: the public fields plus emailVerified", | |
| 7 | summary: "Read your own profile: the public fields, emailVerified and what you may do", | |
| 8 | detail: "The public fields, emailVerified, and `can`: the forge-wide actions this caller may take, by the names GET /api/v1/may takes (forge.read, forge.comment, forge.contribute, forge.make_it_yours, forge.run_crew, forge.administer, account.manage). A client asks `can` instead of reading a role; the forge enforces either way.", | |
| 9 | response: obj({ id: str, username: str, displayName: str, isAdmin: bool, commitEmail: str, emailVerified: bool, can: list(str) }), | |
| 7 | 10 | auth: true, |
| 8 | 11 | role: "member", |
| 9 | 12 | refuses: [401], |
src/contract/openapi/routes/index.ts +1
| @@ -141,6 +141,7 @@ export { route as getApiV1MailKeyScope } from "./getApiV1MailKeyScope.ts"; | ||
| 141 | 141 | export { route as getApiV1MaintenanceDuties } from "./getApiV1MaintenanceDuties.ts"; |
| 142 | 142 | export { route as getApiV1MaintenanceRuns } from "./getApiV1MaintenanceRuns.ts"; |
| 143 | 143 | export { route as getApiV1Map } from "./getApiV1Map.ts"; |
| 144 | export { route as getApiV1May } from "./getApiV1May.ts"; | |
| 144 | 145 | export { route as getApiV1MigrateJob } from "./getApiV1MigrateJob.ts"; |
| 145 | 146 | export { route as getApiV1MigrateJobStream } from "./getApiV1MigrateJobStream.ts"; |
| 146 | 147 | export { route as getApiV1Models } from "./getApiV1Models.ts"; |
src/contract/tags.ts +1
src/core/may.ts added +134
| @@ -0,0 +1,134 @@ | ||
| 1 | /** | |
| 2 | * `may(principal, action, resource)`: the one question access asks. The principal is who is asking | |
| 3 | * (`core/principal.ts`: `principalOf(auth)` for a request, `principalOfUser(user)` for a check made | |
| 4 | * on someone's behalf), the action is a name in | |
| 5 | * `ACTIONS`, each with one sentence a person can read, and the resource is the repository the | |
| 6 | * action is over, when it is over one. The answer is yes, or no with which of the forge's | |
| 7 | * existing answers applies: `not_found` (what you may not read does not exist for you), | |
| 8 | * `unauthorized` (sign in) or `forbidden`. | |
| 9 | * | |
| 10 | * `canRead`, `canWrite` and `canAdmin` (`core/repos.ts`), the wrappers in `actions/access.ts` and | |
| 11 | * `isAccountItself` (`http/context.ts`) all ask here. The rules themselves stay where their data | |
| 12 | * is (`readsRepo`, `writesRepo`, `adminsRepo`); this decides which applies, what a token's scope | |
| 13 | * adds (a token that is `ro` may read and nothing more) and how a refusal is worded. | |
| 14 | */ | |
| 15 | ||
| 16 | import type { Database } from "bun:sqlite"; | |
| 17 | import { ABILITIES, lacks, type Ability } from "./roles.ts"; | |
| 18 | import { adminsRepo, readsRepo, writesRepo, type Repo } from "./repos.ts"; | |
| 19 | import { userOf, type Principal } from "./principal.ts"; | |
| 20 | import { scopeAllows, type TokenScope } from "./tokens.ts"; | |
| 21 | import type { User } from "./users.ts"; | |
| 22 | ||
| 23 | /** What an action is over: a repository, or (nothing) the forge as a whole. */ | |
| 24 | export interface Resource { | |
| 25 | readonly repo: Repo; | |
| 26 | } | |
| 27 | ||
| 28 | interface ActionRow { | |
| 29 | /** One sentence a person can read. */ | |
| 30 | readonly says: string; | |
| 31 | /** What it is over: a repository, or the forge as a whole. */ | |
| 32 | readonly over: "repo" | "forge"; | |
| 33 | /** The scope a token must hold: reading needs `ro`, anything that changes something `rw`. */ | |
| 34 | readonly scope: TokenScope; | |
| 35 | } | |
| 36 | ||
| 37 | const forgeAction = (a: Ability): ActionRow => ({ says: ABILITIES[a], over: "forge", scope: a === "read" ? "ro" : "rw" }); | |
| 38 | ||
| 39 | /** | |
| 40 | * Every action `may` answers, by name. The forge-wide ones are the roles table's abilities (`CAN`). | |
| 41 | */ | |
| 42 | export const ACTIONS = { | |
| 43 | "repo.read": { says: "Read a repository: its code, issues and pulls", over: "repo", scope: "ro" }, | |
| 44 | "repo.write": { says: "Change a repository: push, merge, label, close", over: "repo", scope: "rw" }, | |
| 45 | "repo.admin": { says: "Administer a repository: its settings, webhooks, protection and deletion", over: "repo", scope: "rw" }, | |
| 46 | "forge.read": forgeAction("read"), | |
| 47 | "forge.comment": forgeAction("comment"), | |
| 48 | "forge.contribute": forgeAction("contribute"), | |
| 49 | "forge.make_it_yours": forgeAction("make_it_yours"), | |
| 50 | "forge.run_crew": forgeAction("run_crew"), | |
| 51 | "forge.administer": forgeAction("administer"), | |
| 52 | "account.manage": { says: "Change your own account: password, profile and tokens, as yourself and not by a token", over: "forge", scope: "ro" }, | |
| 53 | } as const satisfies Record<string, ActionRow>; | |
| 54 | export type Action = keyof typeof ACTIONS; | |
| 55 | ||
| 56 | export const isAction = (v: unknown): v is Action => typeof v === "string" && Object.hasOwn(ACTIONS, v); | |
| 57 | ||
| 58 | export type Why = "not_found" | "unauthorized" | "forbidden"; | |
| 59 | ||
| 60 | export type Answer = { readonly ok: true } | { readonly ok: false; readonly why: Why; readonly says: string }; | |
| 61 | ||
| 62 | /** The reason in words, for a client that shows it. */ | |
| 63 | export const WHY_WORDS: Readonly<Record<Why, string>> = { | |
| 64 | not_found: "It does not exist, as far as you can see.", | |
| 65 | unauthorized: "Sign in to do this.", | |
| 66 | forbidden: "Your account may not do this.", | |
| 67 | }; | |
| 68 | ||
| 69 | const SCOPE_WORDS = "This token's scope is too low for it; make one with scope rw."; | |
| 70 | const BROWSER_WORDS = "Only the account itself may do this, signed in with a session or password; a token may not."; | |
| 71 | ||
| 72 | const yes: Answer = { ok: true }; | |
| 73 | const no = (why: Why, says: string = WHY_WORDS[why]): Answer => ({ ok: false, why, says }); | |
| 74 | ||
| 75 | /** The forge-wide actions that are the roles table's abilities, by action name. */ | |
| 76 | const ABILITY_OF: Readonly<Partial<Record<Action, Ability>>> = { | |
| 77 | "forge.read": "read", | |
| 78 | "forge.comment": "comment", | |
| 79 | "forge.contribute": "contribute", | |
| 80 | "forge.make_it_yours": "make_it_yours", | |
| 81 | "forge.run_crew": "run_crew", | |
| 82 | "forge.administer": "administer", | |
| 83 | }; | |
| 84 | ||
| 85 | /** Whether the rule of a repository action holds for this user, ignoring any token's scope. */ | |
| 86 | function repoRuleHolds(db: Database, action: Action, repo: Repo, user: User | undefined): boolean { | |
| 87 | if (action === "repo.read") return readsRepo(db, repo, user); | |
| 88 | if (action === "repo.write") return writesRepo(db, repo, user); | |
| 89 | return adminsRepo(db, repo, user); | |
| 90 | } | |
| 91 | ||
| 92 | function forgeRuleHolds(db: Database, action: Action, p: Principal): boolean { | |
| 93 | const ability = ABILITY_OF[action]; | |
| 94 | if (ability === "read") return true; | |
| 95 | const user = userOf(p); | |
| 96 | if (user === undefined) return false; | |
| 97 | if (ability === "administer") return user.isAdmin; | |
| 98 | if (ability !== undefined) return !lacks(db, user, ability); | |
| 99 | // `account.manage`: the account itself is asking, by a browser identity (a session cookie, or | |
| 100 | // the platform edge behind its headers) or the password, never by a token. | |
| 101 | return p.kind === "session" && p.via !== "none"; | |
| 102 | } | |
| 103 | ||
| 104 | /** | |
| 105 | * The rule and the scope, as a boolean: all a caller that only branches needs, and no reason's | |
| 106 | * reads. | |
| 107 | */ | |
| 108 | export function holds(db: Database, p: Principal, action: Action, resource?: Resource): boolean { | |
| 109 | const row: ActionRow = ACTIONS[action]; | |
| 110 | const held = row.over === "repo" ? repoRuleHolds(db, action, resource!.repo, userOf(p)) : forgeRuleHolds(db, action, p); | |
| 111 | // Only a token carries a scope; the account itself acts with all of its own authority. | |
| 112 | return held && (!("scope" in p) || scopeAllows(p.scope, row.scope)); | |
| 113 | } | |
| 114 | ||
| 115 | export function may(db: Database, p: Principal, action: Action, resource?: Resource): Answer { | |
| 116 | const row: ActionRow = ACTIONS[action]; | |
| 117 | const user = userOf(p); | |
| 118 | if (holds(db, p, action, resource)) return yes; | |
| 119 | if (action === "account.manage") return no(user === undefined ? "unauthorized" : "forbidden", BROWSER_WORDS); | |
| 120 | // What you may not read does not exist for you, signed in or not. | |
| 121 | if (row.over === "repo" && (action === "repo.read" || !readsRepo(db, resource!.repo, user))) return no("not_found"); | |
| 122 | if (user === undefined) return no("unauthorized"); | |
| 123 | // Only here is it asked whether the rule held and the token's scope alone said no. | |
| 124 | const held = row.over === "repo" ? repoRuleHolds(db, action, resource!.repo, user) : forgeRuleHolds(db, action, p); | |
| 125 | return no("forbidden", held ? SCOPE_WORDS : undefined); | |
| 126 | } | |
| 127 | ||
| 128 | /** | |
| 129 | * The forge-wide actions this principal may take, by name: what a client asks instead of reading a | |
| 130 | * role. | |
| 131 | */ | |
| 132 | export function capabilities(db: Database, p: Principal): Action[] { | |
| 133 | return (Object.keys(ACTIONS) as Action[]).filter((a) => ACTIONS[a].over === "forge" && may(db, p, a).ok); | |
| 134 | } |
src/core/principal.ts +16 −4
| @@ -3,8 +3,8 @@ | ||
| 3 | 3 | * of optional fields; this names what the bag means. Anonymous is a value, not |
| 4 | 4 | * `undefined`. A principal has a `kind` (how it arrives: no credential, the |
| 5 | 5 | * session itself, or one of the token kinds) and, when someone is behind it, a |
| 6 | * `subject` (what is asking: a person, an agent or an app). Additive: nothing decides on it yet, | |
| 7 | * so no route's answer changes (docs/ROLES.md, "The words"). | |
| 6 | * `subject` (what is asking: a person, an agent or an app). `may` (`core/may.ts`) asks every | |
| 7 | * question with one (docs/ROLES.md, "The words"). | |
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | 10 | import type { Auth } from "../http/context.ts"; |
| @@ -40,6 +40,10 @@ export interface SessionPrincipal { | ||
| 40 | 40 | |
| 41 | 41 | interface TokenBase { |
| 42 | 42 | readonly subject: Subject; |
| 43 | /** | |
| 44 | * The scope the token was stored with; a narrower kind still never does more than this allows. | |
| 45 | */ | |
| 46 | readonly scope: TokenScope; | |
| 43 | 47 | readonly tokenId: string | undefined; |
| 44 | 48 | readonly tokenName: string | undefined; |
| 45 | 49 | } |
| @@ -77,13 +81,13 @@ export function principalOf(auth: Auth): Principal { | ||
| 77 | 81 | } |
| 78 | 82 | const subject = subjectOf(user, auth.appId); |
| 79 | 83 | if (auth.via === "token") { |
| 80 | const base: TokenBase = { subject, tokenId: auth.tokenId, tokenName: auth.tokenName }; | |
| 84 | const scope: TokenScope = auth.scope ?? "ro"; | |
| 85 | const base: TokenBase = { subject, scope, tokenId: auth.tokenId, tokenName: auth.tokenName }; | |
| 81 | 86 | if (auth.proposal) return { ...base, kind: "proposal_token", proposal: auth.proposal }; |
| 82 | 87 | if (auth.run) return { ...base, kind: "run_token", run: auth.run }; |
| 83 | 88 | if (auth.contribute) return { ...base, kind: "contribute_token", contribute: auth.contribute }; |
| 84 | 89 | if (auth.appId !== undefined) return { ...base, kind: "read_grant_token", appId: auth.appId }; |
| 85 | 90 | if (auth.through !== undefined) return { ...base, kind: "via_token", through: auth.through }; |
| 86 | const scope: TokenScope = auth.scope ?? "ro"; | |
| 87 | 91 | return { ...base, kind: `${scope}_token` }; |
| 88 | 92 | } |
| 89 | 93 | return { |
| @@ -94,6 +98,14 @@ export function principalOf(auth: Auth): Principal { | ||
| 94 | 98 | }; |
| 95 | 99 | } |
| 96 | 100 | |
| 101 | /** | |
| 102 | * The principal of an account the code asks about with no credential in hand: a check made on | |
| 103 | * someone's behalf, or a terminal screen (`none`). Nobody is anonymous. | |
| 104 | */ | |
| 105 | export function principalOfUser(user: User | undefined, via: SessionPrincipal["via"] = "none"): Principal { | |
| 106 | return principalOf({ user, scope: undefined, via }); | |
| 107 | } | |
| 108 | ||
| 97 | 109 | /** The account behind a principal, when there is one: none for anonymous. */ |
| 98 | 110 | export function userOf(principal: Principal): User | undefined { |
| 99 | 111 | if (principal.kind === "anonymous") return undefined; |
src/core/repos.ts +24 −5
| @@ -5,6 +5,8 @@ | ||
| 5 | 5 | * repo. Deletion inverts the order — row first, directory second. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { holds } from "./may.ts"; | |
| 9 | import { principalOfUser } from "./principal.ts"; | |
| 8 | 10 | import { inheritQuarantine, quarantine } from "./quarantine.ts"; |
| 9 | 11 | import { forgetAppFilters } from "./ask_filters.ts"; |
| 10 | 12 | import { isPacksMirror } from "../packs/owner.ts"; |
| @@ -1451,7 +1453,13 @@ function appMayRead(db: Database, repo: Repo, appId: string): boolean { | ||
| 1451 | 1453 | return ro === null || hasGrant(db, repo.id, "app", appId); |
| 1452 | 1454 | } |
| 1453 | 1455 | |
| 1454 | export function canRead( | |
| 1456 | /** Whether `user` (or nobody) may read the repository: `may(…, "repo.read", …)` (`core/may.ts`). */ | |
| 1457 | export function canRead(db: Database, repo: Repo, user: User | undefined): boolean { | |
| 1458 | return holds(db, principalOfUser(user), "repo.read", { repo }); | |
| 1459 | } | |
| 1460 | ||
| 1461 | /** The read rule `may` applies, before any token's scope. */ | |
| 1462 | export function readsRepo( | |
| 1455 | 1463 | db: Database, |
| 1456 | 1464 | repo: Repo, |
| 1457 | 1465 | user: User | undefined, |
| @@ -1477,7 +1485,7 @@ function readsInStanding(db: Database, repo: Repo, user: User | undefined): bool | ||
| 1477 | 1485 | const base = getRepoById(db, repo.sealedFor); |
| 1478 | 1486 | return ( |
| 1479 | 1487 | base !== undefined && |
| 1480 | (canWrite(db, base, user) || onCrew(db, base, user)) | |
| 1488 | (writesRepo(db, base, user) || onCrew(db, base, user)) | |
| 1481 | 1489 | ); |
| 1482 | 1490 | } |
| 1483 | 1491 | return accessAllows(orgAccessFor(db, repo, user), "read"); |
| @@ -1509,7 +1517,13 @@ export function canReadMany(db: Database, repos: readonly Repo[], user: User | u | ||
| 1509 | 1517 | return out; |
| 1510 | 1518 | } |
| 1511 | 1519 | |
| 1512 | export function canWrite( | |
| 1520 | /** Whether `user` may write the repository: `may(…, "repo.write", …)` (`core/may.ts`). */ | |
| 1521 | export function canWrite(db: Database, repo: Repo, user: User | undefined): boolean { | |
| 1522 | return holds(db, principalOfUser(user), "repo.write", { repo }); | |
| 1523 | } | |
| 1524 | ||
| 1525 | /** The write rule `may` applies, before any token's scope. */ | |
| 1526 | export function writesRepo( | |
| 1513 | 1527 | db: Database, |
| 1514 | 1528 | repo: Repo, |
| 1515 | 1529 | user: User | undefined, |
| @@ -1536,7 +1550,7 @@ export function canEnterApp( | ||
| 1536 | 1550 | { named = true }: { named?: boolean } = {}, |
| 1537 | 1551 | ): boolean { |
| 1538 | 1552 | if (app.access === "public") return true; |
| 1539 | if (canWrite(db, repo, user) || onCrew(db, repo, user)) return true; | |
| 1553 | if (writesRepo(db, repo, user) || onCrew(db, repo, user)) return true; | |
| 1540 | 1554 | // A contributor (`core/invites.ts`) enters the app and its previews, never its terminal. |
| 1541 | 1555 | if (named && contributes(db, repo, user)) return true; |
| 1542 | 1556 | return ( |
| @@ -1691,7 +1705,12 @@ export function writableRepoIds( | ||
| 1691 | 1705 | } |
| 1692 | 1706 | |
| 1693 | 1707 | /** Admin over a repo (settings, delete, webhooks, protection). */ |
| 1694 | export function canAdmin( | |
| 1708 | export function canAdmin(db: Database, repo: Repo, user: User | undefined): boolean { | |
| 1709 | return holds(db, principalOfUser(user), "repo.admin", { repo }); | |
| 1710 | } | |
| 1711 | ||
| 1712 | /** The admin rule `may` applies, before any token's scope. */ | |
| 1713 | export function adminsRepo( | |
| 1695 | 1714 | db: Database, |
| 1696 | 1715 | repo: Repo, |
| 1697 | 1716 | user: User | undefined, |
src/generated/marks.ts +164 −162
| @@ -52,168 +52,169 @@ import k47 from "../http/marks/api-v1-keeper.json"; | ||
| 52 | 52 | import k48 from "../http/marks/api-v1-mail-key.json"; |
| 53 | 53 | import k49 from "../http/marks/api-v1-maintenance.json"; |
| 54 | 54 | import k50 from "../http/marks/api-v1-map.json"; |
| 55 | import k51 from "../http/marks/api-v1-migrate.json"; | |
| 56 | import k52 from "../http/marks/api-v1-models.json"; | |
| 57 | import k53 from "../http/marks/api-v1-offers.json"; | |
| 58 | import k54 from "../http/marks/api-v1-openapi.json.json"; | |
| 59 | import k55 from "../http/marks/api-v1-orgs.json"; | |
| 60 | import k56 from "../http/marks/api-v1-packs.json"; | |
| 61 | import k57 from "../http/marks/api-v1-passport.json"; | |
| 62 | import k58 from "../http/marks/api-v1-places.json"; | |
| 63 | import k59 from "../http/marks/api-v1-plans.json"; | |
| 64 | import k60 from "../http/marks/api-v1-proof.json"; | |
| 65 | import k61 from "../http/marks/api-v1-reach.json"; | |
| 66 | import k62 from "../http/marks/api-v1-release.json"; | |
| 67 | import k63 from "../http/marks/api-v1-releases.json"; | |
| 68 | import k64 from "../http/marks/api-v1-repos.json"; | |
| 69 | import k65 from "../http/marks/api-v1-returns.json"; | |
| 70 | import k66 from "../http/marks/api-v1-runner.json"; | |
| 71 | import k67 from "../http/marks/api-v1-search.json"; | |
| 72 | import k68 from "../http/marks/api-v1-secrets.json"; | |
| 73 | import k69 from "../http/marks/api-v1-sessions.json"; | |
| 74 | import k70 from "../http/marks/api-v1-share.json"; | |
| 75 | import k71 from "../http/marks/api-v1-slash.json"; | |
| 76 | import k72 from "../http/marks/api-v1-start.json"; | |
| 77 | import k73 from "../http/marks/api-v1-status.json"; | |
| 78 | import k74 from "../http/marks/api-v1-telemetry.json"; | |
| 79 | import k75 from "../http/marks/api-v1-templates.json"; | |
| 80 | import k76 from "../http/marks/api-v1-thoughts.json"; | |
| 81 | import k77 from "../http/marks/api-v1-timers.json"; | |
| 82 | import k78 from "../http/marks/api-v1-tokens.json"; | |
| 83 | import k79 from "../http/marks/api-v1-usage.json"; | |
| 84 | import k80 from "../http/marks/api-v1-user.json"; | |
| 85 | import k81 from "../http/marks/api-v1-users.json"; | |
| 86 | import k82 from "../http/marks/api-v1-version.json"; | |
| 87 | import k83 from "../http/marks/api-v1.json"; | |
| 88 | import k84 from "../http/marks/api.json"; | |
| 89 | import k85 from "../http/marks/apple-touch-icon-precomposed.png.json"; | |
| 90 | import k86 from "../http/marks/apple-touch-icon.png.json"; | |
| 91 | import k87 from "../http/marks/apps.json"; | |
| 92 | import k88 from "../http/marks/archive.json"; | |
| 93 | import k89 from "../http/marks/asked.json"; | |
| 94 | import k90 from "../http/marks/asks.json"; | |
| 95 | import k91 from "../http/marks/assets.json"; | |
| 96 | import k92 from "../http/marks/audit.csv.json"; | |
| 97 | import k93 from "../http/marks/audit.json"; | |
| 98 | import k94 from "../http/marks/big.json"; | |
| 99 | import k95 from "../http/marks/board.json"; | |
| 100 | import k96 from "../http/marks/boards.json"; | |
| 101 | import k97 from "../http/marks/bring.json"; | |
| 102 | import k98 from "../http/marks/broker.json"; | |
| 103 | import k99 from "../http/marks/changelog.atom.json"; | |
| 104 | import k100 from "../http/marks/changelog.json"; | |
| 105 | import k101 from "../http/marks/claim.json"; | |
| 106 | import k102 from "../http/marks/client-clouds.json"; | |
| 107 | import k103 from "../http/marks/cloud.json"; | |
| 108 | import k104 from "../http/marks/cockpit.json"; | |
| 109 | import k105 from "../http/marks/contract.json"; | |
| 110 | import k106 from "../http/marks/contribute.json"; | |
| 111 | import k107 from "../http/marks/csp-report.json"; | |
| 112 | import k108 from "../http/marks/dash.json"; | |
| 113 | import k109 from "../http/marks/data.json"; | |
| 114 | import k110 from "../http/marks/dataset.json"; | |
| 115 | import k111 from "../http/marks/deploy-to.json"; | |
| 116 | import k112 from "../http/marks/design.json"; | |
| 117 | import k113 from "../http/marks/desk.json"; | |
| 118 | import k114 from "../http/marks/displays.json"; | |
| 119 | import k115 from "../http/marks/docs.json"; | |
| 120 | import k116 from "../http/marks/edge.json"; | |
| 121 | import k117 from "../http/marks/edition.json"; | |
| 122 | import k118 from "../http/marks/events.json"; | |
| 123 | import k119 from "../http/marks/explore.atom.json"; | |
| 124 | import k120 from "../http/marks/explore.json"; | |
| 125 | import k121 from "../http/marks/explore.json.json"; | |
| 126 | import k122 from "../http/marks/family.json"; | |
| 127 | import k123 from "../http/marks/favicon.ico.json"; | |
| 128 | import k124 from "../http/marks/feed.json"; | |
| 129 | import k125 from "../http/marks/feed.json.json"; | |
| 130 | import k126 from "../http/marks/first-admin.json"; | |
| 131 | import k127 from "../http/marks/fleet.json"; | |
| 132 | import k128 from "../http/marks/flow.json"; | |
| 133 | import k129 from "../http/marks/forge.json"; | |
| 134 | import k130 from "../http/marks/forges.json"; | |
| 135 | import k131 from "../http/marks/forks.json"; | |
| 136 | import k132 from "../http/marks/front.json"; | |
| 137 | import k133 from "../http/marks/funnel.json"; | |
| 138 | import k134 from "../http/marks/games.json"; | |
| 139 | import k135 from "../http/marks/go.json"; | |
| 140 | import k136 from "../http/marks/health.json"; | |
| 141 | import k137 from "../http/marks/home.json"; | |
| 142 | import k138 from "../http/marks/hooks.json"; | |
| 143 | import k139 from "../http/marks/icons.json"; | |
| 144 | import k140 from "../http/marks/infra.json"; | |
| 145 | import k141 from "../http/marks/join.json"; | |
| 146 | import k142 from "../http/marks/live.json"; | |
| 147 | import k143 from "../http/marks/llms-full.txt.json"; | |
| 148 | import k144 from "../http/marks/llms.txt.json"; | |
| 149 | import k145 from "../http/marks/login.json"; | |
| 150 | import k146 from "../http/marks/logout.json"; | |
| 151 | import k147 from "../http/marks/maintenance-json.json"; | |
| 152 | import k148 from "../http/marks/maintenance.json"; | |
| 153 | import k149 from "../http/marks/manifest.webmanifest.json"; | |
| 154 | import k150 from "../http/marks/map.json"; | |
| 155 | import k151 from "../http/marks/mcp.json"; | |
| 156 | import k152 from "../http/marks/measure.json"; | |
| 157 | import k153 from "../http/marks/metrics.json"; | |
| 158 | import k154 from "../http/marks/migrate.json"; | |
| 159 | import k155 from "../http/marks/new.json"; | |
| 160 | import k156 from "../http/marks/next.json"; | |
| 161 | import k157 from "../http/marks/notes.json"; | |
| 162 | import k158 from "../http/marks/now.json"; | |
| 163 | import k159 from "../http/marks/oauth.json"; | |
| 164 | import k160 from "../http/marks/oembed.json"; | |
| 165 | import k161 from "../http/marks/offers.json"; | |
| 166 | import k162 from "../http/marks/offline.json"; | |
| 167 | import k163 from "../http/marks/og.json"; | |
| 168 | import k164 from "../http/marks/openapi.json.json"; | |
| 169 | import k165 from "../http/marks/opensearch.xml.json"; | |
| 170 | import k166 from "../http/marks/organizations.json"; | |
| 171 | import k167 from "../http/marks/origins.json"; | |
| 172 | import k168 from "../http/marks/owner.atom.json"; | |
| 173 | import k169 from "../http/marks/owner.json"; | |
| 174 | import k170 from "../http/marks/packs.json"; | |
| 175 | import k171 from "../http/marks/peek.json"; | |
| 176 | import k172 from "../http/marks/pinned.json"; | |
| 177 | import k173 from "../http/marks/pipeline.json"; | |
| 178 | import k174 from "../http/marks/plugins.json"; | |
| 179 | import k175 from "../http/marks/pricing.json"; | |
| 180 | import k176 from "../http/marks/privacy.json"; | |
| 181 | import k177 from "../http/marks/r.json"; | |
| 182 | import k178 from "../http/marks/recover.json"; | |
| 183 | import k179 from "../http/marks/releases.json"; | |
| 184 | import k180 from "../http/marks/releases.json.json"; | |
| 185 | import k181 from "../http/marks/repos.json"; | |
| 186 | import k182 from "../http/marks/resilience.json"; | |
| 187 | import k183 from "../http/marks/review.json"; | |
| 188 | import k184 from "../http/marks/robots.txt.json"; | |
| 189 | import k185 from "../http/marks/root.json"; | |
| 190 | import k186 from "../http/marks/runs.json"; | |
| 191 | import k187 from "../http/marks/script-error.json"; | |
| 192 | import k188 from "../http/marks/search.json"; | |
| 193 | import k189 from "../http/marks/security.json"; | |
| 194 | import k190 from "../http/marks/settings.json"; | |
| 195 | import k191 from "../http/marks/sign-in.json"; | |
| 196 | import k192 from "../http/marks/signin.json"; | |
| 197 | import k193 from "../http/marks/signup.json"; | |
| 198 | import k194 from "../http/marks/sitemap.xml.json"; | |
| 199 | import k195 from "../http/marks/status.json"; | |
| 200 | import k196 from "../http/marks/support.json"; | |
| 201 | import k197 from "../http/marks/sw.js.json"; | |
| 202 | import k198 from "../http/marks/system.json"; | |
| 203 | import k199 from "../http/marks/tab.json"; | |
| 204 | import k200 from "../http/marks/tabforge.json"; | |
| 205 | import k201 from "../http/marks/talk.json"; | |
| 206 | import k202 from "../http/marks/tell.json"; | |
| 207 | import k203 from "../http/marks/templates.json"; | |
| 208 | import k204 from "../http/marks/templates.json.json"; | |
| 209 | import k205 from "../http/marks/terms.json"; | |
| 210 | import k206 from "../http/marks/theme.json"; | |
| 211 | import k207 from "../http/marks/toolbar-lab.js.json"; | |
| 212 | import k208 from "../http/marks/toolbar-lab.json"; | |
| 213 | import k209 from "../http/marks/traces.json"; | |
| 214 | import k210 from "../http/marks/verify.json"; | |
| 215 | import k211 from "../http/marks/welcome.json"; | |
| 216 | import k212 from "../http/marks/well-known.json"; | |
| 55 | import k51 from "../http/marks/api-v1-may.json"; | |
| 56 | import k52 from "../http/marks/api-v1-migrate.json"; | |
| 57 | import k53 from "../http/marks/api-v1-models.json"; | |
| 58 | import k54 from "../http/marks/api-v1-offers.json"; | |
| 59 | import k55 from "../http/marks/api-v1-openapi.json.json"; | |
| 60 | import k56 from "../http/marks/api-v1-orgs.json"; | |
| 61 | import k57 from "../http/marks/api-v1-packs.json"; | |
| 62 | import k58 from "../http/marks/api-v1-passport.json"; | |
| 63 | import k59 from "../http/marks/api-v1-places.json"; | |
| 64 | import k60 from "../http/marks/api-v1-plans.json"; | |
| 65 | import k61 from "../http/marks/api-v1-proof.json"; | |
| 66 | import k62 from "../http/marks/api-v1-reach.json"; | |
| 67 | import k63 from "../http/marks/api-v1-release.json"; | |
| 68 | import k64 from "../http/marks/api-v1-releases.json"; | |
| 69 | import k65 from "../http/marks/api-v1-repos.json"; | |
| 70 | import k66 from "../http/marks/api-v1-returns.json"; | |
| 71 | import k67 from "../http/marks/api-v1-runner.json"; | |
| 72 | import k68 from "../http/marks/api-v1-search.json"; | |
| 73 | import k69 from "../http/marks/api-v1-secrets.json"; | |
| 74 | import k70 from "../http/marks/api-v1-sessions.json"; | |
| 75 | import k71 from "../http/marks/api-v1-share.json"; | |
| 76 | import k72 from "../http/marks/api-v1-slash.json"; | |
| 77 | import k73 from "../http/marks/api-v1-start.json"; | |
| 78 | import k74 from "../http/marks/api-v1-status.json"; | |
| 79 | import k75 from "../http/marks/api-v1-telemetry.json"; | |
| 80 | import k76 from "../http/marks/api-v1-templates.json"; | |
| 81 | import k77 from "../http/marks/api-v1-thoughts.json"; | |
| 82 | import k78 from "../http/marks/api-v1-timers.json"; | |
| 83 | import k79 from "../http/marks/api-v1-tokens.json"; | |
| 84 | import k80 from "../http/marks/api-v1-usage.json"; | |
| 85 | import k81 from "../http/marks/api-v1-user.json"; | |
| 86 | import k82 from "../http/marks/api-v1-users.json"; | |
| 87 | import k83 from "../http/marks/api-v1-version.json"; | |
| 88 | import k84 from "../http/marks/api-v1.json"; | |
| 89 | import k85 from "../http/marks/api.json"; | |
| 90 | import k86 from "../http/marks/apple-touch-icon-precomposed.png.json"; | |
| 91 | import k87 from "../http/marks/apple-touch-icon.png.json"; | |
| 92 | import k88 from "../http/marks/apps.json"; | |
| 93 | import k89 from "../http/marks/archive.json"; | |
| 94 | import k90 from "../http/marks/asked.json"; | |
| 95 | import k91 from "../http/marks/asks.json"; | |
| 96 | import k92 from "../http/marks/assets.json"; | |
| 97 | import k93 from "../http/marks/audit.csv.json"; | |
| 98 | import k94 from "../http/marks/audit.json"; | |
| 99 | import k95 from "../http/marks/big.json"; | |
| 100 | import k96 from "../http/marks/board.json"; | |
| 101 | import k97 from "../http/marks/boards.json"; | |
| 102 | import k98 from "../http/marks/bring.json"; | |
| 103 | import k99 from "../http/marks/broker.json"; | |
| 104 | import k100 from "../http/marks/changelog.atom.json"; | |
| 105 | import k101 from "../http/marks/changelog.json"; | |
| 106 | import k102 from "../http/marks/claim.json"; | |
| 107 | import k103 from "../http/marks/client-clouds.json"; | |
| 108 | import k104 from "../http/marks/cloud.json"; | |
| 109 | import k105 from "../http/marks/cockpit.json"; | |
| 110 | import k106 from "../http/marks/contract.json"; | |
| 111 | import k107 from "../http/marks/contribute.json"; | |
| 112 | import k108 from "../http/marks/csp-report.json"; | |
| 113 | import k109 from "../http/marks/dash.json"; | |
| 114 | import k110 from "../http/marks/data.json"; | |
| 115 | import k111 from "../http/marks/dataset.json"; | |
| 116 | import k112 from "../http/marks/deploy-to.json"; | |
| 117 | import k113 from "../http/marks/design.json"; | |
| 118 | import k114 from "../http/marks/desk.json"; | |
| 119 | import k115 from "../http/marks/displays.json"; | |
| 120 | import k116 from "../http/marks/docs.json"; | |
| 121 | import k117 from "../http/marks/edge.json"; | |
| 122 | import k118 from "../http/marks/edition.json"; | |
| 123 | import k119 from "../http/marks/events.json"; | |
| 124 | import k120 from "../http/marks/explore.atom.json"; | |
| 125 | import k121 from "../http/marks/explore.json"; | |
| 126 | import k122 from "../http/marks/explore.json.json"; | |
| 127 | import k123 from "../http/marks/family.json"; | |
| 128 | import k124 from "../http/marks/favicon.ico.json"; | |
| 129 | import k125 from "../http/marks/feed.json"; | |
| 130 | import k126 from "../http/marks/feed.json.json"; | |
| 131 | import k127 from "../http/marks/first-admin.json"; | |
| 132 | import k128 from "../http/marks/fleet.json"; | |
| 133 | import k129 from "../http/marks/flow.json"; | |
| 134 | import k130 from "../http/marks/forge.json"; | |
| 135 | import k131 from "../http/marks/forges.json"; | |
| 136 | import k132 from "../http/marks/forks.json"; | |
| 137 | import k133 from "../http/marks/front.json"; | |
| 138 | import k134 from "../http/marks/funnel.json"; | |
| 139 | import k135 from "../http/marks/games.json"; | |
| 140 | import k136 from "../http/marks/go.json"; | |
| 141 | import k137 from "../http/marks/health.json"; | |
| 142 | import k138 from "../http/marks/home.json"; | |
| 143 | import k139 from "../http/marks/hooks.json"; | |
| 144 | import k140 from "../http/marks/icons.json"; | |
| 145 | import k141 from "../http/marks/infra.json"; | |
| 146 | import k142 from "../http/marks/join.json"; | |
| 147 | import k143 from "../http/marks/live.json"; | |
| 148 | import k144 from "../http/marks/llms-full.txt.json"; | |
| 149 | import k145 from "../http/marks/llms.txt.json"; | |
| 150 | import k146 from "../http/marks/login.json"; | |
| 151 | import k147 from "../http/marks/logout.json"; | |
| 152 | import k148 from "../http/marks/maintenance-json.json"; | |
| 153 | import k149 from "../http/marks/maintenance.json"; | |
| 154 | import k150 from "../http/marks/manifest.webmanifest.json"; | |
| 155 | import k151 from "../http/marks/map.json"; | |
| 156 | import k152 from "../http/marks/mcp.json"; | |
| 157 | import k153 from "../http/marks/measure.json"; | |
| 158 | import k154 from "../http/marks/metrics.json"; | |
| 159 | import k155 from "../http/marks/migrate.json"; | |
| 160 | import k156 from "../http/marks/new.json"; | |
| 161 | import k157 from "../http/marks/next.json"; | |
| 162 | import k158 from "../http/marks/notes.json"; | |
| 163 | import k159 from "../http/marks/now.json"; | |
| 164 | import k160 from "../http/marks/oauth.json"; | |
| 165 | import k161 from "../http/marks/oembed.json"; | |
| 166 | import k162 from "../http/marks/offers.json"; | |
| 167 | import k163 from "../http/marks/offline.json"; | |
| 168 | import k164 from "../http/marks/og.json"; | |
| 169 | import k165 from "../http/marks/openapi.json.json"; | |
| 170 | import k166 from "../http/marks/opensearch.xml.json"; | |
| 171 | import k167 from "../http/marks/organizations.json"; | |
| 172 | import k168 from "../http/marks/origins.json"; | |
| 173 | import k169 from "../http/marks/owner.atom.json"; | |
| 174 | import k170 from "../http/marks/owner.json"; | |
| 175 | import k171 from "../http/marks/packs.json"; | |
| 176 | import k172 from "../http/marks/peek.json"; | |
| 177 | import k173 from "../http/marks/pinned.json"; | |
| 178 | import k174 from "../http/marks/pipeline.json"; | |
| 179 | import k175 from "../http/marks/plugins.json"; | |
| 180 | import k176 from "../http/marks/pricing.json"; | |
| 181 | import k177 from "../http/marks/privacy.json"; | |
| 182 | import k178 from "../http/marks/r.json"; | |
| 183 | import k179 from "../http/marks/recover.json"; | |
| 184 | import k180 from "../http/marks/releases.json"; | |
| 185 | import k181 from "../http/marks/releases.json.json"; | |
| 186 | import k182 from "../http/marks/repos.json"; | |
| 187 | import k183 from "../http/marks/resilience.json"; | |
| 188 | import k184 from "../http/marks/review.json"; | |
| 189 | import k185 from "../http/marks/robots.txt.json"; | |
| 190 | import k186 from "../http/marks/root.json"; | |
| 191 | import k187 from "../http/marks/runs.json"; | |
| 192 | import k188 from "../http/marks/script-error.json"; | |
| 193 | import k189 from "../http/marks/search.json"; | |
| 194 | import k190 from "../http/marks/security.json"; | |
| 195 | import k191 from "../http/marks/settings.json"; | |
| 196 | import k192 from "../http/marks/sign-in.json"; | |
| 197 | import k193 from "../http/marks/signin.json"; | |
| 198 | import k194 from "../http/marks/signup.json"; | |
| 199 | import k195 from "../http/marks/sitemap.xml.json"; | |
| 200 | import k196 from "../http/marks/status.json"; | |
| 201 | import k197 from "../http/marks/support.json"; | |
| 202 | import k198 from "../http/marks/sw.js.json"; | |
| 203 | import k199 from "../http/marks/system.json"; | |
| 204 | import k200 from "../http/marks/tab.json"; | |
| 205 | import k201 from "../http/marks/tabforge.json"; | |
| 206 | import k202 from "../http/marks/talk.json"; | |
| 207 | import k203 from "../http/marks/tell.json"; | |
| 208 | import k204 from "../http/marks/templates.json"; | |
| 209 | import k205 from "../http/marks/templates.json.json"; | |
| 210 | import k206 from "../http/marks/terms.json"; | |
| 211 | import k207 from "../http/marks/theme.json"; | |
| 212 | import k208 from "../http/marks/toolbar-lab.js.json"; | |
| 213 | import k209 from "../http/marks/toolbar-lab.json"; | |
| 214 | import k210 from "../http/marks/traces.json"; | |
| 215 | import k211 from "../http/marks/verify.json"; | |
| 216 | import k212 from "../http/marks/welcome.json"; | |
| 217 | import k213 from "../http/marks/well-known.json"; | |
| 217 | 218 | |
| 218 | 219 | /** Each file of `http/marks/`, parsed, in name order. */ |
| 219 | 220 | export const MARK_FILES: readonly unknown[] = [ |
| @@ -430,4 +431,5 @@ export const MARK_FILES: readonly unknown[] = [ | ||
| 430 | 431 | k210, |
| 431 | 432 | k211, |
| 432 | 433 | k212, |
| 434 | k213, | |
| 433 | 435 | ]; |
src/http/api.ts +2
| @@ -397,6 +397,7 @@ import { repoSourceRoutes } from "./api/repo_source.ts"; | ||
| 397 | 397 | import { pullRoutes } from "./api/pulls.ts"; |
| 398 | 398 | import type { Router } from "./router.ts"; |
| 399 | 399 | import { clientAddress } from "./peer.ts"; |
| 400 | import { mayRoutes } from "./api/may.ts"; | |
| 400 | 401 | import { INVALID_TOKEN_HINT, INVALID_TOKEN_WORDS, manifestFor, registeredPageManifest } from "../actions/here.ts"; |
| 401 | 402 | import { ok } from "../kernel/result.ts"; |
| 402 | 403 | import { egressRowsFor, egressTotalsFor } from "../spawn/process_counters.ts"; |
| @@ -1283,6 +1284,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 1283 | 1284 | tokenRoutes(router); |
| 1284 | 1285 | |
| 1285 | 1286 | userRoutes(router); |
| 1287 | mayRoutes(router); | |
| 1286 | 1288 | pushDeviceRoutes(router); |
| 1287 | 1289 | appleTelemetryRoutes(router); |
| 1288 | 1290 | forgeOriginRoutes(router); |
src/http/api/may.ts added +54
| @@ -0,0 +1,54 @@ | ||
| 1 | /** | |
| 2 | * `GET /api/v1/may?action=…&resource=owner/name`: one cheap read of what this caller may do, so a | |
| 3 | * client asks instead of reading a role. The answer is `may` (`core/may.ts`): yes, or no with the | |
| 4 | * forge's own reason (`not_found`, `unauthorized`, `forbidden`) and the reason in words. A | |
| 5 | * repository that is not there and one the caller may not read answer alike. | |
| 6 | */ | |
| 7 | ||
| 8 | import { ACTIONS, isAction, may, WHY_WORDS, type Action } from "../../core/may.ts"; | |
| 9 | import { principalOf } from "../../core/principal.ts"; | |
| 10 | import { getRepo } from "../../core/repos.ts"; | |
| 11 | import { INVALID_TOKEN_HINT, INVALID_TOKEN_WORDS } from "../../actions/here.ts"; | |
| 12 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; | |
| 13 | import type { Handler } from "../context.ts"; | |
| 14 | import { apiError, json } from "../respond.ts"; | |
| 15 | import type { Router } from "../router.ts"; | |
| 16 | ||
| 17 | /** `owner/name`, each part a repository name's characters and no longer than one may be. */ | |
| 18 | const REPO_RESOURCE = /^([A-Za-z0-9._-]{1,100})\/([A-Za-z0-9._-]{1,100})$/; | |
| 19 | ||
| 20 | const names = (): string => (Object.keys(ACTIONS) as Action[]).join(", "); | |
| 21 | ||
| 22 | export function mayRoutes(router: Router<Handler>): void { | |
| 23 | router.add("GET", "/api/v1/may", (ctx) => { | |
| 24 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 25 | // A credential that matches nothing is not a signed-out visitor. | |
| 26 | if (ctx.auth.refused === true) return apiError("invalid_token", 401, INVALID_TOKEN_WORDS, INVALID_TOKEN_HINT); | |
| 27 | const action = ctx.url.searchParams.get("action") ?? ""; | |
| 28 | if (!isAction(action)) return apiError("unknown_action", 422, `action is one of: ${names()}`); | |
| 29 | const resource = ctx.url.searchParams.get("resource") ?? undefined; | |
| 30 | const row = ACTIONS[action]; | |
| 31 | let repo; | |
| 32 | if (row.over === "forge") { | |
| 33 | if (resource !== undefined) return apiError("invalid", 422, `${action} is over the whole forge: send no resource`); | |
| 34 | } else { | |
| 35 | const named = resource === undefined ? null : REPO_RESOURCE.exec(resource); | |
| 36 | if (named === null) return apiError("invalid", 422, `${action} is over a repository: resource is owner/name`); | |
| 37 | repo = getRepo(ctx.app.db, named[1]!, named[2]!); | |
| 38 | } | |
| 39 | const answer = row.over === "repo" && repo === undefined | |
| 40 | ? ({ ok: false, why: "not_found", says: WHY_WORDS.not_found } as const) | |
| 41 | : may(ctx.app.db, principalOf(ctx.auth), action, repo === undefined ? undefined : { repo }); | |
| 42 | return json( | |
| 43 | { | |
| 44 | action, | |
| 45 | says: row.says, | |
| 46 | ...(resource === undefined ? {} : { resource }), | |
| 47 | may: answer.ok, | |
| 48 | ...(answer.ok ? {} : { why: answer.why, reason: answer.says }), | |
| 49 | }, | |
| 50 | 200, | |
| 51 | { "cache-control": "no-store", vary: "cookie, authorization" }, | |
| 52 | ); | |
| 53 | }); | |
| 54 | } |
src/http/api/user.ts +3 −1
| @@ -14,6 +14,8 @@ import { addSshKey, CHANGE_PASSWORD_WORDS, changePassword, deleteSshKey, updateP | ||
| 14 | 14 | import { VERIFY_WORDS } from "../../actions/verify_words.ts"; |
| 15 | 15 | import { resendVerification } from "../../actions/verify.ts"; |
| 16 | 16 | import { NOTIFY_ERRORS, notifyHost, notifyUrlOf, setNotifyUrl } from "../../crew/notify.ts"; |
| 17 | import { capabilities } from "../../core/may.ts"; | |
| 18 | import { principalOf } from "../../core/principal.ts"; | |
| 17 | 19 | import { listAssignedTo } from "../../core/issues.ts"; |
| 18 | 20 | import { nextStepsFor } from "../../core/next-steps.ts"; |
| 19 | 21 | import { listKeys, publicKey } from "../../core/keys.ts"; |
| @@ -121,7 +123,7 @@ export function userRoutes(router: Router<Handler>): void { | ||
| 121 | 123 | const me = ctx.auth.user; |
| 122 | 124 | if (!me) return unauthorized(); |
| 123 | 125 | const verified = timePhase(ctx.request, "user", () => emailVerified(ctx.app.db, me.id)); |
| 124 | return timePhase(ctx.request, "render", () => json({ ...publicUser(me), emailVerified: verified })); | |
| 126 | return timePhase(ctx.request, "render", () => json({ ...publicUser(me), emailVerified: verified, can: capabilities(ctx.app.db, principalOf(ctx.auth)) })); | |
| 125 | 127 | }); |
| 126 | 128 | |
| 127 | 129 | // Another verification link for the signed-in account; rate limited. |
src/http/context.ts +5 −2
| @@ -3,7 +3,10 @@ | ||
| 3 | 3 | * route params, and authentication resolved once as plain data. |
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | import type { Database } from "bun:sqlite"; | |
| 6 | 7 | import type { ContributeScope } from "../core/contribute_token.ts"; |
| 8 | import { holds } from "../core/may.ts"; | |
| 9 | import { principalOf } from "../core/principal.ts"; | |
| 7 | 10 | import type { Proposal } from "../core/proposal_token.ts"; |
| 8 | 11 | import type { App } from "../app.ts"; |
| 9 | 12 | import type { RunScope } from "../core/run_token.ts"; |
| @@ -56,8 +59,8 @@ export interface Auth { | ||
| 56 | 59 | * API and the web forms cannot drift apart on who may mint. Browser |
| 57 | 60 | * identities still need a same-origin request; callers check that too. |
| 58 | 61 | */ |
| 59 | export function isAccountItself(auth: Auth): boolean { | |
| 60 | return auth.via === "session" || auth.via === "edge" || auth.via === "password"; | |
| 62 | export function isAccountItself(db: Database, auth: Auth): boolean { | |
| 63 | return holds(db, principalOf(auth), "account.manage"); | |
| 61 | 64 | } |
| 62 | 65 | |
| 63 | 66 | export interface Ctx { |
src/http/git_access.ts +6 −5
| @@ -8,9 +8,11 @@ import { takesOutside } from "../actions/contribute_token.ts"; | ||
| 8 | 8 | import { createRepo, repositoryLimitMessage, resolveOwner } from "../actions/repos.ts"; |
| 9 | 9 | import { CONTRIBUTE_PUSH_MAX_BYTES } from "../core/contribute_token.ts"; |
| 10 | 10 | import { holdFor } from "../core/fork_reach.ts"; |
| 11 | import { canRead, canWrite, getRepo } from "../core/repos.ts"; | |
| 11 | import { canRead, getRepo } from "../core/repos.ts"; | |
| 12 | 12 | import { NOT_A_MEMBER } from "../core/roles.ts"; |
| 13 | 13 | import { pushCap, storageChanged, storageRefusal, storageRefusedText, storageSentence } from "../core/storage.ts"; |
| 14 | import { may } from "../core/may.ts"; | |
| 15 | import { principalOf } from "../core/principal.ts"; | |
| 14 | 16 | import { scopeAllows } from "../core/tokens.ts"; |
| 15 | 17 | import { bundleUriFor, noteBundle } from "../git/bundle_uri.ts"; |
| 16 | 18 | import { heldPushConfig } from "../git/own_refs.ts"; |
| @@ -111,10 +113,9 @@ export async function withGitAccess( | ||
| 111 | 113 | // An outside agent's token may push its one repository; |
| 112 | 114 | // which refs is the hook's (`contribAgent`). |
| 113 | 115 | const outside = ctx.auth.contribute?.repoId === repo.id && takesOutside(ctx.app, repo); |
| 114 | if ( | |
| 115 | !(outside || canWrite(ctx.app.db, repo, ctx.auth.user)) || | |
| 116 | !scopeAllows(ctx.auth.scope ?? "ro", "rw") | |
| 117 | ) { | |
| 116 | // A push needs a credential that writes: one with no scope is a read-only one. | |
| 117 | const writes = scopeAllows(ctx.auth.scope ?? "ro", "rw"); | |
| 118 | if (!writes || !(outside || may(ctx.app.db, principalOf(ctx.auth), "repo.write", { repo }).ok)) { | |
| 118 | 119 | return notFound(); |
| 119 | 120 | } |
| 120 | 121 | } else { |
src/http/lazy_lists.ts +1
| @@ -1238,6 +1238,7 @@ export const API_ROUTES = [ | ||
| 1238 | 1238 | ["GET", "/api/v1/user/assigned"], |
| 1239 | 1239 | ["GET", "/api/v1/user/next-steps"], |
| 1240 | 1240 | ["DELETE", "/api/v1/user/pins/:owner/:name"], |
| 1241 | ["GET", "/api/v1/may"], | |
| 1241 | 1242 | ["GET", "/api/v1/user/devices"], |
| 1242 | 1243 | ["POST", "/api/v1/user/devices"], |
| 1243 | 1244 | ["DELETE", "/api/v1/user/devices/:id"], |
src/http/marks/api-v1-may.json added +4
src/http/mcp/tools/profile.ts +4 −2
| @@ -1,4 +1,6 @@ | ||
| 1 | 1 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 2 | import { capabilities } from "../../../core/may.ts"; | |
| 3 | import { principalOf } from "../../../core/principal.ts"; | |
| 2 | 4 | import { emailVerified } from "../../../core/verify.ts"; |
| 3 | 5 | import { GIFT_WORDS, giveGift, readGifts } from "../../../actions/gifts.ts"; |
| 4 | 6 | import { publicOrigin } from "../../../core/public_origin.ts"; |
| @@ -9,7 +11,7 @@ import { good, bad, type Tool } from "../shared.ts"; | ||
| 9 | 11 | |
| 10 | 12 | export const tool: Tool = { |
| 11 | 13 | name: "profile", |
| 12 | doc: "`{ displayName?, email?, commitEmail?, action? }`: your own profile (`publicUser` and `emailVerified`, never the address); with an argument it changes it by the rules of `PATCH /api/v1/user`, and needs admin scope: only a site admin can mint such a token, so most people sign in to `/mcp` with their password. `action: \"export\"` answers the document of `GET /api/v1/user/export` (a size summary and the link past 16,000 bytes, a bound this tool sets for itself: the MCP layer has none), for a person's account with an admin-scope token. `action: \"gift\"` (#11925), for a person on a paid plan, reads the gifts left and who took each; with `dryRun: false` and an admin-scope token it makes a one-use link to give a friend a forge, shown once", | |
| 14 | doc: "`{ displayName?, email?, commitEmail?, action? }`: your own profile (`publicUser`, `emailVerified`, `can`; never the address); with an argument it changes it by the rules of `PATCH /api/v1/user`, and needs admin scope: only a site admin can mint such a token, so most people sign in to `/mcp` with their password. `action: \"export\"` answers the document of `GET /api/v1/user/export` (a size summary and the link past 16,000 bytes, a bound this tool sets for itself: the MCP layer has none), for a person's account with an admin-scope token. `action: \"gift\"` (#11925), for a person on a paid plan, reads the gifts left and who took each; with `dryRun: false` and an admin-scope token it makes a one-use link to give a friend a forge, shown once", | |
| 13 | 15 | description: "Read or change your profile.", |
| 14 | 16 | inputSchema: { |
| 15 | 17 | type: "object", |
| @@ -40,7 +42,7 @@ export const tool: Tool = { | ||
| 40 | 42 | if (args["action"] === "export") return exportAnswer(ctx, user); |
| 41 | 43 | const { displayName, email, commitEmail } = args; |
| 42 | 44 | if (displayName === undefined && email === undefined && commitEmail === undefined) |
| 43 | return good({ ...publicUser(user), emailVerified: emailVerified(ctx.app.db, user.id) }); | |
| 45 | return good({ ...publicUser(user), emailVerified: emailVerified(ctx.app.db, user.id), can: capabilities(ctx.app.db, principalOf(ctx.auth)) }); | |
| 44 | 46 | if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) |
| 45 | 47 | return bad("forbidden", "changing your profile needs an admin-scope token"); |
| 46 | 48 | if (commitEmail !== undefined && commitEmail !== "noreply" && commitEmail !== "account") |
src/http/mcp/tools/whoami_can.ts +4 −1
| @@ -2,12 +2,14 @@ import { ABILITIES, roleOf, rowOf } from "../../../core/roles.ts"; | ||
| 2 | 2 | import { LAST_WAY_IN, removeOwnPasskey } from "../../../actions/passkeys.ts"; |
| 3 | 3 | import { listPasskeys } from "../../../core/passkeys.ts"; |
| 4 | 4 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 5 | import { capabilities } from "../../../core/may.ts"; | |
| 6 | import { principalOf } from "../../../core/principal.ts"; | |
| 5 | 7 | import { canAdmin, canRead, canWrite } from "../../../core/repos.ts"; |
| 6 | 8 | import { good, bad, type Tool, repoArg, isAnswer } from "../shared.ts"; |
| 7 | 9 | |
| 8 | 10 | export const tool: Tool = { |
| 9 | 11 | name: "whoami_can", |
| 10 | doc: "`{ kind?, remove?, repo? }`: who you are (`username`, and `via` when your own Talk agent asks) and your role, with that role's row of the roles table, each ability yes or no; `repo` (owner/name) adds what you may do there (`read`, `write`, `admin`); `kind: \"passkeys\"` lists your own passkeys (`{ items }`: id, name, created, lastUsed), people only; `remove: id` with `kind: \"passkeys\"` removes one of them, as Settings → Passkeys does (an admin-scope token, never an agent)", | |
| 12 | doc: "`{ kind?, remove?, repo? }`: who you are (`username`, and `via` when your own Talk agent asks) and your role, with that role's row of the roles table, each ability yes or no; `repo` (owner/name) adds what you may do there (`read`, `write`, `admin`); `actions` lists what you may do forge-wide, by the names GET /api/v1/may takes; `kind: \"passkeys\"` lists your own passkeys (`{ items }`: id, name, created, lastUsed), people only; `remove: id` with `kind: \"passkeys\"` removes one of them, as Settings → Passkeys does (an admin-scope token, never an agent)", | |
| 11 | 13 | description: |
| 12 | 14 | "What you can do: your role and each action, yes or no.", |
| 13 | 15 | inputSchema: { |
| @@ -66,6 +68,7 @@ export const tool: Tool = { | ||
| 66 | 68 | role, |
| 67 | 69 | can: rowOf(role), |
| 68 | 70 | abilities: ABILITIES, |
| 71 | actions: capabilities(ctx.app.db, principalOf(ctx.auth)), | |
| 69 | 72 | ...(here === undefined ? {} : { here }), |
| 70 | 73 | }); |
| 71 | 74 | }, |
src/tui/screens/can.ts +7 −1
| @@ -10,6 +10,8 @@ | ||
| 10 | 10 | * API's words — never the link. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { capabilities } from "../../core/may.ts"; | |
| 14 | import { principalOfUser } from "../../core/principal.ts"; | |
| 13 | 15 | import { ABILITIES, roleOf, rowOf, type Ability } from "../../core/roles.ts"; |
| 14 | 16 | import { linkedLogin, unlinkEdgeLogin } from "../../core/edge_links.ts"; |
| 15 | 17 | import { LAST_WAY_IN, linkedParent, parentIssuerOf, unlinkParent } from "../../core/federation.ts"; |
| @@ -60,6 +62,10 @@ export function canScreen(f: Session, ctx: Ctx): Screen { | ||
| 60 | 62 | const fix = mayResend() ? "v sends another link" : "add your email from account settings in a browser"; |
| 61 | 63 | return `Your email is not verified: until it is you can read and talk, but not make repositories, apps or runs. ${fix}.`; |
| 62 | 64 | }; |
| 65 | // The terminal is the account itself, signed in by its key: no token, so no scope, and `via` | |
| 66 | // says so, which is how `account.manage` is on this list as the API gives it. | |
| 67 | const mayLine = (): string => | |
| 68 | `You may: ${capabilities(f.app.db, principalOfUser(f.user, "session")).join(", ")}`; | |
| 63 | 69 | const resend = async (): Promise<void> => { |
| 64 | 70 | const sent = await resendVerification(f.app, f.user); |
| 65 | 71 | verifySaid = verifyWords(sent.ok ? sent.value : sent.error); |
| @@ -81,7 +87,7 @@ export function canScreen(f: Session, ctx: Ctx): Screen { | ||
| 81 | 87 | const row = rowOf(role); |
| 82 | 88 | const login = edgeLogin(); |
| 83 | 89 | const verify = verifyLine(); |
| 84 | [`You are ${role} here.`, ...(verify === undefined ? [] : [verify]), ...(verifySaid === undefined ? [] : [verifySaid]), ...(login === undefined ? [] : [login]), ...(parentLine() === undefined ? [] : [parentLine()!]), ...(refused === undefined ? [] : [refused]), ...(Object.keys(ABILITIES) as Ability[]).map((a) => `${ABILITIES[a]}: ${row[a] ? "yes" : "no"}`)] | |
| 90 | [`You are ${role} here.`, ...(verify === undefined ? [] : [verify]), ...(verifySaid === undefined ? [] : [verifySaid]), ...(login === undefined ? [] : [login]), ...(parentLine() === undefined ? [] : [parentLine()!]), ...(refused === undefined ? [] : [refused]), ...(Object.keys(ABILITIES) as Ability[]).map((a) => `${ABILITIES[a]}: ${row[a] ? "yes" : "no"}`), mayLine()] | |
| 85 | 91 | .slice(0, Math.max(0, area.h)) |
| 86 | 92 | .forEach((l, i) => s.text(area.x, area.y + i, truncate(l, area.w), style(c.mutedFg, c.bg), area.x + area.w)); |
| 87 | 93 | }, |
src/web/pages/account.ts +4 −4
| @@ -992,7 +992,7 @@ export async function tokenCreate(ctx: Ctx): Promise<Response> { | ||
| 992 | 992 | // Minting a token must come from the account itself — a browser session, |
| 993 | 993 | // the platform edge's sign-in, or the password — never from another token |
| 994 | 994 | // (no privilege bootstrapping). readForm below refuses a cross-site post. |
| 995 | if (!isAccountItself(ctx.auth)) { | |
| 995 | if (!isAccountItself(ctx.app.db, ctx.auth)) { | |
| 996 | 996 | return forbiddenPage(ctx, "An access code is made from your own signed-in account, never by another access code."); |
| 997 | 997 | } |
| 998 | 998 | const form = await readForm(ctx, "admin"); |
| @@ -1205,7 +1205,7 @@ export async function keyDelete(ctx: Ctx): Promise<Response> { | ||
| 1205 | 1205 | export function closeOptions(ctx: Ctx): Response { |
| 1206 | 1206 | if (crossOrigin(ctx.request, ctx.url, ctx.app.log)) return json({ error: "refused", message: CAME_FROM_ELSEWHERE }, 403); |
| 1207 | 1207 | const user = ctx.auth.user; |
| 1208 | if (user === undefined || !isAccountItself(ctx.auth)) | |
| 1208 | if (user === undefined || !isAccountItself(ctx.app.db, ctx.auth)) | |
| 1209 | 1209 | return json({ error: "refused", message: "Sign in to your account first." }, 401); |
| 1210 | 1210 | return json({ ...closeChallenge(ctx.app, user.id), rpId: ctx.url.hostname }); |
| 1211 | 1211 | } |
| @@ -1280,7 +1280,7 @@ function closeRefused(ctx: Ctx, said: CloseSaid): Response { | ||
| 1280 | 1280 | // POST /settings/account/close |
| 1281 | 1281 | export async function accountClose(ctx: Ctx): Promise<Response> { |
| 1282 | 1282 | if (!ctx.auth.user) return signInFirst(ctx); |
| 1283 | if (!isAccountItself(ctx.auth)) return forbiddenPage(ctx, CLOSE_ITSELF); | |
| 1283 | if (!isAccountItself(ctx.app.db, ctx.auth)) return forbiddenPage(ctx, CLOSE_ITSELF); | |
| 1284 | 1284 | const user = ctx.auth.user; |
| 1285 | 1285 | const form = await readForm(ctx, "admin"); |
| 1286 | 1286 | if (form instanceof Response) return form; |
| @@ -1306,7 +1306,7 @@ const CLOSE_ITSELF = "Closing an account, or keeping it, is asked from the accou | ||
| 1306 | 1306 | // POST /settings/account/keep |
| 1307 | 1307 | export async function accountKeep(ctx: Ctx): Promise<Response> { |
| 1308 | 1308 | if (!ctx.auth.user) return signInFirst(ctx); |
| 1309 | if (!isAccountItself(ctx.auth)) return forbiddenPage(ctx, CLOSE_ITSELF); | |
| 1309 | if (!isAccountItself(ctx.app.db, ctx.auth)) return forbiddenPage(ctx, CLOSE_ITSELF); | |
| 1310 | 1310 | const form = await readForm(ctx, "admin"); |
| 1311 | 1311 | if (form instanceof Response) return form; |
| 1312 | 1312 | return flashTo(ctx, "/settings", { tone: "success", message: keptSays(keepMyAccount(ctx.app, ctx.auth.user)) }); |
src/web/pages/proposal-tokens.ts +1 −1
| @@ -110,7 +110,7 @@ export async function proposalTokenMint(ctx: Ctx): Promise<Response> { | ||
| 110 | 110 | if (gate instanceof Response) return gate; |
| 111 | 111 | const { repo, form } = gate; |
| 112 | 112 | // Never minted by another token: a credential cannot grow credentials. |
| 113 | if (!isAccountItself(ctx.auth)) | |
| 113 | if (!isAccountItself(ctx.app.db, ctx.auth)) | |
| 114 | 114 | return forbiddenPage(ctx, "A token is made from your own signed-in account, never by another token."); |
| 115 | 115 | const minted = mintProposal(ctx.app, ctx.auth.user, repo, { |
| 116 | 116 | child: field(form, "child"), |
test/may.test.ts added +268
| @@ -0,0 +1,268 @@ | ||
| 1 | /** | |
| 2 | * `may(principal, action, resource)` (#18048): one answer behind `canRead`, `canWrite`, `canAdmin`, | |
| 3 | * the `actions/access.ts` wrappers and `isAccountItself`. The table below is what each of them | |
| 4 | * answered before `may` existed, for anonymous, a guest, a member, a team writer, an organization's | |
| 5 | * admin and the site's admin, on a public and a private repository: a row that changes here is | |
| 6 | * a change of who may do what. Token scope and the account-itself rule are in the same answer; | |
| 7 | * `GET /api/v1/user` lists `can` and `GET /api/v1/may` answers one question. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 10 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { addCrew, createAgentRow } from "../src/core/agents.ts"; | |
| 14 | import { addContributor } from "../src/core/invites.ts"; | |
| 15 | import { requireRepoAdmin, requireWriter, requireReader, requireParticipant } from "../src/actions/access.ts"; | |
| 16 | import { createRepo } from "../src/actions/repos.ts"; | |
| 17 | import { createApp, type App } from "../src/app.ts"; | |
| 18 | import { ACTIONS, capabilities, may } from "../src/core/may.ts"; | |
| 19 | import { principalOf, principalOfUser, type Principal } from "../src/core/principal.ts"; | |
| 20 | import type { Auth } from "../src/http/context.ts"; | |
| 21 | import type { TokenScope } from "../src/core/tokens.ts"; | |
| 22 | import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | |
| 23 | import { canAdmin, canRead, canWrite, getRepo, type Repo } from "../src/core/repos.ts"; | |
| 24 | import { createToken } from "../src/core/tokens.ts"; | |
| 25 | import { createUser, type User } from "../src/core/users.ts"; | |
| 26 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 27 | import { promote } from "./helpers/members.ts"; | |
| 28 | ||
| 29 | let dataDir = ""; | |
| 30 | let app: App, servers: Servers; | |
| 31 | const users: Record<string, User> = {}; | |
| 32 | const secrets: Record<string, string> = {}; | |
| 33 | let pub: Repo, priv: Repo; | |
| 34 | ||
| 35 | beforeAll(async () => { | |
| 36 | dataDir = await mkdtemp(join(tmpdir(), "forge-may-")); | |
| 37 | app = createApp({ dataDir, port: 0 }); | |
| 38 | servers = await serve(app); | |
| 39 | for (const [name, first] of [["boss", true], ["gina", false], ["nina", false], ["wes", false], ["wren", false]] as const) { | |
| 40 | const made = await createUser(app.db, { | |
| 41 | origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, | |
| 42 | password: "a-good-passphrase", adminIfFirst: first, | |
| 43 | }); | |
| 44 | if (!made.ok) throw new Error(String(made.error)); | |
| 45 | users[name] = made.value; | |
| 46 | } | |
| 47 | promote(app.db, users["boss"]!, users["nina"]!, users["wes"]!, users["wren"]!); | |
| 48 | const org = createOrg(app.db, "acme", users["wren"]!.id); | |
| 49 | if (!org.ok) throw new Error(String(org.error)); | |
| 50 | const team = createTeam(app.db, org.value.id, "Writers", "write"); | |
| 51 | if (!team.ok) throw new Error(String(team.error)); | |
| 52 | addTeamMember(app.db, team.value, users["wes"]!.id); | |
| 53 | for (const [name, visibility] of [["pub", "public"], ["priv", "private"]] as const) { | |
| 54 | const made = await createRepo(app, users["wren"]!, { owner: "acme", name, visibility }); | |
| 55 | if (!made.ok) throw new Error(String(made.error)); | |
| 56 | } | |
| 57 | pub = getRepo(app.db, "acme", "pub")!; | |
| 58 | priv = getRepo(app.db, "acme", "priv")!; | |
| 59 | for (const [who, scope] of [["wes", "ro"], ["wes", "rw"], ["wes", "admin"], ["wren", "ro"], ["wren", "rw"], ["nina", "ro"]] as const) | |
| 60 | secrets[`${who}:${scope}`] = createToken(app.db, users[who]!.id, scope, scope).token; | |
| 61 | }); | |
| 62 | afterAll(async () => { | |
| 63 | servers.stop(); | |
| 64 | app.close(); | |
| 65 | await rm(dataDir, { recursive: true, force: true }); | |
| 66 | }); | |
| 67 | ||
| 68 | const as = (who: string | undefined): User | undefined => (who === undefined ? undefined : users[who]); | |
| 69 | ||
| 70 | // [read, write, admin] before `may`, by who and which repository. | |
| 71 | const PINNED: Record<"public" | "private", [string | undefined, string, string, string][]> = { | |
| 72 | public: [ | |
| 73 | [undefined, "yes", "no", "no"], | |
| 74 | ["gina", "yes", "no", "no"], | |
| 75 | ["nina", "yes", "no", "no"], | |
| 76 | ["wes", "yes", "yes", "no"], | |
| 77 | ["wren", "yes", "yes", "yes"], | |
| 78 | ["boss", "yes", "yes", "yes"], | |
| 79 | ], | |
| 80 | private: [ | |
| 81 | [undefined, "no", "no", "no"], | |
| 82 | ["gina", "no", "no", "no"], | |
| 83 | ["nina", "no", "no", "no"], | |
| 84 | ["wes", "yes", "yes", "no"], | |
| 85 | ["wren", "yes", "yes", "yes"], | |
| 86 | ["boss", "yes", "yes", "yes"], | |
| 87 | ], | |
| 88 | }; | |
| 89 | const yn = (b: boolean) => (b ? "yes" : "no"); | |
| 90 | ||
| 91 | test("canRead, canWrite and canAdmin answer what they always did", () => { | |
| 92 | for (const kind of ["public", "private"] as const) | |
| 93 | for (const [who, read, write, admin] of PINNED[kind]) { | |
| 94 | const repo = kind === "public" ? pub : priv; | |
| 95 | const got = [yn(canRead(app.db, repo, as(who))), yn(canWrite(app.db, repo, as(who))), yn(canAdmin(app.db, repo, as(who)))]; | |
| 96 | expect(got, `${who ?? "anonymous"} on ${kind}`).toEqual([read, write, admin]); | |
| 97 | // and the wrappers over them | |
| 98 | const actor = as(who); | |
| 99 | expect(requireReader(app, actor, repo).ok).toBe(read === "yes"); | |
| 100 | expect(requireParticipant(app, actor, repo).ok).toBe(read === "yes" && actor !== undefined); | |
| 101 | const writer = requireWriter(app, actor, repo); | |
| 102 | expect(writer.ok, `${who} writer`).toBe(write === "yes"); | |
| 103 | expect(requireRepoAdmin(app, actor, repo).ok).toBe(admin === "yes"); | |
| 104 | if (!writer.ok) | |
| 105 | expect(writer.error).toBe(read === "no" ? "not_found" : actor === undefined ? "unauthorized" : "forbidden"); | |
| 106 | } | |
| 107 | }); | |
| 108 | ||
| 109 | /** A token's principal, as a request bearing it is read. */ | |
| 110 | const bearer = (user: User | undefined, scope: TokenScope): Principal => principalOf({ user, scope, via: "token" }); | |
| 111 | ||
| 112 | const ask = (p: Principal, action: "repo.read" | "repo.write" | "repo.admin", repo: Repo) => { | |
| 113 | const a = may(app.db, p, action, { repo }); | |
| 114 | return a.ok ? "yes" : a.why; | |
| 115 | }; | |
| 116 | ||
| 117 | test("a no says which of the forge's answers applies", () => { | |
| 118 | const why = (who: string | undefined, action: "repo.read" | "repo.write" | "repo.admin", repo: Repo) => ask(principalOfUser(as(who)), action, repo); | |
| 119 | expect(why(undefined, "repo.read", priv)).toBe("not_found"); | |
| 120 | expect(why(undefined, "repo.write", priv)).toBe("not_found"); | |
| 121 | expect(why(undefined, "repo.write", pub)).toBe("unauthorized"); | |
| 122 | expect(why("nina", "repo.write", pub)).toBe("forbidden"); | |
| 123 | expect(why("nina", "repo.admin", priv)).toBe("not_found"); | |
| 124 | expect(why("wes", "repo.admin", priv)).toBe("forbidden"); | |
| 125 | expect(why("wes", "repo.write", priv)).toBe("yes"); | |
| 126 | }); | |
| 127 | ||
| 128 | test("a token's scope is part of the answer: ro reads, rw changes, admin acts as rw does", () => { | |
| 129 | const token = (who: string, scope: "ro" | "rw" | "admin", action: "repo.read" | "repo.write" | "repo.admin", repo: Repo) => | |
| 130 | ask(bearer(as(who), scope), action, repo); | |
| 131 | for (const repo of [pub, priv]) { | |
| 132 | expect(token("wes", "ro", "repo.read", repo)).toBe("yes"); | |
| 133 | expect(token("wes", "ro", "repo.write", repo)).toBe("forbidden"); | |
| 134 | expect(token("wes", "rw", "repo.write", repo)).toBe("yes"); | |
| 135 | expect(token("wes", "admin", "repo.write", repo)).toBe("yes"); | |
| 136 | expect(token("wes", "admin", "repo.admin", repo)).toBe("forbidden"); | |
| 137 | expect(token("wren", "ro", "repo.admin", repo)).toBe("forbidden"); | |
| 138 | expect(token("wren", "rw", "repo.admin", repo)).toBe("yes"); | |
| 139 | } | |
| 140 | // A token never makes a repository visible that its person cannot read. | |
| 141 | expect(token("nina", "ro", "repo.read", priv)).toBe("not_found"); | |
| 142 | const refused = may(app.db, bearer(as("wes"), "ro"), "repo.write", { repo: pub }); | |
| 143 | expect(refused.ok ? "" : refused.says).toContain("scope"); | |
| 144 | }); | |
| 145 | ||
| 146 | test("a token is not a person: account.manage is the account itself", () => { | |
| 147 | const by = (via: Auth["via"], scope?: TokenScope) => may(app.db, principalOf({ user: as("nina"), scope, via }), "account.manage"); | |
| 148 | for (const via of ["session", "edge", "password"] as const) expect(by(via, "admin").ok).toBe(true); | |
| 149 | for (const scope of ["ro", "rw", "admin"] as const) expect(by("token", scope).ok).toBe(false); | |
| 150 | expect(by("none").ok).toBe(false); | |
| 151 | expect(may(app.db, principalOfUser(undefined), "account.manage")).toMatchObject({ ok: false, why: "unauthorized" }); | |
| 152 | }); | |
| 153 | ||
| 154 | test("the forge-wide actions follow the roles table", () => { | |
| 155 | const can = (who: string | undefined, scope?: "ro" | "rw" | "admin") => capabilities(app.db, scope === undefined ? principalOfUser(as(who)) : bearer(as(who), scope)); | |
| 156 | expect(can(undefined)).toEqual(["forge.read"]); | |
| 157 | expect(can("gina")).toEqual(["forge.read", "forge.comment", "forge.contribute"]); | |
| 158 | expect(can("nina")).toEqual(["forge.read", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]); | |
| 159 | expect(can("boss")).toContain("forge.administer"); | |
| 160 | expect(can("nina")).not.toContain("forge.administer"); | |
| 161 | expect(can("boss", "ro")).toEqual(["forge.read"]); | |
| 162 | for (const name of Object.keys(ACTIONS)) expect(ACTIONS[name as keyof typeof ACTIONS].says).not.toBe(""); | |
| 163 | }); | |
| 164 | ||
| 165 | const get = async (path: string, who?: string) => { | |
| 166 | const headers: Record<string, string> = who === undefined ? {} : { authorization: `Bearer ${secrets[who]}` }; | |
| 167 | const res = await fetch(servers.url + path, { headers }); | |
| 168 | const body = (await res.json()) as Record<string, unknown>; | |
| 169 | return { status: res.status, body }; | |
| 170 | }; | |
| 171 | ||
| 172 | test("GET /api/v1/user lists what the caller may do, by the registry's names", async () => { | |
| 173 | const rw = await get("/api/v1/user", "wes:rw"); | |
| 174 | expect(rw.body["can"]).toEqual(["forge.read", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]); | |
| 175 | expect((await get("/api/v1/user", "wes:ro")).body["can"]).toEqual(["forge.read"]); | |
| 176 | }); | |
| 177 | ||
| 178 | test("GET /api/v1/may answers yes or no with the reason in words", async () => { | |
| 179 | const yes = await get("/api/v1/may?action=repo.write&resource=acme/priv", "wes:rw"); | |
| 180 | expect(yes).toMatchObject({ status: 200, body: { action: "repo.write", resource: "acme/priv", may: true } }); | |
| 181 | const low = await get("/api/v1/may?action=repo.write&resource=acme/priv", "wes:ro"); | |
| 182 | expect(low.body).toMatchObject({ may: false, why: "forbidden" }); | |
| 183 | expect(String(low.body["reason"])).toContain("scope"); | |
| 184 | const anon = await get("/api/v1/may?action=repo.write&resource=acme/pub"); | |
| 185 | expect(anon.body).toMatchObject({ may: false, why: "unauthorized", reason: "Sign in to do this." }); | |
| 186 | // a private repository and one that is not there answer alike | |
| 187 | const hidden = await get("/api/v1/may?action=repo.read&resource=acme/priv", "nina:ro"); | |
| 188 | const absent = await get("/api/v1/may?action=repo.read&resource=acme/nothing", "nina:ro"); | |
| 189 | expect(hidden.body).toEqual({ ...absent.body, resource: "acme/priv" }); | |
| 190 | expect(hidden.body).toMatchObject({ may: false, why: "not_found" }); | |
| 191 | expect((await get("/api/v1/may?action=forge.administer", "wes:rw")).body).toMatchObject({ may: false, why: "forbidden" }); | |
| 192 | }); | |
| 193 | ||
| 194 | test("GET /api/v1/may validates its input", async () => { | |
| 195 | expect((await get("/api/v1/may?action=nope")).status).toBe(422); | |
| 196 | expect((await get("/api/v1/may")).body["error"]).toBe("unknown_action"); | |
| 197 | expect((await get("/api/v1/may?action=repo.read")).status).toBe(422); | |
| 198 | expect((await get("/api/v1/may?action=repo.read&resource=acme/pub/x")).status).toBe(422); | |
| 199 | expect((await get("/api/v1/may?action=forge.read&resource=acme/pub")).status).toBe(422); | |
| 200 | const bad = await fetch(`${servers.url}/api/v1/may?action=forge.read`, { headers: { authorization: "Bearer forge_nonsense" } }); | |
| 201 | expect(bad.status).toBe(401); | |
| 202 | }); | |
| 203 | ||
| 204 | // Who a token or a credential stands for, beyond the people above: each row is what the repository | |
| 205 | // trio answered before `may` existed — [read, write, admin] on the public repository, then on the | |
| 206 | // private one. The kinds: a run's token (a crew agent, or an agent that is not on the crew), a | |
| 207 | // proposal token (the rw token of the writer who minted it; a follow token is its ro one), a | |
| 208 | // contributor, and an app's token (a user with an app id) on a native and on a read-only mirror. | |
| 209 | test("each kind of token and credential answers what it did before may", async () => { | |
| 210 | const mk = async (name: string, kind?: "agent"): Promise<User> => { | |
| 211 | const made = await createUser(app.db, { | |
| 212 | username: name, email: `${name}@forge.local`, | |
| 213 | ...(kind === undefined | |
| 214 | ? { password: "a-good-passphrase", origin: "seed" as const, trusted: true } | |
| 215 | : { agent: true, origin: "agent" as const }), | |
| 216 | }); | |
| 217 | if (!made.ok) throw new Error(String(made.error)); | |
| 218 | return made.value; | |
| 219 | }; | |
| 220 | const crewAgent = await mk("runner", "agent"); | |
| 221 | const strayAgent = await mk("stray", "agent"); | |
| 222 | createAgentRow(app.db, { userId: crewAgent.id, roles: ["builder"] }); | |
| 223 | createAgentRow(app.db, { userId: strayAgent.id, roles: ["builder"] }); | |
| 224 | addCrew(app.db, priv.id, crewAgent.id, users["wren"]!.id, "builder"); | |
| 225 | const guest = await mk("carol"); | |
| 226 | addContributor(app.db, priv.id, guest.id, users["wren"]!.id); | |
| 227 | const contributed = getRepo(app.db, "acme", "priv")!; | |
| 228 | const appUser: User = { ...users["nina"]!, appId: "app1" }; | |
| 229 | ||
| 230 | const row = (p: Principal, repo: Repo): string => | |
| 231 | (["repo.read", "repo.write", "repo.admin"] as const).map((a) => yn(may(app.db, p, a, { repo }).ok)).join(" "); | |
| 232 | const direct = (u: User, repo: Repo): string => [yn(canRead(app.db, repo, u)), yn(canWrite(app.db, repo, u)), yn(canAdmin(app.db, repo, u))].join(" "); | |
| 233 | ||
| 234 | // run token: a crew agent reads what it works on and writes nothing by that | |
| 235 | expect(row(bearer(crewAgent, "rw"), pub)).toBe("yes no no"); | |
| 236 | expect(row(bearer(crewAgent, "rw"), contributed)).toBe("yes no no"); | |
| 237 | expect(row(bearer(strayAgent, "rw"), pub)).toBe("yes no no"); | |
| 238 | expect(row(bearer(strayAgent, "rw"), priv)).toBe("no no no"); | |
| 239 | expect(direct(crewAgent, contributed)).toBe("yes no no"); | |
| 240 | // proposal token: the writer's rw token; a follow token is the same person on ro | |
| 241 | expect(row(bearer(users["wes"], "rw"), pub)).toBe("yes yes no"); | |
| 242 | expect(row(bearer(users["wes"], "rw"), priv)).toBe("yes yes no"); | |
| 243 | expect(row(bearer(users["wes"], "ro"), pub)).toBe("yes no no"); | |
| 244 | expect(row(bearer(users["wes"], "ro"), priv)).toBe("yes no no"); | |
| 245 | // contribute token: a contributor reads the repository they were let into and changes nothing | |
| 246 | expect(row(bearer(guest, "ro"), contributed)).toBe("yes no no"); | |
| 247 | expect(row(bearer(guest, "rw"), contributed)).toBe("yes no no"); | |
| 248 | expect(row(bearer(guest, "ro"), pub)).toBe("yes no no"); | |
| 249 | expect(direct(guest, contributed)).toBe("yes no no"); | |
| 250 | expect(row(bearer(users["gina"], "ro"), priv)).toBe("no no no"); | |
| 251 | // app token: on a native repository an app's user is the person it stands for | |
| 252 | expect(row(bearer(appUser, "ro"), pub)).toBe("yes no no"); | |
| 253 | expect(row(bearer(appUser, "ro"), priv)).toBe("no no no"); | |
| 254 | // and on a mirror of a read-only origin it reads only what it was granted (the mirror rule in | |
| 255 | // readsRepo) | |
| 256 | app.db.run( | |
| 257 | "INSERT INTO origin (id, user_id, kind, api_url, web_url, login, token_enc, read_only) VALUES ('o1', ?1, 'github', 'https://api.example.com', 'https://example.com', 'octo', 'x', 1)", | |
| 258 | [users["wren"]!.id], | |
| 259 | ); | |
| 260 | const mirror = { ...pub, origin: { ...(pub.origin ?? {}), originId: "o1", kind: "github", software: "", fullName: "", htmlUrl: "", lastFetchAt: null } } as unknown as Repo; | |
| 261 | const mirrorPriv = { ...priv, origin: mirror.origin } as Repo; | |
| 262 | expect(row(bearer(appUser, "ro"), mirror)).toBe("no no no"); | |
| 263 | expect(row(bearer(appUser, "ro"), mirrorPriv)).toBe("no no no"); | |
| 264 | expect(row(bearer(users["nina"], "ro"), mirror)).toBe("yes no no"); | |
| 265 | app.db.run("INSERT INTO origin_read_grant (repo_id, kind, grantee_id, granted_by) VALUES (?1, 'app', 'app1', ?2)", [pub.id, users["wren"]!.id]); | |
| 266 | expect(row(bearer(appUser, "ro"), mirror)).toBe("yes no no"); | |
| 267 | expect(row(bearer(appUser, "ro"), mirrorPriv)).toBe("no no no"); | |
| 268 | }); |
test/tui-can.test.ts +2
| @@ -65,6 +65,8 @@ describe("what I can do in the terminal", () => { | ||
| 65 | 65 | const guest = await shown("bob"); |
| 66 | 66 | expect(guest).toContain("You are guest here."); |
| 67 | 67 | expect(guest).toContain("Create a repository or copy an app: no"); |
| 68 | // the same list GET /api/v1/user gives a session, with the account's own `account.manage` on it | |
| 69 | expect(guest).toContain("You may: forge.read, forge.comment, forge.contribute, account.manage"); | |
| 68 | 70 | setMember(forge.db, getUserByName(forge.db, "bob")!.id, true, "x", new Date()); |
| 69 | 71 | const member = await shown("bob"); |
| 70 | 72 | expect(member).toContain("You are member here."); |
new above
offline
A second
Principalbesidesrc/core/principal.ts's (Access 1, on main). Take that one, or build this shape from it in one place, and remove this interface: only one way to say who is asking.