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 #2225

Parked opened this
Closed without merging

scout/forge:scout/2187-propose-upstream-across-forges-part-2-mi → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +280 −2
README.md +4
@@ -109,6 +109,10 @@ Minting, listing and revoking go through one action
109109 repository may; anyone else is told "no such resource here, or it is not
110110 visible to you", as the API says it. The secret is shown once, on minting.
111111
112 - **Page**: Settings → General → Proposal tokens lists yours by child with a
113 Revoke on each, and mints from a form (`child`, `origin`, optional child
114 repository); the secret is shown once. The account's token list names the
115 child and origin beside a proposal token.
112116 - **MCP**: the `proposal_tokens` tool with `repo` and a `verb`: `mint`
113117 (`child`, `origin`, optionally `childRepo`), `list` (the ones you minted for
114118 the repository) or `revoke` (`id`).
src/core/proposal_token.ts +14
@@ -179,3 +179,17 @@ export function deleteProposalToken(
179179 .run(tokenId, userId, repoId).changes > 0
180180 );
181181 }
182
183 /** The proposal behind each of a person's tokens that has one, by token id. */
184 export function proposalsByToken(
185 db: Database,
186 userId: string,
187 ): Map<string, { child: string; origin: string }> {
188 const rows = db
189 .query<{ token_id: string; child: string; origin: string }, [string]>(
190 `SELECT p.token_id, p.child, p.origin FROM proposal_token p
191 JOIN token t ON t.id = p.token_id WHERE t.user_id = ?1`,
192 )
193 .all(userId);
194 return new Map(rows.map((r) => [r.token_id, { child: r.child, origin: r.origin }]));
195 }
src/http/server.ts +7
@@ -258,6 +258,7 @@ import { appNowFragment } from "../web/studio/now.ts";
258258 import { appStateFragment } from "../web/studio/previews.ts";
259259 import { changesList, tellsList } from "../web/studio/lists.ts";
260260 import { dependencySubmit } from "../web/pages/thread.ts";
261 import { proposalTokenMint, proposalTokenRevoke } from "../web/pages/proposal_tokens.ts";
261262 import {
262263 assigneeSubmit,
263264 labelsSubmit,
@@ -1230,6 +1231,12 @@ export function buildRouter(): Router<Handler> {
12301231 router.add("POST", "/:owner/:name/settings", settingsUpdate);
12311232 router.add("POST", "/:owner/:name/settings/wave", waveCut);
12321233 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 );
12331240 router.add("GET", "/:owner/:name/settings/app", appSettingsPage);
12341241 router.add("POST", "/:owner/:name/settings/app", appSettingsUpdate);
12351242 router.add("POST", "/:owner/:name/settings/app/disable", appDisable);
src/web/pages/account.ts +10 −1
@@ -29,6 +29,7 @@ import { forgeHost, noreplyAddress } from "../../core/commit_identity.ts";
2929 import { listKeys } from "../../core/keys.ts";
3030 import { endAccountSession } from "../../actions/signins.ts";
3131 import { listSessions, type SessionInfo } from "../../core/sessions.ts";
32 import { proposalsByToken } from "../../core/proposal_token.ts";
3233 import { listTokens, type TokenScope } from "../../core/tokens.ts";
3334 import type { CommitEmail, User } from "../../core/users.ts";
3435 import { cookieValue, type Ctx } from "../../http/context.ts";
@@ -450,6 +451,7 @@ export function sessionsCard(
450451
451452 function tokensView(ctx: Ctx): Html {
452453 const tokens = listTokens(ctx.app.db, ctx.auth.user!.id);
454 const proposals = proposalsByToken(ctx.app.db, ctx.auth.user!.id);
453455 const sessions = listSessions(
454456 ctx.app.db,
455457 ctx.auth.user!.id,
@@ -482,7 +484,14 @@ function tokensView(ctx: Ctx): Html {
482484 ${tokens.map(
483485 (t) =>
484486 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>
486495 <td>${badge(t.scope)}</td>
487496 <td class="muted">${time(t.createdAt)}</td>
488497 <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/&lt;name&gt;/…</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.id}/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"),
100 origin: field(form, "origin"),
101 childRepo: field(form, "childRepo"),
102 });
103 if (!minted.ok)
104 return flashTo(ctx, back, {
105 tone: "danger",
106 message:
107 minted.error.code === "invalid_child"
108 ? "A child is lowercase words and hyphens."
109 : minted.error.code === "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 {
102102 timeAgo,
103103 } from "../ui.ts";
104104 import { cutWaveFor } from "../../actions/cut_wave.ts";
105 import { proposalTokensCard } from "./proposal_tokens.ts";
105106 import { secretsSection } from "./secrets.ts";
106107 import { saveGrants } from "./subscriptions.ts";
107108
@@ -343,7 +344,7 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
343344 repo,
344345 "general",
345346 "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
347348 ? html`<div class="mt">${secrets}</div>`
348349 : null}`,
349350 );
test/proposal-token-page.test.ts added +115
@@ -0,0 +1,115 @@
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 { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 const ORIGIN = "https://kid.example.com/";
21
22 describe("proposal tokens on the settings page", () => {
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let base: string;
27 let cookie = "";
28 let ada: User;
29 let repo: Repo;
30
31 const form = (fields: Record<string, string>) => new URLSearchParams(fields);
32 const post = (path: string, fields: Record<string, string>, as = cookie) =>
33 fetch(`${base}${path}`, {
34 method: "POST",
35 headers: { cookie: as, origin: base },
36 body: form(fields),
37 redirect: "manual",
38 });
39 const tokens = () => {
40 const r = listProposals(app, ada, repo);
41 if (!r.ok) throw new Error("not listed");
42 return r.value;
43 };
44
45 beforeAll(async () => {
46 dataDir = await mkdtemp(join(tmpdir(), "forge-proposal-doors-"));
47 app = createApp({ dataDir, port: 0 });
48 servers = await serve(app);
49 base = servers.url;
50 const signed = await fetch(`${base}/signup`, {
51 method: "POST",
52 body: form({ username: "ada", email: "[email protected]", password: "doors-password" }),
53 redirect: "manual",
54 });
55 cookie = (signed.headers.get("set-cookie") ?? "").split(";")[0]!;
56 await post("/new", { name: "lib", visibility: "public", description: "d" });
57 ada = getUserByName(app.db, "ada")!;
58 repo = getRepo(app.db, "ada", "lib")!;
59 });
60
61 afterAll(async () => {
62 servers.stop();
63 app.close();
64 await rm(dataDir, { recursive: true, force: true });
65 });
66
67 test("the settings form mints, the list shows the child, revoke removes it", async () => {
68 const bad = await post("/ada/lib/settings/proposal-tokens", { child: "Bad Name", origin: ORIGIN });
69 expect(bad.status).toBe(303);
70 expect(tokens()).toHaveLength(0);
71
72 const made = await post("/ada/lib/settings/proposal-tokens", { child: "web-kid", origin: ORIGIN });
73 expect(made.status).toBe(303);
74 expect(tokens().map((t) => t.child)).toEqual(["web-kid"]);
75
76 const page = await (await fetch(`${base}/ada/lib/settings`, { headers: { cookie } })).text();
77 expect(page).toContain("Proposal tokens");
78 expect(page).toContain("web-kid");
79 const id = tokens()[0]!.id;
80 expect(page).toContain(encodeURIComponent(`/ada/lib/settings/proposal-tokens/${id}/delete`));
81
82 // The account's token list says which child a token is for.
83 const account = await (await fetch(`${base}/settings/tokens`, { headers: { cookie } })).text();
84 expect(account).toContain("child web-kid");
85
86 expect((await post(`/ada/lib/settings/proposal-tokens/${id}/delete`, {})).status).toBe(303);
87 expect(tokens()).toHaveLength(0);
88 });
89
90 test("a mutation from another origin or without a session mints nothing", async () => {
91 const foreign = await fetch(`${base}/ada/lib/settings/proposal-tokens`, {
92 method: "POST",
93 headers: { cookie, origin: "https://evil.example" },
94 body: form({ child: "evil", origin: ORIGIN }),
95 redirect: "manual",
96 });
97 expect(foreign.status).toBeGreaterThanOrEqual(400);
98 await post("/ada/lib/settings/proposal-tokens", { child: "anon", origin: ORIGIN }, "");
99 expect(tokens()).toHaveLength(0);
100 });
101
102 test("a reader is refused, and an ordinary token is not revoked through a repository", async () => {
103 await fetch(`${base}/signup`, {
104 method: "POST",
105 body: form({ username: "bob", email: "[email protected]", password: "doors-password" }),
106 redirect: "manual",
107 });
108 const bob = getUserByName(app.db, "bob")!;
109 expect(mintProposal(app, bob, repo, { child: "x", origin: ORIGIN }).ok).toBe(false);
110 expect(listProposals(app, bob, repo).ok).toBe(false);
111 const plain = createToken(app.db, ada.id, "plain", "rw");
112 expect(revokeProposal(app, ada, repo, plain.id).ok).toBe(false);
113 expect(app.db.query("SELECT 1 FROM token WHERE id = ?1").get(plain.id)).not.toBeNull();
114 });
115 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs