Public: anyone can read this; the crew can change it.
Propose upstream across forges, part 2: mint, list and revoke proposal tokens from the page, the terminal and MCP #2222
scout/forge:scout/2187-propose-upstream-across-forges-part-2-mi → main 1 commit fork
12 files
changed +707
−19
README.md +7 −2
| @@ -92,8 +92,13 @@ curl -sX POST localhost:3000/api/v1/repos/you/hello/proposal-tokens \ | ||
| 92 | 92 | `childRepo` (optional) a fork of this repository, and deleting it deletes the |
| 93 | 93 | token, as does deleting the repository. The token expires in 30 days. It is |
| 94 | 94 | listed as `proposal:<child>` among your tokens, and revoking it there ends it. |
| 95 | Minting is API-only for now; a page, a terminal command and an MCP tool are | |
| 96 | part 2 (#2187). Over HTTPS it pushes only `child/<name>/…` branches of this repository (anything | |
| 95 | Every door calls the same `mintProposal` (`src/actions/proposal_tokens.ts`): | |
| 96 | the form under Settings → General → Proposal tokens (which lists them by child, | |
| 97 | each with a Revoke), the terminal's "Proposal tokens of a repository" command | |
| 98 | (`n` mints, `x` revokes), MCP's `proposal_token_mint`, `proposal_tokens` and | |
| 99 | `proposal_token_revoke`, and `GET`/`DELETE …/proposal-tokens[/:id]`. Each | |
| 100 | works on your own tokens and needs write on the repository; the account's token | |
| 101 | list shows the child and origin beside the name. Over HTTPS it pushes only `child/<name>/…` branches of this repository (anything | |
| 97 | 102 | else is refused with one line) and `POST …/pulls` from one of them, with a |
| 98 | 103 | body of at most 64 KiB and 20 requests a minute. Every other request is a |
| 99 | 104 | 403, decided in `src/http/proposal_gate.ts` before any handler runs. A proposed pull |
src/actions/proposal_tokens.ts added +97
| @@ -0,0 +1,97 @@ | ||
| 1 | /** | |
| 2 | * Proposal tokens (`core/proposal_token.ts`) for every door — the settings | |
| 3 | * form, `POST …/proposal-tokens`, MCP's `proposal_tokens` and the terminal: | |
| 4 | * mint one for a named child, list a repository's by child, revoke one. | |
| 5 | * A writer of the repository does all three, on their own tokens only; a | |
| 6 | * repository the actor cannot write is `not_found`, as everywhere. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { | |
| 11 | listProposalTokens, | |
| 12 | mintProposalToken, | |
| 13 | type ProposalListing, | |
| 14 | } from "../core/proposal_token.ts"; | |
| 15 | import { canWrite, getRepo, type Repo } from "../core/repos.ts"; | |
| 16 | import { deleteToken } from "../core/tokens.ts"; | |
| 17 | import type { User } from "../core/users.ts"; | |
| 18 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 19 | ||
| 20 | export type ProposalTokenError = | |
| 21 | | "unauthorized" | |
| 22 | | "not_found" | |
| 23 | | "invalid_child" | |
| 24 | | "invalid_origin"; | |
| 25 | ||
| 26 | const writer = (app: App, actor: User | undefined, repo: Repo): actor is User => | |
| 27 | actor !== undefined && canWrite(app.db, repo, actor); | |
| 28 | ||
| 29 | /** | |
| 30 | * Mint a token for `child`. `childRepo` (`owner/name`), when given, must be | |
| 31 | * a fork of this repository. The secret is returned once. | |
| 32 | */ | |
| 33 | export function mintProposal( | |
| 34 | app: App, | |
| 35 | actor: User | undefined, | |
| 36 | repo: Repo, | |
| 37 | input: { child: string; origin: string; childRepo?: string }, | |
| 38 | ): Result<{ id: string; token: string }, ProposalTokenError> { | |
| 39 | if (!writer(app, actor, repo)) return err("not_found"); | |
| 40 | let childRepoId: string | undefined; | |
| 41 | const spec = input.childRepo ?? ""; | |
| 42 | if (spec !== "") { | |
| 43 | const [owner, name, ...rest] = spec.split("/"); | |
| 44 | const child = | |
| 45 | owner && name && rest.length === 0 ? getRepo(app.db, owner, name) : undefined; | |
| 46 | if (!child || child.forkParentId !== repo.id) return err("not_found"); | |
| 47 | childRepoId = child.id; | |
| 48 | } | |
| 49 | const minted = mintProposalToken(app.db, actor.id, repo.id, { | |
| 50 | child: input.child, | |
| 51 | origin: input.origin, | |
| 52 | ...(childRepoId ? { childRepoId } : {}), | |
| 53 | }); | |
| 54 | if (!minted.ok) return minted; | |
| 55 | app.bus.append({ | |
| 56 | kind: "token.created", | |
| 57 | actorId: actor.id, | |
| 58 | payload: { | |
| 59 | tokenId: minted.value.id, | |
| 60 | name: `proposal:${input.child}`, | |
| 61 | scope: "rw", | |
| 62 | repoId: repo.id, | |
| 63 | }, | |
| 64 | }); | |
| 65 | return minted; | |
| 66 | } | |
| 67 | ||
| 68 | /** The actor's proposal tokens for this repository, grouped by child. */ | |
| 69 | export function listProposals( | |
| 70 | app: App, | |
| 71 | actor: User | undefined, | |
| 72 | repo: Repo, | |
| 73 | ): Result<ProposalListing[], "not_found"> { | |
| 74 | if (!writer(app, actor, repo)) return err("not_found"); | |
| 75 | return ok(listProposalTokens(app.db, actor.id, repo.id)); | |
| 76 | } | |
| 77 | ||
| 78 | /** Revoke one of the actor's proposal tokens for this repository. */ | |
| 79 | export function revokeProposal( | |
| 80 | app: App, | |
| 81 | actor: User | undefined, | |
| 82 | repo: Repo, | |
| 83 | tokenId: string, | |
| 84 | ): Result<void, "not_found"> { | |
| 85 | if (!writer(app, actor, repo)) return err("not_found"); | |
| 86 | // Only a proposal token of this repository: an ordinary token is revoked | |
| 87 | // from the account page, not through a repository's door. | |
| 88 | if (!listProposalTokens(app.db, actor.id, repo.id).some((p) => p.tokenId === tokenId)) | |
| 89 | return err("not_found"); | |
| 90 | if (!deleteToken(app.db, actor.id, tokenId)) return err("not_found"); | |
| 91 | app.bus.append({ | |
| 92 | kind: "token.deleted", | |
| 93 | actorId: actor.id, | |
| 94 | payload: { tokenId, repoId: repo.id }, | |
| 95 | }); | |
| 96 | return ok(); | |
| 97 | } |
src/core/proposal_token.ts +60
| @@ -81,6 +81,66 @@ export function mintProposalToken( | ||
| 81 | 81 | return ok(minted); |
| 82 | 82 | } |
| 83 | 83 | |
| 84 | export interface ProposalListing extends Proposal { | |
| 85 | readonly childRepoId: string | null; | |
| 86 | readonly createdAt: string; | |
| 87 | readonly lastUsedAt: string | null; | |
| 88 | readonly expiresAt: string | null; | |
| 89 | } | |
| 90 | ||
| 91 | /** One person's proposal tokens for a repository, grouped by child. */ | |
| 92 | export function listProposalTokens( | |
| 93 | db: Database, | |
| 94 | userId: string, | |
| 95 | repoId: string, | |
| 96 | ): ProposalListing[] { | |
| 97 | return db | |
| 98 | .query< | |
| 99 | { | |
| 100 | token_id: string; | |
| 101 | repo_id: string; | |
| 102 | child: string; | |
| 103 | origin: string; | |
| 104 | child_repo_id: string | null; | |
| 105 | created_at: string; | |
| 106 | last_used_at: string | null; | |
| 107 | expires_at: string | null; | |
| 108 | }, | |
| 109 | [string, string] | |
| 110 | >( | |
| 111 | `SELECT p.token_id, p.repo_id, p.child, p.origin, p.child_repo_id, | |
| 112 | t.created_at, t.last_used_at, t.expires_at | |
| 113 | FROM proposal_token p JOIN token t ON t.id = p.token_id | |
| 114 | WHERE t.user_id = ?1 AND p.repo_id = ?2 | |
| 115 | ORDER BY p.child, p.token_id`, | |
| 116 | ) | |
| 117 | .all(userId, repoId) | |
| 118 | .map((r) => ({ | |
| 119 | tokenId: r.token_id, | |
| 120 | repoId: r.repo_id, | |
| 121 | child: r.child, | |
| 122 | origin: r.origin, | |
| 123 | childRepoId: r.child_repo_id, | |
| 124 | createdAt: r.created_at, | |
| 125 | lastUsedAt: r.last_used_at, | |
| 126 | expiresAt: r.expires_at, | |
| 127 | })); | |
| 128 | } | |
| 129 | ||
| 130 | /** The proposal behind each of a person's tokens that has one, by token id. */ | |
| 131 | export function proposalsByToken( | |
| 132 | db: Database, | |
| 133 | userId: string, | |
| 134 | ): Map<string, { child: string; origin: string }> { | |
| 135 | const rows = db | |
| 136 | .query<{ token_id: string; child: string; origin: string }, [string]>( | |
| 137 | `SELECT p.token_id, p.child, p.origin FROM proposal_token p | |
| 138 | JOIN token t ON t.id = p.token_id WHERE t.user_id = ?1`, | |
| 139 | ) | |
| 140 | .all(userId); | |
| 141 | return new Map(rows.map((r) => [r.token_id, { child: r.child, origin: r.origin }])); | |
| 142 | } | |
| 143 | ||
| 84 | 144 | /** What a token is limited to, or undefined for an ordinary token. */ |
| 85 | 145 | export function proposalOf(db: Database, tokenId: string): Proposal | undefined { |
| 86 | 146 | const row = db |
src/http/api.ts +33 −15
| @@ -215,9 +215,13 @@ import { | ||
| 215 | 215 | } from "../core/reviews.ts"; |
| 216 | 216 | import { createSession } from "../core/sessions.ts"; |
| 217 | 217 | import { listTokens } from "../core/tokens.ts"; |
| 218 | import { | |
| 219 | listProposals, | |
| 220 | mintProposal, | |
| 221 | revokeProposal, | |
| 222 | } from "../actions/proposal_tokens.ts"; | |
| 218 | 223 | import { |
| 219 | 224 | headInNamespace, |
| 220 | mintProposalToken, | |
| 221 | 225 | PROPOSAL_BODY_MAX, |
| 222 | 226 | pullProposalOf, |
| 223 | 227 | recordPullProposal, |
| @@ -3108,6 +3112,29 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 3108 | 3112 | return json(paged(items, query.limit, (p) => p.number)); |
| 3109 | 3113 | }); |
| 3110 | 3114 | |
| 3115 | // The writer's own proposal tokens for this repository, by child. | |
| 3116 | router.add("GET", "/api/v1/repos/:owner/:name/proposal-tokens", (ctx) => { | |
| 3117 | const denied = requireScope(ctx, "rw"); | |
| 3118 | if (denied) return denied; | |
| 3119 | const repo = loadRepo(ctx); | |
| 3120 | const listed = repo ? listProposals(ctx.app, ctx.auth.user, repo) : undefined; | |
| 3121 | return listed?.ok ? json(listed.value) : notFound(); | |
| 3122 | }); | |
| 3123 | ||
| 3124 | router.add( | |
| 3125 | "DELETE", | |
| 3126 | "/api/v1/repos/:owner/:name/proposal-tokens/:id", | |
| 3127 | (ctx) => { | |
| 3128 | const denied = requireScope(ctx, "rw"); | |
| 3129 | if (denied) return denied; | |
| 3130 | const repo = loadRepo(ctx); | |
| 3131 | const revoked = repo | |
| 3132 | ? revokeProposal(ctx.app, ctx.auth.user, repo, ctx.params.id!) | |
| 3133 | : undefined; | |
| 3134 | return revoked?.ok ? new Response(null, { status: 204 }) : notFound(); | |
| 3135 | }, | |
| 3136 | ); | |
| 3137 | ||
| 3111 | 3138 | // A writer hands a child its own narrow credential for this repository |
| 3112 | 3139 | // (`core/proposal_token.ts`); the secret is shown once, as for any token. |
| 3113 | 3140 | router.add( |
| @@ -3121,24 +3148,15 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 3121 | 3148 | const input = await boundedBody(ctx.request, PROPOSAL_BODY_MAX); |
| 3122 | 3149 | if (input === "too_large") |
| 3123 | 3150 | return apiError("too_large", 413, `at most ${PROPOSAL_BODY_MAX} bytes`); |
| 3124 | let childRepoId: string | undefined; | |
| 3125 | const childSpec = str(input.childRepo); | |
| 3126 | if (childSpec !== "") { | |
| 3127 | const [owner, name, ...rest] = childSpec.split("/"); | |
| 3128 | const child = | |
| 3129 | owner && name && rest.length === 0 | |
| 3130 | ? getRepo(ctx.app.db, owner, name) | |
| 3131 | : undefined; | |
| 3132 | if (!child || child.forkParentId !== repo.id) return notFound(); | |
| 3133 | childRepoId = child.id; | |
| 3134 | } | |
| 3135 | const minted = mintProposalToken(ctx.app.db, ctx.auth.user!.id, repo.id, { | |
| 3151 | const minted = mintProposal(ctx.app, ctx.auth.user, repo, { | |
| 3136 | 3152 | child: str(input.child), |
| 3137 | 3153 | origin: str(input.origin), |
| 3138 | ...(childRepoId ? { childRepoId } : {}), | |
| 3154 | childRepo: str(input.childRepo), | |
| 3139 | 3155 | }); |
| 3140 | 3156 | if (!minted.ok) |
| 3141 | return apiError(minted.error, 422, "child is lowercase words and hyphens; origin is an https address"); | |
| 3157 | return minted.error === "invalid_child" || minted.error === "invalid_origin" | |
| 3158 | ? apiError(minted.error, 422, "child is lowercase words and hyphens; origin is an https address") | |
| 3159 | : notFound(); | |
| 3142 | 3160 | return json(minted.value, 201); |
| 3143 | 3161 | }, |
| 3144 | 3162 | ); |
src/http/mcp.ts +68
| @@ -108,6 +108,7 @@ import { | ||
| 108 | 108 | } from "../core/repos.ts"; |
| 109 | 109 | import { plannerDeclines } from "../crew/autonomy.ts"; |
| 110 | 110 | import { checkSummary, listActiveRuns } from "../core/runs.ts"; |
| 111 | import { listProposals, mintProposal, revokeProposal } from "../actions/proposal_tokens.ts"; | |
| 111 | 112 | import { scopeAllows } from "../core/tokens.ts"; |
| 112 | 113 | import { getUserByName, getUsersByIds, type User } from "../core/users.ts"; |
| 113 | 114 | import { openapi } from "../contract/openapi.ts"; |
| @@ -1770,6 +1771,73 @@ const TOOLS: readonly Tool[] = [ | ||
| 1770 | 1771 | : bad("not_found", "no such app or repository (owner/name)"); |
| 1771 | 1772 | }, |
| 1772 | 1773 | }, |
| 1774 | { | |
| 1775 | name: "proposal_token_mint", | |
| 1776 | description: | |
| 1777 | "Mint a proposal token for a child forge: a credential for you that can only push `child/<name>/…` branches to this repository and open pulls from them, and expires in 30 days. Writers only. `child` is lowercase words and hyphens; `origin` is the child's https address; `childRepo` (owner/name, optional) is a fork of this repository. The secret is in this answer once and so in this conversation: hand it only to the child.", | |
| 1778 | inputSchema: { | |
| 1779 | type: "object", | |
| 1780 | properties: { | |
| 1781 | repo: REPO_ARG, | |
| 1782 | child: { type: "string", maxLength: 40 }, | |
| 1783 | origin: { type: "string", maxLength: 200 }, | |
| 1784 | childRepo: { type: "string", maxLength: 200 }, | |
| 1785 | }, | |
| 1786 | required: ["repo", "child", "origin"], | |
| 1787 | }, | |
| 1788 | writes: true, | |
| 1789 | run(ctx, user, args) { | |
| 1790 | const repo = repoArg(ctx, user, args); | |
| 1791 | if (isAnswer(repo)) return repo; | |
| 1792 | const made = mintProposal(ctx.app, user, repo, { | |
| 1793 | child: str(args["child"]), | |
| 1794 | origin: str(args["origin"]), | |
| 1795 | childRepo: str(args["childRepo"]), | |
| 1796 | }); | |
| 1797 | if (made.ok) return good(made.value); | |
| 1798 | return made.error === "invalid_child" || made.error === "invalid_origin" | |
| 1799 | ? bad(made.error, "child is lowercase words and hyphens; origin is an https address") | |
| 1800 | : bad("not_found", "no such repository you can write (owner/name), or no such fork"); | |
| 1801 | }, | |
| 1802 | }, | |
| 1803 | { | |
| 1804 | name: "proposal_tokens", | |
| 1805 | description: | |
| 1806 | "Your proposal tokens for a repository, by child: id, child, origin, when made, last used and when each expires. Never the secrets. Writers only.", | |
| 1807 | inputSchema: { | |
| 1808 | type: "object", | |
| 1809 | properties: { repo: REPO_ARG }, | |
| 1810 | required: ["repo"], | |
| 1811 | }, | |
| 1812 | writes: false, | |
| 1813 | run(ctx, user, args) { | |
| 1814 | const repo = repoArg(ctx, user, args); | |
| 1815 | if (isAnswer(repo)) return repo; | |
| 1816 | const listed = listProposals(ctx.app, user, repo); | |
| 1817 | return listed.ok | |
| 1818 | ? good({ tokens: listed.value }) | |
| 1819 | : bad("not_found", "no such repository you can write (owner/name)"); | |
| 1820 | }, | |
| 1821 | }, | |
| 1822 | { | |
| 1823 | name: "proposal_token_revoke", | |
| 1824 | description: | |
| 1825 | "Revoke one of your proposal tokens for a repository by its id (from `proposal_tokens`). The child's next request is refused.", | |
| 1826 | inputSchema: { | |
| 1827 | type: "object", | |
| 1828 | properties: { repo: REPO_ARG, id: { type: "string", maxLength: 100 } }, | |
| 1829 | required: ["repo", "id"], | |
| 1830 | }, | |
| 1831 | writes: true, | |
| 1832 | run(ctx, user, args) { | |
| 1833 | const repo = repoArg(ctx, user, args); | |
| 1834 | if (isAnswer(repo)) return repo; | |
| 1835 | const revoked = revokeProposal(ctx.app, user, repo, str(args["id"])); | |
| 1836 | return revoked.ok | |
| 1837 | ? good({ revoked: true }) | |
| 1838 | : bad("not_found", "no such proposal token of yours for that repository"); | |
| 1839 | }, | |
| 1840 | }, | |
| 1773 | 1841 | { |
| 1774 | 1842 | name: "usage", |
| 1775 | 1843 | description: |
src/http/server.ts +7
| @@ -258,6 +258,7 @@ import { appNowFragment } from "../web/studio/now.ts"; | ||
| 258 | 258 | import { appStateFragment } from "../web/studio/previews.ts"; |
| 259 | 259 | import { changesList, tellsList } from "../web/studio/lists.ts"; |
| 260 | 260 | import { dependencySubmit } from "../web/pages/thread.ts"; |
| 261 | import { proposalTokenMint, proposalTokenRevoke } from "../web/pages/proposal_tokens.ts"; | |
| 261 | 262 | import { |
| 262 | 263 | assigneeSubmit, |
| 263 | 264 | labelsSubmit, |
| @@ -1230,6 +1231,12 @@ export function buildRouter(): Router<Handler> { | ||
| 1230 | 1231 | router.add("POST", "/:owner/:name/settings", settingsUpdate); |
| 1231 | 1232 | router.add("POST", "/:owner/:name/settings/wave", waveCut); |
| 1232 | 1233 | router.add("POST", "/:owner/:name/settings/archive", archiveSubmit); |
| 1234 | router.add("POST", "/:owner/:name/settings/proposal-tokens", proposalTokenMint); | |
| 1235 | router.add( | |
| 1236 | "POST", | |
| 1237 | "/:owner/:name/settings/proposal-tokens/:id/delete", | |
| 1238 | proposalTokenRevoke, | |
| 1239 | ); | |
| 1233 | 1240 | router.add("GET", "/:owner/:name/settings/app", appSettingsPage); |
| 1234 | 1241 | router.add("POST", "/:owner/:name/settings/app", appSettingsUpdate); |
| 1235 | 1242 | router.add("POST", "/:owner/:name/settings/app/disable", appDisable); |
src/tui/forge.ts +6
| @@ -60,6 +60,7 @@ import { mayRead } from "../release/gate.ts"; | ||
| 60 | 60 | import { stalledScreen } from "./screens/stalled.ts"; |
| 61 | 61 | import { issuesScreen, newIssueScreen } from "./screens/issues.ts"; |
| 62 | 62 | import { limbsScreen } from "./screens/limbs.ts"; |
| 63 | import { proposalTokensScreen } from "./screens/proposal_tokens.ts"; | |
| 63 | 64 | import { newPullScreen } from "./screens/newpull.ts"; |
| 64 | 65 | import { newForgeScreen } from "./screens/newforge.ts"; |
| 65 | 66 | import { newRepoScreen } from "./screens/newrepo.ts"; |
| @@ -100,6 +101,11 @@ const REPO_VERBS: readonly { | ||
| 100 | 101 | title: "Milestones in a repository", |
| 101 | 102 | open: (f, ctx, repo) => limbsScreen(f, ctx, repo), |
| 102 | 103 | }, |
| 104 | { | |
| 105 | id: "proposal-tokens", | |
| 106 | title: "Proposal tokens of a repository", | |
| 107 | open: proposalTokensScreen, | |
| 108 | }, | |
| 103 | 109 | { id: "new-issue", title: "New issue", open: newIssueScreen }, |
| 104 | 110 | { id: "new-pull", title: "New pull request", open: newPullScreen }, |
| 105 | 111 | { |
src/tui/screens/proposal_tokens.ts added +103
| @@ -0,0 +1,103 @@ | ||
| 1 | /** | |
| 2 | * A repository's proposal tokens in the terminal, as the settings page has | |
| 3 | * them (`actions/proposal_tokens.ts`): by child, `n` mints one (child, origin, | |
| 4 | * and optionally the child's fork), `x` revokes the one under the cursor. The | |
| 5 | * secret is printed once on the status line and gone at the next key. | |
| 6 | */ | |
| 7 | ||
| 8 | import { listProposals, mintProposal, revokeProposal } from "../../actions/proposal_tokens.ts"; | |
| 9 | import { isChildName, parseOrigin } from "../../core/proposal_token.ts"; | |
| 10 | import type { Repo } from "../../core/repos.ts"; | |
| 11 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 12 | import { binding } from "../app/keys.ts"; | |
| 13 | import { style } from "../term/style.ts"; | |
| 14 | import { truncate } from "../term/width.ts"; | |
| 15 | import type { Session } from "../session.ts"; | |
| 16 | import { fill, len, split } from "../ui/layout.ts"; | |
| 17 | import { ListState, drawList, later, promptScreen, type ListRow } from "./common.ts"; | |
| 18 | ||
| 19 | export function proposalTokensScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | |
| 20 | const state = new ListState(); | |
| 21 | let note = ""; | |
| 22 | const read = () => listProposals(f.app, f.user, repo); | |
| 23 | ||
| 24 | const rows = (): ListRow[] => { | |
| 25 | const r = read(); | |
| 26 | return r.ok | |
| 27 | ? r.value.map((p) => ({ | |
| 28 | title: p.child, | |
| 29 | secondary: p.origin, | |
| 30 | meta: `made ${p.createdAt.slice(0, 10)} · ${p.lastUsedAt ? `used ${p.lastUsedAt.slice(0, 10)}` : "never used"}`, | |
| 31 | })) | |
| 32 | : []; | |
| 33 | }; | |
| 34 | ||
| 35 | const mint = (child: string, origin: string, childRepo: string): string | undefined => { | |
| 36 | const made = mintProposal(f.app, f.user, repo, { child, origin, childRepo }); | |
| 37 | if (made.ok) { | |
| 38 | note = `Copy it now, it is never shown again: ${made.value.token}`; | |
| 39 | ctx.invalidate(); | |
| 40 | return undefined; | |
| 41 | } | |
| 42 | return made.error === "invalid_child" | |
| 43 | ? "A child is lowercase words and hyphens." | |
| 44 | : made.error === "invalid_origin" | |
| 45 | ? "An origin is an https address." | |
| 46 | : "Not a fork of this repository, or you cannot write it."; | |
| 47 | }; | |
| 48 | ||
| 49 | const screen: Screen = { | |
| 50 | title: `Proposal tokens · ${repo.ownerName}/${repo.name}`, | |
| 51 | keys: [binding(["j", "k"], "move cursor"), binding(["n"], "mint"), binding(["x"], "revoke")], | |
| 52 | render(area, s) { | |
| 53 | const c = ctx.theme.c; | |
| 54 | const r = read(); | |
| 55 | const [head, list] = split(area, "v", [len(1), fill(1)]); | |
| 56 | const text = | |
| 57 | note !== "" | |
| 58 | ? note | |
| 59 | : r.ok | |
| 60 | ? "A child's token pushes child/<name>/… branches here and opens pulls, nothing else." | |
| 61 | : "Only a writer of this repository has proposal tokens."; | |
| 62 | s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 63 | drawList(s, list!, c, state, rows()); | |
| 64 | }, | |
| 65 | key(e) { | |
| 66 | const r = read(); | |
| 67 | const listed = r.ok ? r.value : []; | |
| 68 | note = ""; | |
| 69 | if (state.key(e, listed.length)) return true; | |
| 70 | if (e.ctrl || e.alt || !r.ok) return false; | |
| 71 | if (e.key === "x") { | |
| 72 | const p = listed[state.index]; | |
| 73 | if (p === undefined) return false; | |
| 74 | note = revokeProposal(f.app, f.user, repo, p.tokenId).ok | |
| 75 | ? `Revoked the token for ${p.child}.` | |
| 76 | : "No such token."; | |
| 77 | state.clamp(listed.length - 1); | |
| 78 | } else if (e.key === "n") { | |
| 79 | const ask = (title: string, label: string, onSubmit: (v: string) => string | undefined | Promise<void>) => | |
| 80 | promptScreen(ctx, screen, { title, label, onSubmit }); | |
| 81 | ctx.push( | |
| 82 | ask("Child", "lowercase words and hyphens", (child) => | |
| 83 | !isChildName(child) | |
| 84 | ? "A child is lowercase words and hyphens." | |
| 85 | : later(ctx, () => | |
| 86 | ask("Origin", "the child's https address", (origin) => | |
| 87 | parseOrigin(origin) === undefined | |
| 88 | ? "An origin is an https address." | |
| 89 | : later(ctx, () => | |
| 90 | ask("Child repository", "owner/name of its fork here, empty for none", (fork) => | |
| 91 | mint(child, origin, fork.trim()), | |
| 92 | ), | |
| 93 | ), | |
| 94 | ), | |
| 95 | ), | |
| 96 | ), | |
| 97 | ); | |
| 98 | } else return false; | |
| 99 | return true; | |
| 100 | }, | |
| 101 | }; | |
| 102 | return screen; | |
| 103 | } |
src/web/pages/account.ts +10 −1
| @@ -29,6 +29,7 @@ import { forgeHost, noreplyAddress } from "../../core/commit_identity.ts"; | ||
| 29 | 29 | import { listKeys } from "../../core/keys.ts"; |
| 30 | 30 | import { endAccountSession } from "../../actions/signins.ts"; |
| 31 | 31 | import { listSessions, type SessionInfo } from "../../core/sessions.ts"; |
| 32 | import { proposalsByToken } from "../../core/proposal_token.ts"; | |
| 32 | 33 | import { listTokens, type TokenScope } from "../../core/tokens.ts"; |
| 33 | 34 | import type { CommitEmail, User } from "../../core/users.ts"; |
| 34 | 35 | import { cookieValue, type Ctx } from "../../http/context.ts"; |
| @@ -450,6 +451,7 @@ export function sessionsCard( | ||
| 450 | 451 | |
| 451 | 452 | function tokensView(ctx: Ctx): Html { |
| 452 | 453 | const tokens = listTokens(ctx.app.db, ctx.auth.user!.id); |
| 454 | const proposals = proposalsByToken(ctx.app.db, ctx.auth.user!.id); | |
| 453 | 455 | const sessions = listSessions( |
| 454 | 456 | ctx.app.db, |
| 455 | 457 | ctx.auth.user!.id, |
| @@ -482,7 +484,14 @@ function tokensView(ctx: Ctx): Html { | ||
| 482 | 484 | ${tokens.map( |
| 483 | 485 | (t) => |
| 484 | 486 | html`<tr> |
| 485 | <td><strong>${t.name}</strong></td> | |
| 487 | <td> | |
| 488 | <strong>${t.name}</strong> | |
| 489 | ${proposals.has(t.id) | |
| 490 | ? html`<div class="muted small"> | |
| 491 | child ${proposals.get(t.id)!.child} · ${proposals.get(t.id)!.origin} | |
| 492 | </div>` | |
| 493 | : null} | |
| 494 | </td> | |
| 486 | 495 | <td>${badge(t.scope)}</td> |
| 487 | 496 | <td class="muted">${time(t.createdAt)}</td> |
| 488 | 497 | <td class="muted"> |
src/web/pages/proposal_tokens.ts added +128
| @@ -0,0 +1,128 @@ | ||
| 1 | /** | |
| 2 | * Proposal tokens on the repository settings page: a form to mint one for a | |
| 3 | * child, and the ones already minted, by child, each with its revoke. The | |
| 4 | * work is `actions/proposal_tokens.ts`; this is the form and the redirect. | |
| 5 | */ | |
| 6 | ||
| 7 | import { listProposals, mintProposal, revokeProposal } from "../../actions/proposal_tokens.ts"; | |
| 8 | import { canAdmin, type Repo } from "../../core/repos.ts"; | |
| 9 | import type { Ctx } from "../../http/context.ts"; | |
| 10 | import { loadRepo, repoBase, repoNotFound } from "../chrome.ts"; | |
| 11 | import { field, readForm } from "../form.ts"; | |
| 12 | import { html, type Html } from "../html.ts"; | |
| 13 | import { icon } from "../icons.ts"; | |
| 14 | import { flashTo } from "../layout.ts"; | |
| 15 | import { btn, card, confirmAction, field as formField, time } from "../ui.ts"; | |
| 16 | ||
| 17 | /** The card for an administrator of `repo`; the page draws it under the gates. */ | |
| 18 | export function proposalTokensCard(ctx: Ctx, repo: Repo): Html { | |
| 19 | const base = repoBase(repo); | |
| 20 | const listed = listProposals(ctx.app, ctx.auth.user, repo); | |
| 21 | const tokens = listed.ok ? listed.value : []; | |
| 22 | return card( | |
| 23 | html`<p class="muted"> | |
| 24 | A child forge proposes upstream with its own token: it can push | |
| 25 | <code>child/<name>/…</code> branches here and open pulls from | |
| 26 | them, and nothing else. The secret is shown once; the token expires in | |
| 27 | 30 days. | |
| 28 | </p> | |
| 29 | ${tokens.length === 0 | |
| 30 | ? html`<p class="muted small">No proposal tokens yet.</p>` | |
| 31 | : html`<div class="table-scroll"> | |
| 32 | <table class="table"> | |
| 33 | <thead> | |
| 34 | <tr><th>Child</th><th>Origin</th><th>Created</th><th>Last used</th><th></th></tr> | |
| 35 | </thead> | |
| 36 | <tbody> | |
| 37 | ${tokens.map( | |
| 38 | (t) => | |
| 39 | html`<tr> | |
| 40 | <td><strong>${t.child}</strong></td> | |
| 41 | <td class="muted">${t.origin}</td> | |
| 42 | <td class="muted">${time(t.createdAt)}</td> | |
| 43 | <td class="muted">${t.lastUsedAt ? time(t.lastUsedAt) : "never"}</td> | |
| 44 | <td> | |
| 45 | ${confirmAction({ | |
| 46 | action: `${base}/settings/proposal-tokens/${t.tokenId}/delete`, | |
| 47 | verb: "Revoke", | |
| 48 | size: "sm", | |
| 49 | })} | |
| 50 | </td> | |
| 51 | </tr>`, | |
| 52 | )} | |
| 53 | </tbody> | |
| 54 | </table> | |
| 55 | </div>`} | |
| 56 | <form method="post" action="${base}/settings/proposal-tokens" class="mt"> | |
| 57 | ${formField({ | |
| 58 | label: "Child", | |
| 59 | name: "child", | |
| 60 | required: true, | |
| 61 | hint: "Lowercase words and hyphens; its branches live under child/<name>/.", | |
| 62 | })} | |
| 63 | ${formField({ | |
| 64 | label: "Origin", | |
| 65 | name: "origin", | |
| 66 | required: true, | |
| 67 | hint: "Where the child lives: an https address.", | |
| 68 | })} | |
| 69 | ${formField({ | |
| 70 | label: "Child repository (optional)", | |
| 71 | name: "childRepo", | |
| 72 | hint: "owner/name of a fork of this repository.", | |
| 73 | })} | |
| 74 | <div class="form-actions">${btn("Mint token", { variant: "primary" })}</div> | |
| 75 | </form>`, | |
| 76 | { head: html`${icon("key")}<h2>Proposal tokens</h2>` }, | |
| 77 | ); | |
| 78 | } | |
| 79 | ||
| 80 | /** The repo for an administrator, and the form for a person at a browser. */ | |
| 81 | async function gate(ctx: Ctx) { | |
| 82 | const repo = loadRepo(ctx); | |
| 83 | if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return repoNotFound(ctx); | |
| 84 | const form = await readForm(ctx, "admin"); | |
| 85 | if (form instanceof Response) return form; | |
| 86 | return { repo, form }; | |
| 87 | } | |
| 88 | ||
| 89 | // POST /:owner/:name/settings/proposal-tokens | |
| 90 | export async function proposalTokenMint(ctx: Ctx): Promise<Response> { | |
| 91 | // Like any token: from a session or the password, never from another token. | |
| 92 | if (ctx.auth.via !== "session" && ctx.auth.via !== "password") | |
| 93 | return new Response("forbidden", { status: 403 }); | |
| 94 | const opened = await gate(ctx); | |
| 95 | if (opened instanceof Response) return opened; | |
| 96 | const { repo, form } = opened; | |
| 97 | const back = `${repoBase(repo)}/settings`; | |
| 98 | const minted = mintProposal(ctx.app, ctx.auth.user, repo, { | |
| 99 | child: field(form, "child").trim(), | |
| 100 | origin: field(form, "origin").trim(), | |
| 101 | childRepo: field(form, "childRepo").trim(), | |
| 102 | }); | |
| 103 | if (!minted.ok) | |
| 104 | return flashTo(ctx, back, { | |
| 105 | tone: "danger", | |
| 106 | message: | |
| 107 | minted.error === "invalid_child" | |
| 108 | ? "A child is lowercase words and hyphens." | |
| 109 | : minted.error === "invalid_origin" | |
| 110 | ? "An origin is an https address." | |
| 111 | : "That child repository is not a fork of this one.", | |
| 112 | }); | |
| 113 | return flashTo(ctx, back, { | |
| 114 | message: "Proposal token created — copy it now, it is never shown again.", | |
| 115 | code: minted.value.token, | |
| 116 | }); | |
| 117 | } | |
| 118 | ||
| 119 | // POST /:owner/:name/settings/proposal-tokens/:id/delete | |
| 120 | export async function proposalTokenRevoke(ctx: Ctx): Promise<Response> { | |
| 121 | const opened = await gate(ctx); | |
| 122 | if (opened instanceof Response) return opened; | |
| 123 | const { repo } = opened; | |
| 124 | const revoked = revokeProposal(ctx.app, ctx.auth.user, repo, ctx.params.id ?? ""); | |
| 125 | return flashTo(ctx, `${repoBase(repo)}/settings`, revoked.ok | |
| 126 | ? { message: "Proposal token revoked." } | |
| 127 | : { tone: "danger", message: "No such proposal token." }); | |
| 128 | } |
src/web/pages/settings.ts +2 −1
| @@ -102,6 +102,7 @@ import { | ||
| 102 | 102 | timeAgo, |
| 103 | 103 | } from "../ui.ts"; |
| 104 | 104 | import { cutWaveFor } from "../../actions/cut_wave.ts"; |
| 105 | import { proposalTokensCard } from "./proposal_tokens.ts"; | |
| 105 | 106 | import { secretsSection } from "./secrets.ts"; |
| 106 | 107 | import { saveGrants } from "./subscriptions.ts"; |
| 107 | 108 | |
| @@ -343,7 +344,7 @@ export async function settingsPage(ctx: Ctx): Promise<Response> { | ||
| 343 | 344 | repo, |
| 344 | 345 | "general", |
| 345 | 346 | "Settings", |
| 346 | html`${lead}<div class="mt">${body}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${secrets | |
| 347 | html`${lead}<div class="mt">${body}</div><div class="mt">${wave}</div><div class="mt">${archive}</div><div class="mt">${proposalTokensCard(ctx, repo)}</div>${secrets | |
| 347 | 348 | ? html`<div class="mt">${secrets}</div>` |
| 348 | 349 | : null}`, |
| 349 | 350 | ); |
test/proposal-token-doors.test.ts added +186
| @@ -0,0 +1,186 @@ | ||
| 1 | /** | |
| 2 | * Proposal tokens are minted, listed by child and revoked from the settings | |
| 3 | * page, the terminal and MCP, as well as the API — all through one action. | |
| 4 | */ | |
| 5 | ||
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { createApp, type App } from "../src/app.ts"; | |
| 11 | import { listProposals, mintProposal, revokeProposal } from "../src/actions/proposal_tokens.ts"; | |
| 12 | import { getRepo, type Repo } from "../src/core/repos.ts"; | |
| 13 | import { createToken } from "../src/core/tokens.ts"; | |
| 14 | import { getUserByName, type User } from "../src/core/users.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 17 | import { proposalTokensScreen } from "../src/tui/screens/proposal_tokens.ts"; | |
| 18 | import { local } from "../src/tui/screens/where.ts"; | |
| 19 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 20 | import { quietLogs } from "./helpers/globals.ts"; | |
| 21 | import { settleApp } from "./helpers/tui.ts"; | |
| 22 | ||
| 23 | quietLogs(); | |
| 24 | ||
| 25 | const ORIGIN = "https://kid.example.com/"; | |
| 26 | ||
| 27 | describe("proposal tokens from every door", () => { | |
| 28 | let dataDir: string; | |
| 29 | let app: App; | |
| 30 | let servers: Servers; | |
| 31 | let base: string; | |
| 32 | let cookie = ""; | |
| 33 | let ada: User; | |
| 34 | let repo: Repo; | |
| 35 | let bearer = ""; | |
| 36 | let nextId = 1; | |
| 37 | ||
| 38 | const form = (fields: Record<string, string>) => new URLSearchParams(fields); | |
| 39 | const post = (path: string, fields: Record<string, string>, as = cookie) => | |
| 40 | fetch(`${base}${path}`, { | |
| 41 | method: "POST", | |
| 42 | headers: { cookie: as, origin: base }, | |
| 43 | body: form(fields), | |
| 44 | redirect: "manual", | |
| 45 | }); | |
| 46 | const mcp = async (name: string, args: Record<string, unknown>, token = bearer) => { | |
| 47 | const res = await fetch(`${base}/mcp`, { | |
| 48 | method: "POST", | |
| 49 | headers: { | |
| 50 | "content-type": "application/json", | |
| 51 | accept: "application/json, text/event-stream", | |
| 52 | authorization: `Bearer ${token}`, | |
| 53 | }, | |
| 54 | body: JSON.stringify({ | |
| 55 | jsonrpc: "2.0", | |
| 56 | id: nextId++, | |
| 57 | method: "tools/call", | |
| 58 | params: { name, arguments: args }, | |
| 59 | }), | |
| 60 | }); | |
| 61 | const body = (await res.json()) as any; | |
| 62 | const text: string = body.result.content[0].text; | |
| 63 | return body.result.isError === true ? { error: text } : { value: JSON.parse(text) }; | |
| 64 | }; | |
| 65 | const tokens = () => { | |
| 66 | const r = listProposals(app, ada, repo); | |
| 67 | if (!r.ok) throw new Error("not listed"); | |
| 68 | return r.value; | |
| 69 | }; | |
| 70 | ||
| 71 | beforeAll(async () => { | |
| 72 | dataDir = await mkdtemp(join(tmpdir(), "forge-proposal-doors-")); | |
| 73 | app = createApp({ dataDir, port: 0 }); | |
| 74 | servers = await serve(app); | |
| 75 | base = servers.url; | |
| 76 | const signed = await fetch(`${base}/signup`, { | |
| 77 | method: "POST", | |
| 78 | body: form({ username: "ada", email: "[email protected]", password: "doors-password" }), | |
| 79 | redirect: "manual", | |
| 80 | }); | |
| 81 | cookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 82 | await post("/new", { name: "lib", visibility: "public", description: "d" }); | |
| 83 | ada = getUserByName(app.db, "ada")!; | |
| 84 | repo = getRepo(app.db, "ada", "lib")!; | |
| 85 | bearer = createToken(app.db, ada.id, "mcp", "rw").token; | |
| 86 | }); | |
| 87 | ||
| 88 | afterAll(async () => { | |
| 89 | servers.stop(); | |
| 90 | app.close(); | |
| 91 | await rm(dataDir, { recursive: true, force: true }); | |
| 92 | }); | |
| 93 | ||
| 94 | test("the settings form mints, the list shows the child, revoke removes it", async () => { | |
| 95 | const bad = await post("/ada/lib/settings/proposal-tokens", { child: "Bad Name", origin: ORIGIN }); | |
| 96 | expect(bad.status).toBe(303); | |
| 97 | expect(tokens()).toHaveLength(0); | |
| 98 | ||
| 99 | const made = await post("/ada/lib/settings/proposal-tokens", { child: "web-kid", origin: ORIGIN }); | |
| 100 | expect(made.status).toBe(303); | |
| 101 | expect(tokens().map((t) => t.child)).toEqual(["web-kid"]); | |
| 102 | ||
| 103 | const page = await (await fetch(`${base}/ada/lib/settings`, { headers: { cookie } })).text(); | |
| 104 | expect(page).toContain("Proposal tokens"); | |
| 105 | expect(page).toContain("web-kid"); | |
| 106 | const id = tokens()[0]!.tokenId; | |
| 107 | expect(page).toContain(encodeURIComponent(`/ada/lib/settings/proposal-tokens/${id}/delete`)); | |
| 108 | ||
| 109 | // The account's token list says which child a token is for. | |
| 110 | const account = await (await fetch(`${base}/settings/tokens`, { headers: { cookie } })).text(); | |
| 111 | expect(account).toContain("child web-kid"); | |
| 112 | ||
| 113 | expect((await post(`/ada/lib/settings/proposal-tokens/${id}/delete`, {})).status).toBe(303); | |
| 114 | expect(tokens()).toHaveLength(0); | |
| 115 | }); | |
| 116 | ||
| 117 | test("a mutation from another origin or without a session mints nothing", async () => { | |
| 118 | const foreign = await fetch(`${base}/ada/lib/settings/proposal-tokens`, { | |
| 119 | method: "POST", | |
| 120 | headers: { cookie, origin: "https://evil.example" }, | |
| 121 | body: form({ child: "evil", origin: ORIGIN }), | |
| 122 | redirect: "manual", | |
| 123 | }); | |
| 124 | expect(foreign.status).toBeGreaterThanOrEqual(400); | |
| 125 | await post("/ada/lib/settings/proposal-tokens", { child: "anon", origin: ORIGIN }, ""); | |
| 126 | expect(tokens()).toHaveLength(0); | |
| 127 | }); | |
| 128 | ||
| 129 | test("MCP mints, lists and revokes; a read-only token and a stranger cannot", async () => { | |
| 130 | const made = await mcp("proposal_token_mint", { repo: "ada/lib", child: "mcp-kid", origin: ORIGIN }); | |
| 131 | expect(made.value.token).toMatch(/^forge_/); | |
| 132 | expect((await mcp("proposal_token_mint", { repo: "ada/lib", child: "BAD", origin: ORIGIN })).error).toContain("child"); | |
| 133 | expect((await mcp("proposal_token_mint", { repo: "ada/lib", child: "x", origin: "http://x" })).error).toContain("origin"); | |
| 134 | ||
| 135 | const listed = await mcp("proposal_tokens", { repo: "ada/lib" }); | |
| 136 | expect(listed.value.tokens.map((t: any) => t.child)).toEqual(["mcp-kid"]); | |
| 137 | expect(JSON.stringify(listed.value)).not.toContain("forge_"); | |
| 138 | ||
| 139 | const ro = createToken(app.db, ada.id, "ro", "ro").token; | |
| 140 | expect((await mcp("proposal_token_mint", { repo: "ada/lib", child: "ro-kid", origin: ORIGIN }, ro)).error).toBeDefined(); | |
| 141 | expect(tokens()).toHaveLength(1); | |
| 142 | ||
| 143 | const id = listed.value.tokens[0].tokenId; | |
| 144 | expect((await mcp("proposal_token_revoke", { repo: "ada/lib", id: "nope" })).error).toBeDefined(); | |
| 145 | expect((await mcp("proposal_token_revoke", { repo: "ada/lib", id })).value).toEqual({ revoked: true }); | |
| 146 | expect(tokens()).toHaveLength(0); | |
| 147 | }); | |
| 148 | ||
| 149 | test("a reader is refused at every door, and an ordinary token is not revoked through a repository", async () => { | |
| 150 | await fetch(`${base}/signup`, { | |
| 151 | method: "POST", | |
| 152 | body: form({ username: "bob", email: "[email protected]", password: "doors-password" }), | |
| 153 | redirect: "manual", | |
| 154 | }); | |
| 155 | const bob = getUserByName(app.db, "bob")!; | |
| 156 | expect(mintProposal(app, bob, repo, { child: "x", origin: ORIGIN }).ok).toBe(false); | |
| 157 | expect(listProposals(app, bob, repo).ok).toBe(false); | |
| 158 | const theirs = createToken(app.db, bob.id, "t", "rw").token; | |
| 159 | expect((await mcp("proposal_token_mint", { repo: "ada/lib", child: "x", origin: ORIGIN }, theirs)).error).toBeDefined(); | |
| 160 | const plain = createToken(app.db, ada.id, "plain", "rw"); | |
| 161 | expect(revokeProposal(app, ada, repo, plain.id).ok).toBe(false); | |
| 162 | expect(app.db.query("SELECT 1 FROM token WHERE id = ?1").get(plain.id)).not.toBeNull(); | |
| 163 | }); | |
| 164 | ||
| 165 | test("the terminal lists by child and revokes with x", async () => { | |
| 166 | mintProposal(app, ada, repo, { child: "tui-kid", origin: ORIGIN }); | |
| 167 | const terminal = headlessTerminal(160, 30); | |
| 168 | const { app: tui, session } = createForgeApp( | |
| 169 | app, | |
| 170 | { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:a", user: ada }, | |
| 171 | { terminal, exitHooks: false }, | |
| 172 | ); | |
| 173 | tui.start(); | |
| 174 | try { | |
| 175 | tui.ctx.push(proposalTokensScreen(session, tui.ctx, repo)); | |
| 176 | await settleApp(tui); | |
| 177 | expect(tui.screen.toText()).toContain("tui-kid"); | |
| 178 | expect(tui.screen.toText()).toContain(ORIGIN); | |
| 179 | tui.dispatch({ type: "key", key: "x", ctrl: false, alt: false, shift: false }); | |
| 180 | await settleApp(tui); | |
| 181 | expect(tokens()).toHaveLength(0); | |
| 182 | } finally { | |
| 183 | tui.stop(); | |
| 184 | } | |
| 185 | }); | |
| 186 | }); |
new above
offline