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

The app's owner hides a note or bans its sender from a screen, not only through `POST /__forge/note/moderate` #5097

Parked opened this
Closed without merging

scout/forge:scout/4819-the-app-s-owner-hides-a-note-or-bans-its → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +239 −3
README.md +5 −2
@@ -1013,8 +1013,11 @@ Under the box, four starter sentences are plain links (no script):
10131013 happens on the forge, not on the app: the app host answers only
10141014 `POST /__forge/note` and `GET /__forge/notes`, and `/__forge/note/moderate` is
10151015 a 404 there, because the app's own code (or a preview's) could call it
1016 same-origin with a visiting admin's cookie. The terminal screen above is the
1017 owner's tool today.
1016 same-origin with a visiting admin's cookie. The terminal screen above and the
1017 app's studio page are the owner's tools: the page lists the latest notes
1018 (sender, words, page, when) for those who may admin the repository, each with
1019 Hide and Ban sender, and every banned sender once with Unban, posting to
1020 `POST /:owner/:name/app/notes` on the forge's origin (`web/studio/notes.ts`).
10181021 Limits count the socket's client (`http/peer.ts`, with its trusted-proxy
10191022 rule), never a header the client wrote, and all three are checked before any
10201023 is spent. The request body is read only up to 16 KB. The issue says its text
src/actions/app_notes.ts +49 −1
@@ -6,7 +6,7 @@
66 * both go through here, so the limits and the gating are one set.
77 */
88 import type { App } from "../app.ts";
9 import { banVisitor, markSender, getNote, hideNote, insertNote, isBanned, notesOf, notesOfApp, type AppNote } from "../core/app_notes.ts";
9 import { banVisitor, bannedNotes, unbanVisitor, markSender, getNote, hideNote, insertNote, isBanned, notesOf, notesOfApp, type AppNote } from "../core/app_notes.ts";
1010 import type { AppRecord } from "../core/apps.ts";
1111 import { createLabel, getIssue, getLabel } from "../core/issues.ts";
1212 import { RateLimiter } from "../core/ratelimit.ts";
@@ -259,3 +259,51 @@ export async function moderateNote(
259259 if (action === "ban") banVisitor(app.db, record.id, note.visitor);
260260 return ok(true);
261261 }
262
263 /** What the owner's list shows of one note: the sender, the words, the page. */
264 export interface OwnerNote {
265 readonly id: string;
266 readonly by: string;
267 readonly person: boolean;
268 readonly text: string;
269 readonly page: string;
270 readonly at: string;
271 readonly banned: boolean;
272 }
273
274 /** The page a note was sent from, read back from the fenced line the issue holds. */
275 function pageOf(body: string): string {
276 const m = /^- Page: `([^`\n]*)`/m.exec(body);
277 return m?.[1] ?? "";
278 }
279
280 function ownerView(app: App, repo: Repo, n: AppNote, banned: boolean): OwnerNote | undefined {
281 const issue = getIssue(app.db, repo.id, n.issueNumber);
282 if (issue === undefined) return undefined;
283 return {
284 id: n.id,
285 by: n.name,
286 person: n.visitor.startsWith("u:"),
287 text: issue.title.startsWith(FROM_APP_TITLE) ? issue.title.slice(FROM_APP_TITLE.length) : issue.title,
288 page: pageOf(issue.body),
289 at: n.createdAt,
290 banned,
291 };
292 }
293
294 /** The owner's screen: the latest notes still shown, and each banned sender once. Writers only. */
295 export function ownerNotes(app: App, record: AppRecord, repo: Repo, actor: User | undefined): { notes: OwnerNote[]; banned: OwnerNote[] } | undefined {
296 if (actor === undefined || !canAdmin(app.db, repo, actor)) return undefined;
297 const pick = (rows: AppNote[], banned: boolean) =>
298 rows.map((n) => ownerView(app, repo, n, banned)).filter((n): n is OwnerNote => n !== undefined);
299 return { notes: pick(notesOfApp(app.db, record.id), false), banned: pick(bannedNotes(app.db, record.id), true) };
300 }
301
302 /** The owner's: let the sender of a note write again. */
303 export function unbanSender(app: App, record: AppRecord, repo: Repo, actor: User | undefined, noteId: string): Result<true, "forbidden" | "not_found"> {
304 if (actor === undefined || !canAdmin(app.db, repo, actor)) return err("forbidden");
305 const note = getNote(app.db, record.id, noteId);
306 if (note === undefined) return err("not_found");
307 unbanVisitor(app.db, record.id, note.visitor);
308 return ok(true);
309 }
src/core/app_notes.ts +23
@@ -100,6 +100,29 @@ export function banVisitor(db: Database, appId: string, visitor: string): void {
100100 db.query("UPDATE app_note SET hidden = 1 WHERE app_id = ?1 AND visitor = ?2").run(appId, visitor);
101101 }
102102
103 /** Let a banned sender write again; the notes hidden with the ban stay hidden. */
104 export function unbanVisitor(db: Database, appId: string, visitor: string): void {
105 db.query("DELETE FROM app_note_ban WHERE app_id = ?1 AND visitor = ?2").run(appId, visitor);
106 }
107
108 /**
109 * Each banned sender once, newest ban first, as their latest note (hidden or
110 * not): the note's id is how the owner names them, never the visitor key.
111 */
112 export function bannedNotes(db: Database, appId: string): AppNote[] {
113 return db
114 .query<Row, [string]>(
115 `SELECT n.* FROM app_note_ban b
116 JOIN app_note n ON n.app_id = b.app_id AND n.visitor = b.visitor
117 WHERE b.app_id = ?1
118 AND n.id = (SELECT m.id FROM app_note m WHERE m.app_id = b.app_id AND m.visitor = b.visitor
119 ORDER BY m.created_at DESC, m.id DESC LIMIT 1)
120 ORDER BY b.created_at DESC, n.id DESC`,
121 )
122 .all(appId)
123 .map(fromRow);
124 }
125
103126 export function isBanned(db: Database, appId: string, visitor: string): boolean {
104127 return (
105128 db
src/http/server.ts +2
@@ -226,6 +226,7 @@ import {
226226 newIssuePage,
227227 newIssueSubmit,
228228 } from "../web/pages/issues.ts";
229 import { noteModerate } from "../web/studio/notes.ts";
229230 import { tellPage } from "../web/studio/tell.ts";
230231 import { tellHerePage } from "../web/studio/tell_here.ts";
231232 import { globalMapPage, mapPage } from "../web/pages/map.ts";
@@ -1234,6 +1235,7 @@ export function buildRouter(): Router<Handler> {
12341235 router.add("GET", "/:owner/:name/app/:env/open", appOpen);
12351236 // Where a private app sends a person who arrived by its link.
12361237 router.add("GET", "/apps/open", appsOpen);
1238 router.add("POST", "/:owner/:name/app/notes", noteModerate);
12371239 router.add("POST", "/:owner/:name/app/:env/redeploy", appRedeploy);
12381240 router.add("POST", "/:owner/:name/app/:env/stop", appStop);
12391241 router.add("GET", "/:owner/:name/runs", runsList);
src/web/studio/app.ts +2
@@ -51,6 +51,7 @@ import { changesHref, tellsHref } from "./nouns.ts";
5151 import { answersRegion } from "./answers.ts";
5252 import { nowCard, nowRegion } from "./now.ts";
5353 import { repoAsks } from "./asks.ts";
54 import { notesCard } from "./notes.ts";
5455 import { appPanels } from "./previews.ts";
5556 import { noCrewLine, servingHistory, type WordCtx } from "./words.ts";
5657 import { crewKeyNote } from "./crew.ts";
@@ -500,6 +501,7 @@ export async function studioApp(
500501 ${ownerFacts && ctx.auth.user ? answersRegion(ctx, repo, ctx.auth.user) : null}
501502 <div id="app-previews">${previews}</div>
502503 ${nowRegion(repo, now)}
504 ${notesCard(ctx, repo, record)}
503505 </div>
504506 <aside class="stack">
505507 ${crewCard} ${weekCard} ${ownCard} ${more}
src/web/studio/notes.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * The app's notes from its forge button (#4758), on the studio page, for the
3 * people who may moderate: the latest `from-app` notes with Hide and Ban
4 * sender, and each banned sender once with Unban. The buttons post to the
5 * forge's own origin (`POST /:owner/:name/app/notes`), never to the app's
6 * host, where moderation is a 404.
7 */
8 import { moderateNote, ownerNotes, unbanSender, type OwnerNote } from "../../actions/app_notes.ts";
9 import { getAppByRepo, type AppRecord } from "../../core/apps.ts";
10 import type { Repo } from "../../core/repos.ts";
11 import type { User } from "../../core/users.ts";
12 import type { Ctx } from "../../http/context.ts";
13 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
14 import { readForm } from "../form.ts";
15 import { html, type Html } from "../html.ts";
16 import { flashTo } from "../layout.ts";
17 import { badge, btn, icon, listCard, row, time } from "../ui.ts";
18 import { safeBack } from "../../http/context.ts";
19
20 const act = (base: string, n: OwnerNote, action: "hide" | "ban" | "unban", label: string, danger = false): Html =>
21 html`<form method="post" action="${base}/app/notes" class="inline">
22 <input type="hidden" name="id" value="${n.id}" />
23 <input type="hidden" name="action" value="${action}" />
24 ${btn(label, { size: "sm", ...(danger ? { variant: "danger" as const } : {}) })}
25 </form>`;
26
27 const sender = (n: OwnerNote): Html =>
28 html`${n.by} ${badge(n.person ? "signed in" : "anonymous", { variant: "outline" })}`;
29
30 /** The card, or nothing for anyone who may not moderate or when there is nothing to show. */
31 export function notesCard(ctx: Ctx, repo: Repo, record: AppRecord): Html | null {
32 const seen = ownerNotes(ctx.app, record, repo, ctx.auth.user);
33 if (seen === undefined || (seen.notes.length === 0 && seen.banned.length === 0)) return null;
34 const base = repoBase(repo);
35 const notes = seen.notes.map((n) =>
36 row({
37 title: n.text,
38 meta: html`${sender(n)} · ${n.page === "" ? "no page" : n.page} · ${time(n.at)}`,
39 trail: html`<span class="bar">${act(base, n, "hide", "Hide")} ${act(base, n, "ban", "Ban sender", true)}</span>`,
40 }),
41 );
42 const banned = seen.banned.map((n) =>
43 row({
44 title: sender(n),
45 meta: html`banned · last wrote ${time(n.at)}`,
46 trail: act(base, n, "unban", "Unban"),
47 }),
48 );
49 return html`<div class="stack" id="app-notes">
50 ${listCard(notes.length > 0 ? notes : [row({ title: html`<span class="muted">No notes shown.</span>` })], {
51 head: html`${icon("comment")}<h2>Notes from the app</h2>`,
52 })}
53 ${banned.length === 0 ? null : listCard(banned, { head: html`<h2>Banned senders</h2>` })}
54 </div>`;
55 }
56
57 const FAILURE: Record<string, string> = {
58 forbidden: "You need admin access to do that.",
59 unavailable: "That could not be done just now.",
60 };
61
62 // POST /:owner/:name/app/notes — hide a note, ban or unban its sender.
63 export async function noteModerate(ctx: Ctx): Promise<Response> {
64 const repo = loadRepo(ctx);
65 if (!repo) return notFoundPage(ctx);
66 const record = getAppByRepo(ctx.app.db, repo.id);
67 if (record === undefined) return notFoundPage(ctx);
68 const user: User | undefined = ctx.auth.user;
69 if (!user) return signInFirst(ctx);
70 const form = await readForm(ctx, "rw");
71 if (form instanceof Response) return form;
72 const id = String(form.get("id") ?? "");
73 const action = String(form.get("action") ?? "");
74 if (id === "" || id.length > 64 || !["hide", "ban", "unban"].includes(action))
75 return new Response("bad request", { status: 400 });
76 const done =
77 action === "unban"
78 ? unbanSender(ctx.app, record, repo, user, id)
79 : await moderateNote(ctx.app, record, repo, user, id, action as "hide" | "ban");
80 const back = safeBack(ctx) ?? repoBase(repo);
81 if (!done.ok) {
82 if (done.error === "not_found") return notFoundPage(ctx);
83 return flashTo(ctx, back, { tone: "danger", message: FAILURE[done.error] ?? "That could not be done." });
84 }
85 return flashTo(ctx, back, {
86 message: action === "hide" ? "Note hidden." : action === "ban" ? "Sender banned." : "Sender unbanned.",
87 });
88 }
test/apps-feedback.test.ts +70
@@ -312,6 +312,76 @@ describe("the forge button takes notes from anyone", () => {
312312 expect((await at("diary", "/__forge/notes")).status).toBe(404);
313313 });
314314
315 test("the studio page lists the notes; a writer hides one, bans a sender and unbans them; a stranger sees and can do nothing", async () => {
316 // The minute's bounds are spent by the tests before; this one starts a later minute.
317 const start = Date.now() + 120_000;
318 noteClock.now = () => start;
319 const signin = await fetch(`${servers.url}/signin`, {
320 method: "POST",
321 headers: { origin: servers.url },
322 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
323 redirect: "manual",
324 });
325 const me = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
326 const forge = (path: string, init: RequestInit = {}, cookie = me) =>
327 fetch(`${servers.url}${path}`, {
328 ...init,
329 headers: { origin: servers.url, ...(cookie ? { cookie } : {}), ...(init.headers as Record<string, string>) },
330 redirect: "manual",
331 });
332 const form = (body: Record<string, string>, cookie = me) =>
333 forge("/alice/notes/app/notes", { method: "POST", body: new URLSearchParams(body) }, cookie);
334 const first = await post("studio words one", "", "10.7.0.1");
335 const cookie = cookieOf(first);
336 const sent = (await first.json()) as { note: { id: string; url: string }; name: string };
337 const number = Number(sent.note.url.split("/").pop());
338 const repo = getRepo(app.db, "alice", "notes")!;
339
340 const page = await (await forge("/alice/notes")).text();
341 expect(page).toContain("studio words one");
342 expect(page).toContain(sent.name);
343 expect(page).toContain("anonymous");
344 expect(page).toContain("/lists");
345 expect(page).toContain("Hide");
346 expect(page).toContain("Ban sender");
347 // a stranger reads no list and the post is refused
348 const stranger = await (await forge("/alice/notes", {}, "")).text();
349 expect(stranger).not.toContain("Ban sender");
350 expect(stranger).not.toContain('id="app-notes"');
351 expect((await form({ id: sent.note.id, action: "hide" }, "")).status).not.toBe(302);
352 expect(getIssue(app.db, repo.id, number)!.state).toBe("open");
353 // same-origin is checked
354 const cross = await forge("/alice/notes/app/notes", { method: "POST", headers: { origin: "http://evil.example" }, body: new URLSearchParams({ id: sent.note.id, action: "hide" }) });
355 expect(cross.status).toBe(403);
356 expect((await form({ id: sent.note.id, action: "nuke" })).status).toBe(400);
357
358 // hide: the issue closes and the row goes
359 expect((await form({ id: sent.note.id, action: "hide" })).status).toBe(303);
360 expect(getIssue(app.db, repo.id, number)!.state).toBe("closed");
361 expect(await (await forge("/alice/notes")).text()).not.toContain(`value="${sent.note.id}"`);
362
363 // ban: the sender's next note is refused and they are listed once with Unban
364 const second = await post("studio words two", cookie, "10.7.0.1");
365 expect(second.status).toBe(201);
366 const secondId = ((await second.json()) as { note: { id: string } }).note.id;
367 expect((await form({ id: secondId, action: "ban" })).status).toBe(303);
368 expect((await post("again", cookie, "10.7.0.1")).status).toBe(403);
369 const banned = await (await forge("/alice/notes")).text();
370 expect(banned).toContain("Banned senders");
371 expect(banned.split(`value="${secondId}"`).length - 1).toBe(1);
372 // unban
373 expect((await form({ id: secondId, action: "unban" })).status).toBe(303);
374 expect((await post("back again", cookie, "10.7.0.1")).status).toBe(201);
375 expect(await (await forge("/alice/notes")).text()).not.toContain(`value="${secondId}"`);
376 // the app host answers 404 for moderation, and for the forge's own path too
377 for (const path of ["/__forge/note/moderate", "/app/notes"])
378 expect((await at("notes", path, { method: "POST", body: JSON.stringify({ id: secondId, action: "ban" }) }, "")).status).toBe(404);
379 });
380
381 test("the clock is the real one again", () => {
382 noteClock.now = () => Date.now();
383 });
384
315385 test("the panel fits a phone and a desktop, and says no forge words first", () => {
316386 // 390x844: at most 320px wide within the viewport, and 70% high leaves the top (camera) clear.
317387 expect(toolbarJs).toContain("max-width:min(320px,calc(100vw - 64px))");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs