Files
buzz/admin-web/tests/routes.spec.ts
Will Pfleger 86b9142a09 refactor(relay): NIP-98 admin auth with Operator/Moderator roles and NIP-11 discovery (#3777)
Adds authenticated, role-based moderation to the relay admin API. On
`main` the admin API is read-only and gated only by `Host`/`Origin`
matching; this branch adds NIP-98 authentication, a two-tier
Operator/Moderator principal model, mutation and staffing endpoints, and
NIP-11 auto-discovery so clients never type the admin URL by hand.

## Authentication (`BUZZ_ADMIN_AUTH`)

`BUZZ_ADMIN_AUTH` accepts `nip98` or `disabled`. Leaving it unset
defaults to `nip98` (fail-secure). Configuration fails closed: any other
value aborts startup, while a lingering `BUZZ_ADMIN_TOKEN` is ignored
with a startup warning — token (bearer) authentication is not supported.
`Host`/`Origin` matching is retained in every mode as defense-in-depth.

- **`nip98`** (default) — per-request signed NIP-98 (kind 27235) events,
resolved to an Operator or Moderator principal with per-person
attribution and individual revocability. Read-write per resolved
principal.
- **`disabled`** — no credential; relies entirely on network-layer
controls (reverse proxy, VPN, firewall) and logs a `WARN` on every boot.
Always read-only: `authorize()` resolves no principal, so mutation and
staffing routes always `403`.

## Roles

Buzz has two independent authority axes after this change.
**Relay-level** roles (new here) are deployment-global: they act across
every community on the relay, through the admin API. **Community-level**
roles (pre-existing, unchanged by this PR) are tenant-scoped: they act
inside one community, through signed Nostr moderation commands.

### Relay level (new)

| Role | Description |
|---|---|
| **Operator** | Full control of the deployment's moderation surface:
read all reports, feedback, and attachments across every community;
resolve reports with enforcement (`delete`/`kick`/`ban`/`timeout`) or
decisions (`dismiss`/`escalate`); reopen and cancel; update feedback
status; and manage the Operator/Moderator roster via the staffing
endpoints. |
| **Moderator** | Day-to-day triage: everything an Operator can do
except staffing — cannot view or change the roster. |

How a pubkey acquires a relay role (resolution order; config always
outranks DB):

1. Listed in `RELAY_OPERATOR_PUBKEYS` → **Operator** (source `config`)
2. Equals `RELAY_OWNER_PUBKEY` while `RELAY_OPERATOR_PUBKEYS` is empty →
**Operator** (source `owner_fallback`, a break-glass grant for
self-hosters that deactivates once any operator is configured)
3. Row in the `relay_operators` table → **Operator** or **Moderator**
(source `db`, managed via the staffing endpoints)
4. No match → `403`

### Community level (pre-existing, unchanged)

| Role | Description |
|---|---|
| **Owner** (community) | Full authority within their community: every
moderation action (delete, kick, ban/unban, timeout/untimeout, resolve
reports, view queue) plus member, role, and invite management. No guard
rails. |
| **Admin** (community) | Same community-wide moderation capabilities as
owner, except an admin cannot ban or time out the owner or a fellow
admin — only the owner may action an admin. Manages members and invites;
only the owner grants the admin role. |
| **Member** (community) | Standard participant; no moderation
capability. |
| **Owner / Admin** (channel) | Channel-local authority only: delete
messages and kick users within their own channel. |
| **Member / Guest / Bot** (channel) | No moderation authority. |

There is no community-level Moderator tier in v1; relay-level Moderator
is the only role by that name.

## Escalation scoping

The operator report queue is an escalation backstop, not the community's
day-to-day triage surface (per `VISION_MODERATION`, the severe class is
the platform's to review rather than the community's). Two rules enforce
that:

- **Escalated-by-default listing.** `GET /reports` with no `status`
parameter returns only `escalated` reports. An explicit
`status=<open|resolved|dismissed|escalated>` filter is always honored as
given, and full visibility across every status stays available for
platform-safety and legal review via `scope=all` (which lists reports
regardless of status). `scope` accepts only `all` and is ignored when an
explicit `status` is present.
- **Auto-escalated `illegal` reports.** Member reports whose category is
`illegal` are ingested with `status=escalated` rather than `open`, so
the severe class reaches the operator backstop without waiting for a
community admin to forward it. Every other category still lands `open`.
Auto-escalation only sets the queue status — it records no moderator
decision and stamps no resolver, so an auto-escalated report is
indistinguishable downstream from an admin-escalated one: the reopen
route returns it to `open` on the same terms, keyed only on status,
never on how the report became escalated.

## Principal resolution and NIP-98 admission

`resolve_admin_principal()` returns `AdminPrincipal { pubkey, role,
source }` per the resolution order above; `None` never falls through as
a role. Admission is ordered so the replay guard is a privilege, not a
public surface: signature/URL/method/payload-hash verification first,
roster check second, and only then is the deployment-scoped replay id
atomically consumed — a validly-signing but unrostered key never
allocates a replay slot. Redis failure fails closed.

## Report resolution, recovery, and enforcement provenance

`POST /reports/{id}/resolve` is a crash-safe enforcement state machine:
decision-only outcomes (`dismiss`/`escalate`) are a single
CAS-plus-audit transaction; enforcement
(`delete`/`kick`/`ban`/`timeout`) claims the report
(`open`→`processing`), runs the durable mutation, then finalizes — a
re-drive resumes at the step marker and converges to exactly-one
enforcement, fenced by a lease and an outbox claim token.

Person-directed enforcement on an `event`-kind report derives its target
from the stored event's author (server-owned truth, never the reporter's
`p` tag) via a single `derive_enforcement_target` shared by the HTTP
driver and the recovery worker. If the reported event was purged before
its author could be read, person-directed actions are rejected pre-claim
and the report stays `open`; `delete` needs only the event id and is
exempt.

`GET /reports/{id}` and the resolve response carry an `activeAction`
field surfacing the enforcement that actually executed — a report
dismissed after a reopen still reports the ban that ran. `POST
/reports/{id}/reopen` returns a terminal report to `open` (idempotent on
`requestId`). `POST /reports/{id}/cancel` is the sole recovery path for
a pre-mutation `failed` action, attributed via
`relay_admin_actions.cancelled_by`.

## Feedback

`GET /feedback` and `/feedback/{id}` survive a tenant purge: provenance
columns are severed to `NULL` rather than cascade-deleted, and the
attachment path fails closed to `404` on a severed row. `PATCH
/feedback/{id}` updates lifecycle `status`
(`new`/`reviewed`/`archived`).

## Staffing and probe

`GET/PUT/DELETE /operators/{pubkey}` are Operator-only; mutating a
config-backed pubkey returns `409 Conflict`. `GET /operators` returns
the union of config and DB principals with per-entry `source`. `GET
/probe` reports auth mode, role, source, `canAct`, and `canStaff` for
the desktop console.

## NIP-11 auto-discovery

The NIP-11 relay-information document gains an optional `admin_api`
field carrying the canonical admin origin (`scheme://host[:port]`, no
path), present iff `BUZZ_ADMIN_HOST` is set and omitted otherwise. The
scheme follows the same loopback rule as NIP-98 `u`-tag verification via
a shared `scheme_for_host` helper, so the advertised origin and the
origin the relay verifies against can never diverge.

## Operator API origin decoupling

`RELAY_OPERATOR_API_ORIGIN` is no longer required at boot when
`RELAY_OPERATOR_PUBKEYS` is set — it is used only by the
community-provisioning endpoints, which fail closed at request time
(with a boot-time `WARN`) until it is set. The admin console needs no
origin.

## Admin-web adaptation

The standalone `admin-web` dashboard signs each request as a NIP-98
event via a NIP-07 browser extension, discovers the auth mode with a
single unauthenticated probe (`200` → `disabled`, anything else →
`nip98`, fail-secure), and carries no token entry surface. Playwright
coverage exercises the NIP-98 and CSP paths.

## Security hardening

Three findings from security review are folded in:

- **Append-only roster audit.** `PUT`/`DELETE /operators/{pubkey}`
mutate the deployment-wide root of trust, but the upsert overwrites
`role`/`added_by` in place and the delete removes the only row — so a
grant→revoke sequence left no trace of who was ever granted or by whom.
Each mutation now writes an `relay_operator_audit` row (actor, target,
`grant`/`revoke`, pre-image `prev_role`, `new_role`, timestamp) inside
the same transaction as the mutation. A per-target transaction-scoped
advisory lock serializes concurrent mutations of the same pubkey before
the pre-image read, so the recorded `prev_role` is always the true
predecessor even under a concurrent-grant race. Chronology is keyed on a
`BIGINT GENERATED ALWAYS AS IDENTITY` `seq` column, not the wall clock:
the serializing lock guarantees insertion order and `seq` captures it,
so ordered reads (`ORDER BY seq`) follow the true privilege chain even
across a backward NTP step that a `clock_timestamp()` ordering would
invert. `created_at` (`clock_timestamp()`) is retained as informational
occurrence time only. Append-only by construction — no `UPDATE`/`DELETE`
path and no API surface. A no-op delete writes nothing.
- **`expirationSecs` overflow.** The timeout path built `Utc::now() +
Duration::seconds(secs as i64)` from an attacker-controlled `u64`:
`i64::MAX` panicked the handler, and a wrapped-negative magnitude minted
a *past* expiry that still passed validation. `compute_timeout_until`
now rejects zero, rejects magnitudes above a documented
`MAX_TIMEOUT_SECS` (365 days), and uses checked
`try_seconds`/`checked_add_signed` so no input can panic or produce a
past expiry — over-cap, zero, `i64::MAX`, and wrapping-negative inputs
all return a clean `4xx`.
- **Uppercase-hex config-backed bypass.** Config pubkeys are lowercased
at parse, but the `409` immutability check raw-string-compared the path
param while `decode_hex_pubkey` accepted uppercase — so `PUT
/operators/{UPPERCASE}` skipped the guard and wrote a shadow row for the
same 32 bytes. The validated param is now canonicalized (lowercased)
before the `409` check, DB write, `DELETE`, and response body.

## Migrations

- `0035_relay_operators.sql` — `relay_operators` roster table
(deployment-global), `actor_authority` on `moderation_actions`,
`processing` status plus `active_action_id` on `moderation_reports`,
`status` on `product_feedback`.
- `0036_relay_admin_actions.sql` — enforcement-action table with a
`request_id` idempotency key, a `step_marker` for crash recovery, and a
`cancelled_by` attribution column.
- `0037_relay_admin_action_lease.sql` — lease fencing for the action
worker.
- `0038_relay_admin_outbox_claim_token.sql` — fenced claim token on the
outbox worker.
- `0039_relay_operator_audit.sql` — append-only `relay_operator_audit`
trail for roster mutations (see Security hardening).

`docs/admin/README.md` documents the full principal model, NIP-98 event
requirements, capabilities by role, the startup error matrix, and the
discovery field.

## Production blast radius

A relay without `BUZZ_ADMIN_HOST` is completely unaffected — the admin
surface stays disabled and `BUZZ_ADMIN_AUTH` is ignored; a lingering
`BUZZ_ADMIN_TOKEN` logs a startup warning and must be removed. Where
`BUZZ_ADMIN_HOST` **is** set, unset `BUZZ_ADMIN_AUTH` defaults to
`nip98` (per-person signed auth); `BUZZ_ADMIN_AUTH=disabled` reproduces
`main`'s prior `Host`/`Origin`-only gating but is read-only (mutation
routes `403`). The five migrations add tables and columns without
touching existing data.

---

Related: [block/buzz#4768](https://github.com/block/buzz/pull/4768)
(desktop admin console consuming the `admin_api` field),
[squareup/bb-public#339](https://github.com/squareup/bb-public/pull/339)
(Phase 4 rollout config)

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-08-28 11:43:05 -04:00

383 lines
13 KiB
TypeScript

import { expect, test } from "@playwright/test";
test.beforeEach(async ({ page }) => {
// Every admin API call returns 200, so the probe resolves to disabled mode
// and the dashboard renders without a credential.
await page.route("**/api/admin/v1/**", async (route) => {
await route.fulfill({ contentType: "application/json", body: "[]" });
});
});
for (const [path, heading] of [
["/reports", "Open reports"],
["/feedback", "Feedback"],
]) {
test(`${path} supports a deep link and empty state`, async ({ page }) => {
await page.goto(path);
await expect(page.getByRole("heading", { name: heading })).toBeVisible();
await expect(page.getByText("No records.")).toBeVisible();
});
}
test("forbidden reads have an explicit state", async ({ page }) => {
await page.route("**/api/admin/v1/reports?**", (route) =>
route.fulfill({
status: 403,
contentType: "application/json",
body: JSON.stringify({
error: { code: "forbidden", message: "request is not authorized" },
}),
}),
);
await page.goto("/reports");
await expect(
page.getByRole("heading", { name: "Access denied" }),
).toBeVisible();
});
test("report rows render the relay response contract", async ({ page }) => {
await page.route("**/api/admin/v1/reports?**", (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify([
{
id: "0e6caad8-1e18-4cd7-84fa-7264103f0a08",
communityId: "6d474feb-c50a-44e4-a0b5-f30532df49bc",
communityHost: "design.buzz.xyz",
reporterPubkey: "21".repeat(32),
targetKind: "event",
target: "12".repeat(32),
reportType: "spam",
status: "open",
createdAt: "2026-07-17T17:30:00Z",
},
]),
}),
);
await page.goto("/reports");
await expect(page.getByText("design.buzz.xyz")).toBeVisible();
await expect(page.getByText("spam")).toBeVisible();
await expect(page.getByText("Unknown date")).toHaveCount(0);
});
test("event report detail renders the reported message content", async ({
page,
}) => {
const id = "0e6caad8-1e18-4cd7-84fa-7264103f0a08";
await page.route(`**/api/admin/v1/reports/${id}`, (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify({
id,
communityId: "6d474feb-c50a-44e4-a0b5-f30532df49bc",
communityHost: "design.buzz.xyz",
reporterPubkey: "21".repeat(32),
targetKind: "event",
target: "12".repeat(32),
reportType: "spam",
status: "open",
createdAt: "2026-07-17T17:30:00Z",
message: {
authorPubkey: "31".repeat(32),
content:
"This is the complete reported message.\nIt preserves lines.",
createdAt: "2026-07-17T17:25:00Z",
deletedAt: null,
},
}),
}),
);
await page.goto(`/reports/${id}`);
await expect(
page.getByText("This is the complete reported message.", { exact: false }),
).toBeVisible();
await expect(page.getByText("31".repeat(32))).toBeVisible();
await expect(
page.getByText("Message content is unavailable", { exact: false }),
).toHaveCount(0);
});
test("event report detail explains when message content is unavailable", async ({
page,
}) => {
const id = "0e6caad8-1e18-4cd7-84fa-7264103f0a09";
await page.route(`**/api/admin/v1/reports/${id}`, (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify({
id,
communityId: "6d474feb-c50a-44e4-a0b5-f30532df49bc",
communityHost: "design.buzz.xyz",
reporterPubkey: "21".repeat(32),
targetKind: "event",
target: "12".repeat(32),
reportType: "spam",
status: "open",
createdAt: "2026-07-17T17:30:00Z",
message: null,
}),
}),
);
await page.goto(`/reports/${id}`);
await expect(
page.getByText("Message content is unavailable", { exact: false }),
).toBeVisible();
});
test("feedback cards open the complete submission", async ({ page }) => {
const id = "feed0000-0000-4000-8000-000000000001";
const fullBody = `${"Long feedback ".repeat(30)}end of feedback`;
await page.route(`**/api/admin/v1/feedback/${id}`, (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify({
id,
communityId: "6d474feb-c50a-44e4-a0b5-f30532df49bc",
communityHost: "design.buzz.xyz",
eventId: "31".repeat(32),
submitterPubkey: "21".repeat(32),
category: "needs-work",
body: fullBody,
tags: [],
eventCreatedAt: "2026-07-17T17:25:00Z",
receivedAt: "2026-07-17T17:30:00Z",
}),
}),
);
await page.route("**/api/admin/v1/feedback", (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify([
{
id,
communityId: "6d474feb-c50a-44e4-a0b5-f30532df49bc",
communityHost: "design.buzz.xyz",
submitterPubkey: "21".repeat(32),
category: "needs-work",
bodySummary: `${fullBody.slice(0, 240)}…`,
receivedAt: "2026-07-17T17:30:00Z",
},
]),
}),
);
await page.goto("/feedback");
const card = page.locator(".feedback-record");
await expect(card.locator(".record-provenance")).toContainText(
"design.buzz.xyz",
);
await card.locator(".feedback-main-link").click();
await expect(page).toHaveURL(`/feedback/${id}`);
await expect(
page.getByRole("heading", { name: "Feedback detail" }),
).toBeVisible();
await expect(
page.getByText("end of feedback", { exact: false }),
).toBeVisible();
});
test("feedback can be searched and filtered by community and time", async ({
page,
}) => {
const recent = new Date(Date.now() - 60 * 60 * 1000).toISOString();
const old = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString();
await page.route("**/api/admin/v1/feedback", (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify([
{
id: "recent",
communityId: "one",
communityHost: "design.buzz.xyz",
submitterPubkey: "21".repeat(32),
category: "bug",
bodySummary: "Composer freezes after sleep",
receivedAt: recent,
},
{
id: "old",
communityId: "two",
communityHost: "engineering.buzz.xyz",
submitterPubkey: "22".repeat(32),
category: "praise",
bodySummary: "Calls are much more reliable",
receivedAt: old,
},
]),
}),
);
await page.goto("/feedback");
await expect(page.getByText("2 of 2 submissions")).toBeVisible();
await page.getByRole("searchbox", { name: "Search feedback" }).fill("calls");
await expect(page.getByText("Calls are much more reliable")).toBeVisible();
await expect(page.getByText("Composer freezes after sleep")).toHaveCount(0);
await page.getByRole("searchbox", { name: "Search feedback" }).fill("");
await page.getByLabel("Community").selectOption("design.buzz.xyz");
await expect(page.getByText("Composer freezes after sleep")).toBeVisible();
await expect(page.getByText("Calls are much more reliable")).toHaveCount(0);
await page.getByLabel("Community").selectOption("all");
await page.getByLabel("Received").selectOption("day");
await expect(page.getByText("Composer freezes after sleep")).toBeVisible();
await expect(page.getByText("Calls are much more reliable")).toHaveCount(0);
});
test("feedback filters keep long community names usable", async ({ page }) => {
await page.route("**/api/admin/v1/feedback", (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify([
{
id: "long-community",
communityId: "long-community",
communityHost: `${"long-community-name.".repeat(4)}buzz.example.com`,
submitterPubkey: "21".repeat(32),
category: "bug",
bodySummary: "The filter row stays within its container",
receivedAt: new Date().toISOString(),
},
]),
}),
);
for (const viewport of [
{ name: "desktop", width: 1200 },
{ name: "mobile", width: 720 },
]) {
await test.step(viewport.name, async () => {
await page.setViewportSize({ width: viewport.width, height: 720 });
await page.goto("/feedback");
const filters = page.locator(".feedback-filters");
const search = page.getByRole("searchbox", { name: "Search feedback" });
const community = page.getByRole("combobox", { name: "Community" });
const status = page.getByLabel("Status");
await expect(filters).toBeVisible();
await expect(community).toBeVisible();
await expect(status).toBeVisible();
const [filtersBox, searchBox, communityBox, statusBox] =
await Promise.all([
filters.boundingBox(),
search.boundingBox(),
community.boundingBox(),
status.boundingBox(),
]);
if (!filtersBox || !searchBox || !communityBox || !statusBox) {
throw new Error("feedback filter bounds were unavailable");
}
expect(statusBox.x + statusBox.width).toBeLessThanOrEqual(
filtersBox.x + filtersBox.width,
);
if (viewport.name === "desktop") {
const rootFontSize = await page.evaluate(() =>
Number.parseFloat(
getComputedStyle(document.documentElement).fontSize,
),
);
expect(communityBox.width).toBeGreaterThanOrEqual(14 * rootFontSize);
} else {
expect(Math.abs(communityBox.width - searchBox.width)).toBeLessThan(1);
}
const pageWidths = await page.evaluate(() => ({
client: document.documentElement.clientWidth,
scroll: document.documentElement.scrollWidth,
}));
expect(pageWidths.scroll).toBe(pageWidths.client);
});
}
});
test("feedback status is stored locally by feedback id", async ({ page }) => {
await page.route("**/api/admin/v1/feedback", (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify([
{
id: "feedback-one",
communityId: "one",
communityHost: "design.buzz.xyz",
submitterPubkey: "21".repeat(32),
category: "bug",
bodySummary: "Composer freezes after sleep",
receivedAt: new Date().toISOString(),
},
]),
}),
);
await page.goto("/feedback");
await page.getByRole("checkbox", { name: "Acted on" }).check();
await page.reload();
await expect(page.getByRole("checkbox", { name: "Acted on" })).toBeChecked();
await page.getByLabel("Status").selectOption("acted-on");
await expect(page.getByText("Composer freezes after sleep")).toBeVisible();
await page.getByLabel("Status").selectOption("pending");
await expect(page.getByText("No matching feedback.")).toBeVisible();
});
test("feedback attachments render from imeta without raw markdown", async ({
page,
}) => {
const id = "feedback-with-attachments";
const imageUrl = `https://design.buzz.xyz/media/${"a".repeat(64)}.png`;
const fileUrl = `https://design.buzz.xyz/media/${"b".repeat(64)}.txt`;
await page.route(`**/api/admin/v1/feedback/${id}`, (route) =>
route.fulfill({
contentType: "application/json",
body: JSON.stringify({
id,
communityId: "one",
communityHost: "design.buzz.xyz",
eventId: "31".repeat(32),
submitterPubkey: "21".repeat(32),
category: "bug",
body: `Composer froze.\n![image](${imageUrl})\n[diagnostics.txt](${fileUrl})`,
tags: [
[
"imeta",
`url ${imageUrl}`,
"m image/png",
`x ${"a".repeat(64)}`,
"size 48213",
"dim 1280x720",
"filename screenshot.png",
],
[
"imeta",
`url ${fileUrl}`,
"m text/plain",
`x ${"b".repeat(64)}`,
"size 391",
"filename diagnostics.txt",
],
],
eventCreatedAt: "2026-07-17T17:25:00Z",
receivedAt: "2026-07-17T17:30:00Z",
}),
}),
);
await page.goto(`/feedback/${id}`);
await expect(
page.getByText("Composer froze.", { exact: true }),
).toBeVisible();
await expect(page.getByText("![image]", { exact: false })).toHaveCount(0);
await expect(
page.getByRole("img", { name: "screenshot.png" }),
).toHaveAttribute("src", /^blob:/);
await expect(
page.getByRole("link", { name: /diagnostics.txt/ }),
).toHaveAttribute("href", /^blob:/);
const fileHeight = await page
.locator(".file-attachment")
.evaluate((element) => element.getBoundingClientRect().height);
expect(fileHeight).toBeLessThan(100);
});