Public: anyone can read this; the crew can change it.

On the home, an admin selects apps and archives them in one tap, and the answer offers Undo #2521

Parked opened this
Closed without merging

scout/forge:scout/2512-on-the-home-an-admin-selects-apps-and-ar → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +280 −3
src/http/server.ts +4
@@ -248,6 +248,7 @@ import {
248248 asksMute,
249249 asksPage,
250250 } from "../web/studio/asks_page.ts";
251 import { homeArchive, homeArchived, homeArchiveUndo } from "../web/studio/home_archive.ts";
251252 import { liveFeedFragment } from "../web/studio/feed.ts";
252253 import { serviceWorker } from "../web/sw.ts";
253254 import { explorePage } from "../web/studio/explore.ts";
@@ -648,6 +649,9 @@ export function buildRouter(): Router<Handler> {
648649 // Apps and people ranked by real numbers, narrowed in one line (#607).
649650 router.add("GET", "/explore", explorePage);
650651 router.add("POST", "/front", frontUpdate);
652 router.add("POST", "/home/archive", homeArchive);
653 router.add("GET", "/home/archived/:op", homeArchived);
654 router.add("POST", "/home/archived/:op/undo", homeArchiveUndo);
651655 router.add("GET", "/signin", signinPage);
652656 router.add("POST", "/signin", signinSubmit);
653657 router.add("GET", "/signin/parent", parentStart);
src/web/studio/feed_style.ts +3
@@ -27,6 +27,9 @@ export const feedCss = /* css */ `
2727 /* Your apps: a narrow column on a desk, a tab away on a phone. */
2828 .home-tabs { display: none; margin-bottom: 12px; }
2929 .home-app { gap: 8px; }
30 .home-pick { display: none; }
31 #apps-select:checked ~ * .home-pick { display: inline-flex; }
32 #apps-select:focus-visible ~ * .home-apps-verbs label { outline: 2px solid var(--accent, currentColor); }
3033 .home-apps-verbs { flex-wrap: wrap; padding: 10px 14px; }
3134 @media (max-width: 899px) {
3235 .home-tabs { display: inline-flex; }
src/web/studio/home.ts +30 −3
@@ -83,13 +83,23 @@ function yourApps(ctx: Ctx, user: User): Html {
8383 ? undefined
8484 : runtime.status(record).find((env) => env.env === "production")?.state;
8585 return html`<li class="row home-app">
86 ${when(
87 user.isAdmin,
88 () =>
89 html`<input
90 class="home-pick"
91 type="checkbox"
92 name="repo"
93 value="${repo.id}"
94 aria-label="Select ${repo.name}"
95 />`,
96 )}
8697 <a class="truncate" href="${repoBase(repo)}">${repo.ownerName}/${repo.name}</a>
8798 <span class="spacer"></span>
8899 ${state === undefined ? null : envStateBadge(state)}
89100 </li>`;
90101 });
91 return card(
92 html`${rows.length === 0
102 const list = html`${rows.length === 0
93103 ? html`<p class="muted small">No apps yet.</p>`
94104 : html`<ul class="list">
95105 ${rows}
@@ -108,7 +118,24 @@ function yourApps(ctx: Ctx, user: User): Html {
108118 ${when(user.isAdmin, () =>
109119 btn("Front page", { href: "/front", size: "sm", icon: "globe" }),
110120 )}
111 </div>`,
121 ${when(
122 user.isAdmin && rows.length > 0,
123 () => html`<label class="btn btn-sm" for="apps-select">Select</label>
124 <span class="home-pick">${btn("Archive", { size: "sm" })}</span>`,
125 )}
126 </div>`;
127 return card(
128 // An admin's list is a form: ticks cost no space until Select shows them.
129 user.isAdmin && rows.length > 0
130 ? html`<form method="post" action="/home/archive">
131 <input
132 class="sr-only"
133 type="checkbox"
134 id="apps-select"
135 aria-label="Select apps"
136 />${list}
137 </form>`
138 : list,
112139 {
113140 head: html`${icon("rocket")}
114141 <h2>Your apps</h2>`,
src/web/studio/home_archive.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * Archiving apps from the home: an admin ticks apps in the rail and archives
3 * them in one step. It is the fleet's own `archive` operation over the ticked
4 * repositories (`actions/fleet.ts`) — nothing new is written here — and the
5 * page that answers lists what was archived with the operation's undo.
6 */
7
8 import { applyFleetIds, getFleetOp, undoFleetOp } from "../../actions/fleet.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { signInFirst } from "../chrome.ts";
11 import { readForm } from "../form.ts";
12 import { html } from "../html.ts";
13 import { page, redirect } from "../layout.ts";
14 import { btn } from "../ui.ts";
15 import { MAX_ROWS } from "../../fleet/selection.ts";
16
17 /** The ticked repository ids, once each, as long as they are plausible ids. */
18 function picked(form: Awaited<ReturnType<typeof readForm>>): string[] {
19 if (form instanceof Response) return [];
20 const ids = form
21 .getAll("repo")
22 .filter((v): v is string => typeof v === "string" && /^[\w-]{1,64}$/.test(v));
23 return [...new Set(ids)];
24 }
25
26 // POST /home/archive — archive the ticked apps, a site admin's.
27 export async function homeArchive(ctx: Ctx): Promise<Response> {
28 if (!ctx.auth.user) return signInFirst(ctx);
29 const form = await readForm(ctx, "admin");
30 if (form instanceof Response) return form;
31 if (!ctx.auth.user.isAdmin) return new Response("forbidden", { status: 403 });
32 const ids = picked(form);
33 if (ids.length === 0 || ids.length > MAX_ROWS)
34 return redirect("/", {
35 url: ctx.url,
36 flash: { tone: "danger", message: "Tick the apps to archive first." },
37 });
38 const op = await applyFleetIds(
39 ctx.app,
40 ctx.auth.user,
41 "repo",
42 ids,
43 `home: ${ids.length} selected`,
44 { verb: "archive", value: true },
45 );
46 if (!op.ok)
47 return redirect("/", {
48 url: ctx.url,
49 flash: { tone: "danger", message: op.error.message },
50 });
51 return redirect(`/home/archived/${op.value.id}`);
52 }
53
54 // GET /home/archived/:op — what was archived, and the undo.
55 export function homeArchived(ctx: Ctx): Response {
56 if (!ctx.auth.user) return signInFirst(ctx);
57 const found = getFleetOp(ctx.app, ctx.auth.user, ctx.params.op ?? "");
58 if (!found.ok || found.value.verb !== "archive")
59 return new Response("not found", { status: 404 });
60 const op = found.value;
61 const wasUndo = op.undoOf !== null;
62 const rows = op.rows.filter((r) => r.outcome === "ok");
63 const left = op.rows.filter((r) => r.outcome !== "ok");
64 const canUndo = op.reversible && op.undoneBy === null && !wasUndo;
65 const body = html`<h1>${wasUndo ? "Brought back" : "Archived"}</h1>
66 <p id="home-archived" role="status">
67 ${rows.length} app${rows.length === 1 ? "" : "s"}
68 ${wasUndo ? "back on the home" : "archived"}${left.length === 0
69 ? ""
70 : `, ${left.length} left as they were`}.
71 </p>
72 <ul class="list">
73 ${rows.map((r) => html`<li class="row">${r.label}</li>`)}
74 </ul>
75 ${left.length === 0
76 ? null
77 : html`<ul class="list muted">
78 ${left.map((r) => html`<li class="row">${r.label}: ${r.reason}</li>`)}
79 </ul>`}
80 <div class="bar mt">
81 ${canUndo
82 ? html`<form method="post" action="/home/archived/${op.id}/undo">
83 ${btn("Undo", { variant: "primary" })}
84 </form>`
85 : null}
86 ${btn("Home", { href: "/" })}
87 </div>
88 ${canUndo ? html`<p class="small muted">Undo is kept for a day.</p>` : null}`;
89 return page({ ctx, title: wasUndo ? "Brought back" : "Archived", body });
90 }
91
92 // POST /home/archived/:op/undo — the operation's own undo.
93 export async function homeArchiveUndo(ctx: Ctx): Promise<Response> {
94 if (!ctx.auth.user) return signInFirst(ctx);
95 const form = await readForm(ctx, "admin");
96 if (form instanceof Response) return form;
97 const undone = await undoFleetOp(ctx.app, ctx.auth.user, ctx.params.op ?? "");
98 if (!undone.ok && undone.error.code === "not_found")
99 return new Response("not found", { status: 404 });
100 if (!undone.ok)
101 return redirect("/", {
102 url: ctx.url,
103 flash: { tone: "danger", message: undone.error.message },
104 });
105 return redirect(`/home/archived/${undone.value.id}`);
106 }
test/home-archive.test.ts added +137
@@ -0,0 +1,137 @@
1 /**
2 * Archiving from the home: an admin ticks apps and archives them in one
3 * step; the answer lists them and offers the fleet's undo.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp as insertApp } from "../src/core/apps.ts";
12 import type { Repo } from "../src/core/repos.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { promote } from "./helpers/members.ts";
17
18 describe("home archive", () => {
19 let dataDir: string;
20 let app: App;
21 let servers: Servers;
22 let root: User;
23 let rootCookie: string;
24 let bobCookie: string;
25 let repos: Repo[];
26
27 const get = (path: string, cookie: string) =>
28 fetch(`${servers.url}${path}`, {
29 headers: { cookie: `${cookie}; forge_mode=studio` },
30 redirect: "manual",
31 });
32 const post = (path: string, cookie: string, body: string, origin = servers.url) =>
33 fetch(`${servers.url}${path}`, {
34 method: "POST",
35 headers: {
36 cookie: `${cookie}; forge_mode=studio`,
37 origin,
38 "content-type": "application/x-www-form-urlencoded",
39 },
40 body,
41 redirect: "manual",
42 });
43
44 beforeAll(async () => {
45 dataDir = await mkdtemp(join(tmpdir(), "forge-home-archive-"));
46 app = createApp({ dataDir, port: 0 });
47 servers = await serve(app);
48 const mk = async (username: string, first = false) => {
49 const r = await createUser(app.db, {
50 origin: "seed",
51 trusted: true,
52 username,
53 email: `${username}@forge.local`,
54 password: "a-good-passphrase",
55 adminIfFirst: first,
56 });
57 if (!r.ok) throw new Error(r.error);
58 promote(app.db, r.value);
59 return r.value;
60 };
61 root = await mk("keeper", true);
62 const bob = await mk("bob");
63 rootCookie = `forge_session=${createSession(app.db, root.id).token}`;
64 bobCookie = `forge_session=${createSession(app.db, bob.id).token}`;
65 repos = [];
66 for (const name of ["alpha", "beta", "gamma"]) {
67 const made = await createRepo(app, root, { name, visibility: "public" });
68 if (!made.ok) throw new Error(String(made.error));
69 insertApp(app.db, { repoId: made.value.id, slug: name, access: "public" });
70 repos.push(made.value);
71 }
72 const mine = await createRepo(app, bob, { name: "mine", visibility: "public" });
73 if (!mine.ok) throw new Error(String(mine.error));
74 }, 30_000);
75
76 afterAll(async () => {
77 servers.stop();
78 app.close();
79 await rm(dataDir, { recursive: true, force: true });
80 });
81
82 const body = (...ids: string[]) => ids.map((id) => `repo=${id}`).join("&");
83 const home = async (cookie: string) => (await get("/live/apps", cookie)).text();
84 const full = async (cookie: string) => (await get("/", cookie)).text();
85
86 test("an admin archives two, the answer lists them, Undo brings them back", async () => {
87 const before = await full(rootCookie);
88 expect(before).toContain('name="repo"');
89 expect(before).toContain("keeper/alpha");
90
91 const res = await post("/home/archive", rootCookie, body(repos[0]!.id, repos[1]!.id));
92 expect(res.status).toBe(303);
93 const receipt = res.headers.get("location")!;
94 expect(receipt).toStartWith("/home/archived/");
95
96 const after = await home(rootCookie);
97 expect(after).not.toContain("keeper/alpha");
98 expect(after).not.toContain("keeper/beta");
99 expect(after).toContain("keeper/gamma");
100
101 const answer = await (await get(receipt, rootCookie)).text();
102 expect(answer).toContain("keeper/alpha");
103 expect(answer).toContain("keeper/beta");
104 expect(answer.replace(/\s+/g, " ")).toContain("2 apps archived");
105 expect(answer).toContain(`action="${receipt}/undo"`);
106
107 const undone = await post(`${receipt}/undo`, rootCookie, "");
108 expect(undone.status).toBe(303);
109 const back = await home(rootCookie);
110 expect(back).toContain("keeper/alpha");
111 expect(back).toContain("keeper/beta");
112
113 const twice = await post(`${receipt}/undo`, rootCookie, "");
114 expect(twice.status).toBe(303);
115 expect(twice.headers.get("location")).toBe("/");
116 });
117
118 test("a cross-origin post is refused and archives nothing", async () => {
119 const res = await post(
120 "/home/archive",
121 rootCookie,
122 body(repos[2]!.id),
123 "https://evil.example",
124 );
125 expect(res.status).toBe(403);
126 expect(await home(rootCookie)).toContain("keeper/gamma");
127 });
128
129 test("a non-admin sees no checkboxes and cannot post", async () => {
130 const page = await full(bobCookie);
131 expect(page).not.toContain('name="repo"');
132 expect(page).not.toContain("apps-select");
133 const res = await post("/home/archive", bobCookie, body(repos[2]!.id));
134 expect(res.status).toBe(403);
135 expect(await home(rootCookie)).toContain("keeper/gamma");
136 });
137 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs