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

The accounts page offers "remove the organization too" behind a confirm page that lists everything that will go #1553

Closed opened this
Closed without merging

scout/forge:scout/1488-the-accounts-page-offers-remove-the-orga → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +189 −3
src/http/server.ts +4
@@ -16,6 +16,8 @@ import {
1616 import {
1717 accountAct,
1818 accountsPage,
19 retireAct,
20 retirePage,
1921 personSignInsPage,
2022 signInAct,
2123 } from "../web/pages/accounts.ts";
@@ -691,6 +693,8 @@ export function buildRouter(): Router<Handler> {
691693 accountAct("unsuspend"),
692694 );
693695 router.add("POST", "/settings/accounts/:username/remove", accountAct("remove"));
696 router.add("GET", "/settings/accounts/:username/retire", retirePage);
697 router.add("POST", "/settings/accounts/:username/retire", retireAct);
694698 router.add("POST", "/settings/accounts/:username/verify", accountAct("verify"));
695699 router.add("GET", "/settings/crew", crewPage);
696700 router.add("POST", "/settings/crew", agentCreate);
src/web/pages/accounts.ts +129 −3
@@ -8,6 +8,8 @@
88 import {
99 listAccounts,
1010 removeAccount,
11 retireAndRemoveAccount,
12 retirementPlan,
1113 suspendAccount,
1214 unsuspendAccount,
1315 verifyAccount,
@@ -225,6 +227,124 @@ function confirmSuspend(username: string, orgs: readonly string[]): Html {
225227 );
226228 }
227229
230 /** The refusal to remove a last owner, with the two ways forward. */
231 function refuseRemove(username: string, orgs: readonly string[]): Html {
232 const at = `/settings/accounts/${encodeURIComponent(username)}`;
233 return card(
234 html`<p>
235 <strong>${username}</strong> is the only person owning
236 ${orgs.join(", ")}. Make someone else an owner first, or remove the
237 organization too. Nothing was changed.
238 </p>
239 <div class="form-actions">
240 ${orgs[0] === undefined
241 ? null
242 : btn("Add an owner first", { href: ownersTeam(orgs[0]), size: "sm" })}
243 ${btn("Remove the organization too", {
244 href: `${at}/retire`,
245 size: "sm",
246 variant: "danger",
247 })}
248 </div>`,
249 { tone: "danger" },
250 );
251 }
252
253 // GET /settings/accounts/:username/retire — everything that would go; reads only
254 export function retirePage(ctx: Ctx): Response {
255 if (!ctx.auth.user) return signInFirst(ctx);
256 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
257 const username = ctx.params.username ?? "";
258 const plan = retirementPlan(ctx.app, ctx.auth.user, username);
259 if (!plan.ok) return notFoundPage(ctx);
260 if (plan.value.length === 0)
261 return flashTo(ctx, "/settings/accounts", {
262 message: `${username} owns no organization alone; nothing to retire.`,
263 });
264 const at = `/settings/accounts/${encodeURIComponent(username)}`;
265 return shell(
266 ctx,
267 card(
268 html`<ul class="rows">
269 ${plan.value.map(
270 (o) => html`<li class="row">
271 <div class="row-main">
272 <strong>${o.org}</strong> ${badge("organization")}
273 <div class="row-meta">
274 ${o.repos.length === 0
275 ? "no repositories"
276 : html`repositories:
277 ${o.repos.map(
278 (r, i) =>
279 html`${i > 0 ? ", " : ""}${r.name}${r.app === null
280 ? null
281 : html` (app ${r.app})`}`,
282 )}`}
283 </div>
284 <div class="row-meta">
285 teams: ${o.teams.length === 0 ? "none" : o.teams.join(", ")}
286 </div>
287 </div>
288 </li>`,
289 )}
290 </ul>
291 <p>Then the account <strong>${username}</strong> itself goes.</p>
292 <form method="post" action="${at}/retire" class="form-actions">
293 <input type="hidden" name="confirm" value="1" />
294 ${btn("Remove them all", { type: "submit", size: "sm", variant: "danger" })}
295 ${btn("Keep them", { href: "/settings/accounts", size: "sm", variant: "ghost" })}
296 </form>`,
297 {
298 tone: "attn",
299 head: html`<h2>Remove ${username} and what only they own</h2>
300 <p class="muted">
301 This deletes the organizations below with their repositories, apps
302 and teams, and cannot be undone. Nothing is removed until you
303 confirm.
304 </p>`,
305 },
306 ),
307 );
308 }
309
310 /** Names for a one-line message: the first few, then how many more. */
311 function some(names: readonly string[]): string {
312 return names.length <= 5
313 ? names.join(", ")
314 : `${names.slice(0, 5).join(", ")} and ${names.length - 5} more`;
315 }
316
317 // POST /settings/accounts/:username/retire
318 export async function retireAct(ctx: Ctx): Promise<Response> {
319 if (!ctx.auth.user) return signInFirst(ctx);
320 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
321 const form = await readForm(ctx, "admin");
322 if (form instanceof Response) return form;
323 const username = ctx.params.username ?? "";
324 const done = await retireAndRemoveAccount(ctx.app, ctx.auth.user, username, {
325 confirmed: field(form, "confirm") === "1",
326 });
327 if (!done.ok) {
328 if (done.error === "not_found") return notFoundPage(ctx);
329 return flashTo(ctx, "/settings/accounts", {
330 message:
331 done.error === "not_allowed"
332 ? "You cannot do that to yourself, another admin, or an agent."
333 : "That needs your confirmation; nothing was changed.",
334 tone: "danger",
335 });
336 }
337 const { removed, failed } = done.value;
338 if (failed !== null)
339 return flashTo(ctx, "/settings/accounts", {
340 message: `${removed.length === 0 ? "Nothing was removed" : `Removed ${some(removed)}`}; ${failed} would not go. Try again to finish.`,
341 tone: "danger",
342 });
343 return flashTo(ctx, "/settings/accounts", {
344 message: removed.length === 0 ? `${username} was already removed.` : `Removed ${some(removed)}.`,
345 });
346 }
347
228348 // GET /settings/accounts/:username — where one person is signed in
229349 export function personSignInsPage(ctx: Ctx): Response {
230350 if (!ctx.auth.user) return signInFirst(ctx);
@@ -324,6 +444,14 @@ export function accountAct(act: Act) {
324444 : await removeAccount(ctx.app, ctx.auth.user, username);
325445 if (!done.ok) {
326446 if (done.error === "not_found") return notFoundPage(ctx);
447 if (act === "remove" && done.error === "last_owner") {
448 const user = getUserByName(ctx.app.db, username);
449 const orgs =
450 user === undefined
451 ? []
452 : soleOwnedOrgs(ctx.app.db, user.id).map((o) => o.username);
453 return accountsView(ctx, refuseRemove(username, orgs), 409);
454 }
327455 if (act === "suspend" && done.error === "last_owner") {
328456 const user = getUserByName(ctx.app.db, username);
329457 const orgs =
@@ -336,9 +464,7 @@ export function accountAct(act: Act) {
336464 message:
337465 done.error === "not_allowed"
338466 ? "You cannot do that to yourself, another admin, or an agent."
339 : done.error === "last_owner"
340 ? `${username} is the only person owning an organization (named in their row). Make someone else an owner first; nothing was changed.`
341 : "That did not finish; nothing was lost. Try again.",
467 : "That did not finish; nothing was lost. Try again.",
342468 tone: "danger",
343469 });
344470 }
test/accounts.test.ts +56
@@ -555,6 +555,62 @@ describe("accounts: the owner sees, suspends and removes", () => {
555555 expect(getUserByName(app.db, "sam")?.removedAt).not.toBeNull();
556556 });
557557
558 test("the accounts page offers a confirm page that lists what goes; only the confirmed POST removes it", async () => {
559 const { user: boss, token: bossToken } = await outsider("tess");
560 const org = createOrg(app.db, "tessco", boss.id);
561 if (!org.ok) throw new Error(org.error);
562 const made = await createRepo(app, org.value, { name: "ledger" });
563 if (!made.ok) throw new Error(made.error);
564 const bare = repoDir(app.reposRoot, "tessco", "ledger");
565 const auth = { authorization: `Bearer ${ownerToken}` };
566 const retire = "/settings/accounts/tess/retire";
567 const post = (headers: Record<string, string> = {}, body = "confirm=1", token = ownerToken) =>
568 fetch(`${base}${retire}`, {
569 method: "POST",
570 headers: {
571 authorization: `Bearer ${token}`,
572 "content-type": "application/x-www-form-urlencoded",
573 ...headers,
574 },
575 body,
576 });
577
578 // The refusal links to the confirm page.
579 const refused = await fetch(`${base}/settings/accounts/tess/remove`, {
580 method: "POST",
581 headers: { ...auth, "content-type": "application/x-www-form-urlencoded" },
582 });
583 expect(refused.status).toBe(409);
584 expect(await refused.text()).toContain(`href="${retire}"`);
585
586 // Reading the confirm page changes nothing.
587 const seen = await fetch(`${base}${retire}`, { headers: auth });
588 expect(seen.status).toBe(200);
589 const text = await seen.text();
590 expect(text).toContain("tessco/ledger");
591 expect(text).toContain("Owners");
592 expect(existsSync(bare)).toBe(true);
593 expect(getUserByName(app.db, "tess")?.removedAt).toBeNull();
594 expect(getUserByName(app.db, "tessco")?.removedAt).toBeNull();
595
596 // A non-admin gets neither page; a stranger's POST does nothing.
597 expect((await fetch(`${base}${retire}`, { headers: { authorization: `Bearer ${bossToken}` } })).status).toBe(404);
598 expect((await post({}, "confirm=1", bossToken)).status).toBe(404);
599 // Cross-origin is refused.
600 expect((await post({ origin: "https://evil.example" })).status).toBe(403);
601 // Without the confirm field nothing happens either.
602 expect((await post({}, "")).status).toBe(200);
603 expect(existsSync(bare)).toBe(true);
604 expect(getUserByName(app.db, "tess")?.removedAt).toBeNull();
605
606 // Confirmed: it goes.
607 const done = await post({}, "confirm=1");
608 expect(done.status).toBe(200);
609 expect(existsSync(bare)).toBe(false);
610 expect(getUserByName(app.db, "tessco")?.removedAt).not.toBeNull();
611 expect(getUserByName(app.db, "tess")?.removedAt).not.toBeNull();
612 });
613
558614 test("an account with nothing in it can be removed too", async () => {
559615 await outsider("empty");
560616 const res = await api("/api/v1/admin/accounts/empty", {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs