Skip to content

Commit 8f8c4df

Browse files
wpfleger96DuncanAlia
authored
feat(desktop): relay admin console for the /api/admin/v1 operator surface (#4768)
Adds a relay admin console under Settings — the single surface for relay-level operator work — replacing the previously unreachable moderation section. Operators authenticate with their own Nostr key over NIP-98 — no browser extension, no bearer token — to view deployment-wide moderation reports and product feedback, resolve/dismiss/escalate/reopen reports, update feedback status, and manage the operator/moderator staffing roster. ## Nav reachability The old `moderation` section id was defined in `settingsSections` but never wired into any group in `settingsNavGroups`, so the sidebar never rendered it — unreachable since #1617. This PR replaces it with a `relay-admin` section wired into the Communities nav group, pointing at the relay admin console, and drops the separate `admin-console` section id so a single surface owns relay-level trust & safety. The Relay admin nav entry is always visible. Auth gates the panel itself; the nav entry is a door, not a credential — hiding it behind discovery state would strand an operator whose relay transiently fails NIP-11 discovery with no path back to the connection settings. ## Discovery and connection On mount the console reads the connected relay's NIP-11 document for the optional `admin_api` field. When a valid origin is discovered **and its host matches the connected relay's host** (case-insensitive, host identity only), it is automatically saved and probed — the panel renders immediately with no Save step required. A cross-host advertisement is pre-fill only: it populates the manual origin field under Advanced and is never saved or probed without an explicit Save, so a relay cannot direct an unconsented NIP-98 signature at a third-party origin; residual exposure on the same-host path is bounded by NIP-98's URL/method/payload binding. Saving is only required for manual origin changes. The advertised origin is untrusted input: revalidated through `AdminOrigin::parse`, falling back to manual entry when absent or invalid. A saved manual origin always takes precedence over discovery. ## Auth and transport (Rust, `src-tauri/src/commands/admin/`) - `AdminOrigin` value object: validates scheme + host + optional port, rejects credentials/path/query/fragment; `http://` only for loopback. The relay side normalizes its configured admin host at config load and compares inbound `Host`/`Origin` hosts case-insensitively. - `AdminRoute` closed enum: no IPC surface accepts arbitrary URLs, so the NIP-98-signed URL is byte-identical to the fetched URL. - Dedicated no-redirect `reqwest` client as an SSRF guard: a relay `3xx` is an error and the NIP-98 header never crosses origins. - `admin_probe` signs `GET /probe` and returns a typed state (`nip98Authorized` / `nip98Denied` / `disabled` / `notAdminApi` / `networkOrIntercepted`). The response body is validated against the full relay contract — `nip98Authorized` only when the complete NIP-98 invariant holds, `disabled` only on a coherent disabled-mode body; any incoherent or unrelated JSON classifies as `notAdminApi`, so the console never fails open at the network boundary. Unknown fields are tolerated for forward compatibility. - NIP-98 signing via `AppState::signing_keys()`, one retry on `401` with a fresh signed event; response size bounded by a `Content-Length` preflight and a streaming byte counter; per-pubkey origin storage with atomic `0o600` writes. ## Relay admin console The console is gated behind the relay `OPERATOR`/`MODERATOR` roles from #3777; every `/api/admin/v1/*` route returns `403` to anyone else. Community self-administration (`community-members` / Invites) and in-channel enforcement (the 9040–9043 signed commands) are a separate axis and are untouched. The previously-duplicate community report queue (`ModerationQueueCard`, `moderationQueue.ts`, and three dead hooks) was unreachable dead code and is deleted in its own commit; `useBanMemberMutation` and the rest of `features/moderation/hooks.ts` remain in use by the members sidebar and message menu. ## Console UI (TypeScript, `src/features/admin-console/`) - `AdminConsoleSettingsCard`: discovery + probe flow, honest copy for every probe state, manual origin under an `Advanced` disclosure at the bottom. The role (operator/moderator) is rendered in the connection status line as plain text ("Connected as operator") — no badge-shaped elements above the tab row. The origin provenance (relay config / database) appears inside the Advanced card as small muted text. Section title changed to `Admin`. - `AdminConsolePanel` with Reports / Feedback / Staffing tabs (Staffing gated on `role === "operator"`); reports and feedback grouped by community for cross-community triage. - **Reports**: always requests `scope=all` so the existing resolve/cancel/reopen controls can reach every status (`open`, `processing`, `resolved`, `dismissed`, `escalated`). The relay's omitted-scope default is `escalated`-only (the platform-safety backstop); `scope=all` is explicit and scoped to this console. Full action matrix per `target_kind` (event → delete/kick/ban/timeout/dismiss/escalate; pubkey → ban/timeout/dismiss/escalate; blob → dismiss/escalate); kick is suppressed when the report carries no `channelId`. A `processing` row stays navigable — enforcement state lives in the detail view. A `failed` action (always pre-mutation) offers a single **Cancel & reopen** via `POST /reports/{id}/cancel` with `{actionId}` fencing; there is no client-side retry. `pending`/`enforcing` actions belong to the relay recovery worker and offer no button; a `409` reloads detail. Lists refetch on back-navigation after a mutation. - **Report failure UX**: `reportErrorMessage()` strips 4xx/5xx status prefixes and surfaces the relay's own error reason in the toast (e.g. relay returns `"400: you cannot report this content"` → toast shows `"you cannot report this content"`). Self-report blocking UI removed — the relay has no self-report gate, and the failure was purely client-side error surfacing. - **Reason audience disclosure**: the Reason (optional) field shows exact copy under the input based on selected action — Delete discloses that reason is sent verbatim to the affected user and posted publicly in the room; Kick/Ban/Timeout disclose affected-user only; Dismiss/Escalate disclose reporter only. These mirror the actual relay notice paths. - **Enforcement history**: the report detail carries the governing action even after the report leaves `processing` — a report enforced then reopened is `open` yet still shows its `succeeded` action as executed history alongside the resolve form; a reopen does not un-happen a ban. The resolve form gates on `open` status alone. - **Reopen**: terminal reports (`resolved`/`dismissed`/`escalated`) can be returned to `open` for re-triage via `POST /reports/{id}/reopen`. Reopen never reverses applied enforcement, and the copy says so. - **Feedback**: list, detail, and status control (`new`/`reviewed`/`archived`) with a generation-fenced attachment viewer. A purged source community severs provenance to `null` rather than deleting the row; severed rows bucket under a "source community removed" heading. - **Staffing**: Add is create-only with display names resolved via `useUsersBatchQuery` and npub cross-fade on hover (`HoverStaffingIdentity`). An entered key that already appears in the authoritative roster (config, owner-fallback, or DB) is rejected locally with an inline duplicate-key message and no request is issued; a `409 Conflict` from add, role change, or remove surfaces the relay's parsed error body via `adminErrorMessage(e)` — distinguishing config-backed key conflicts from last-operator conflicts without HTTP-status inference. Roster with `config`/`owner_fallback`/`db` source labels; config-backed entries disable remove client-side. In-place role change via `<select>` calling `putAdminOperator`; the relay responds with the effective `OperatorEntry` (`pubkey`, `effectiveRole`, `sources`) in the same shape as the roster list. Read-only badge for config-managed entries. - **Timeout expiry**: `useTimeoutState` clears the store when derived state is `INACTIVE` but the store is still active; the 1s tick is scoped to entries with a known `expiresAtMs` and owned by `ComposerTimeoutBanner` (mounted only while a timeout is active), while `ChannelPane` subscribes to the boolean `useTimeoutActive()` — the pane re-renders when a timeout starts or ends, not every second. `useMembersSidebarModeration` ticks `nowMs` only while the sidebar is open, the viewer can moderate, and some member has a future `mutedUntil`; the tick after the last expiry stops the interval. - Staffing refreshes the principal after a self-demotion or self-removal: `AdminConsolePanel` passes `onSelfMutation` to `StaffingTab`, which re-probes the saved origin so the role badge and tab visibility update without a manual re-probe. - Staffing mutation failures, including both 409 variants (config-backed key vs. last operator), surface the relay's parsed error via `adminErrorMessage`, so the last-operator recovery guidance is shown. - Mutations confirm via `sonner` toasts; failures surface the relay's parsed error `message`, not raw JSON. The `disabled` auth mode renders read-only. ## Mutation idempotency Resolve and reopen carry a per-attempt `requestId`. On first submit the whole command (`{requestId, action, reason, expirationSecs}`) is frozen; after an ambiguous failure (409, 5xx, transport error, truncated response) the snapshot is retained, action/reason/duration controls are locked, and the retry sends the exact same payload byte-for-byte. A definitive pre-commit rejection (non-409 4xx with `bodyComplete: true`) discards the snapshot, unlocks controls, and the corrected submit uses a fresh payload. On success the toast derives from the authoritative `AdminReportResolution` (`activeAction.action` when present; otherwise `status` for decision-only outcomes) — never from the mutable form selection. The native mutation commands — including operator delete — reject with a typed `AdminMutationError` carrying the relay's HTTP status (`relayStatus`, `null` when no verdict exists) and a `bodyComplete` flag that is `true` only when the full response body was read. ## Restriction routes contract change `GET /members/restrictions` and `DELETE /members/{pubkey}/ban|timeout` now take `communityHost` instead of `communityId`; the relay resolves the tenant itself and returns `400 unknown_community_host` for an unmapped host. This is a breaking contract change with no compatibility shim: the relay must run this build before a desktop that uses it, scripts sending `communityId` must switch, and rolling the relay back breaks the desktop Restrictions UI. `docs/admin/README.md` documents the three routes in the route inventory and carries the migration note. Restriction calls also carry the relay the list was loaded from, and the native side rejects a mismatch before building any URL. ## Hardening - Saved admin origins are stored per pubkey and per relay host. The host slug parses the relay URL, keeps the port-drop for DNS names, and encodes IPv6 hosts canonically, so two IPv6 relays never share a file and no IPv6 slug can match a DNS slug. - NIP-11 admin discovery has its own 10s request deadline and reads `/info` success and error bodies through the bounded reader with a 64 KiB cap (`Content-Length` is only a pre-check). - `PUT /operators` builds its `OperatorEntry` response from the validated body (`effectiveRole = role`, `sources = ["db"]`) instead of re-reading the roster, so a concurrent change can't turn a committed write into a `403`. Related: #3777 (relay `OPERATOR`/`MODERATOR` role model + NIP-98 auth + `admin_api` NIP-11 advertisement — provides the runtime and the discovery field this console consumes) Related: [builderbot-platform-core-infrastructure#140](squareup/builderbot-platform-core-infrastructure#140) (prod admin ingress allowlist and NIP-98 rollout) ## Screenshots Captured headless at `197f0ba0c` against the mock bridge (1280×720). ### Setup **Origin setup — Advanced disclosure open, idle state** ![Relay admin panel with Advanced: admin origin disclosure open before probe](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/02-origin-setup.png) **Authorized console — all three tabs** ![Authorized relay console showing Connected as operator status and Reports/Feedback/Staffing tabs](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/03-origin-authorized.png) ### Reports **Reports queue — open, processing, resolved across two relay groups** ![Reports tab showing community-grouped list with spam/open, harassment/processing, illegal/resolved rows](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/04-reports-queue.png) **Open report detail — reporter, target, message snapshot, resolve form** ![Open spam report detail with reported message content and Delete/Kick/Ban/Timeout/Dismiss/Escalate action buttons](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/05-report-detail-open.png) **Processing report — PROCESSING/HARASSMENT, ban enforcing state** ![Processing harassment report detail showing enforcement state with ban action in enforcing status](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/06-report-enforcement.png) **Resolve form — Delete selected, audience disclosure copy** ![Resolve form with Delete action selected showing "Sent verbatim to the affected user and posted publicly in the room" audience copy](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/07-resolve-form.png) **Resolved report — enforcement history block** ![Resolved/illegal report detail showing Resolved by, Resolved at, and Act ID fields from completed enforcement](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/08-resolved-history.png) ### Feedback **Feedback list — community grouping with status badges** ![Feedback tab showing relay.example.com group with new/reviewed items and source-community-removed group](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/09-feedback-list.png) **Feedback detail — mutable status control (operator mode)** ![Feedback detail with new/reviewed/archived status tab control visible for mutation](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/10-feedback-mutable.png) **Feedback detail — passive status badge (read-only/disabled mode)** ![Feedback detail in disabled mode showing passive "Status NEW" badge with no mutation control](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/11-feedback-readonly.png) ### Staffing **Staffing roster — config/owner\_fallback/db source labels** ![Staffing tab showing three operators with config, owner_fallback, and db source labels](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/12-staffing-roster.png) **Add form — new pubkey filled, ready to submit** ![Staffing add form with a new 64-hex pubkey entered and moderator role selected](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/13-staffing-add.png) **Duplicate rejection — inline error for existing principal** ![Staffing add form showing "Already an operator: operator. Use Remove to revoke before re-adding with a different role." error for an existing config-backed operator](https://raw.githubusercontent.com/block/buzz/f92559f9fab694b51afd60fdf76cb276de2fa830/docs/pr4768/14-staffing-dup.png) --------- Signed-off-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]> Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Signed-off-by: Alia <d32955ad69077062930cc46cfe2df30ca9aaf6f8e76422681265e9e9af704d78@buzz.block.builderlab.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Alia <d32955ad69077062930cc46cfe2df30ca9aaf6f8e76422681265e9e9af704d78@buzz.block.builderlab.xyz>
1 parent 28a8b90 commit 8f8c4df

64 files changed

Lines changed: 19240 additions & 1314 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎crates/buzz-db/src/store/admin_moderation.rs‎

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ pub struct AdminReport {
3838
pub target_kind: String,
3939
/// Hex target identifier.
4040
pub target: String,
41+
/// Author of the reported event when `target_kind` is `"event"` and the
42+
/// event is stored (deleted events included), so a list row can name the
43+
/// reported person without a per-report detail read.
44+
pub target_author_pubkey: Option<String>,
4145
/// Optional channel.
4246
pub channel_id: Option<Uuid>,
4347
/// NIP-56 report category.
@@ -195,9 +199,19 @@ pub async fn list_reports(
195199
r.report_event_id, r.reporter_pubkey, r.target_kind,
196200
r.target_event_id, r.target_pubkey, r.target_blob_sha256,
197201
r.channel_id, r.report_type, r.note, r.status, r.resolved_by,
198-
r.resolved_at, r.action_id, r.created_at
202+
r.resolved_at, r.action_id, r.created_at,
203+
target.pubkey AS target_author_pubkey
199204
FROM moderation_reports r
200205
JOIN communities c ON c.id = r.community_id
206+
LEFT JOIN LATERAL (
207+
SELECT e.pubkey
208+
FROM events e
209+
WHERE r.target_kind = 'event'
210+
AND e.community_id = r.community_id
211+
AND e.id = r.target_event_id
212+
ORDER BY e.created_at DESC
213+
LIMIT 1
214+
) target ON TRUE
201215
WHERE ($1::uuid IS NULL OR r.community_id = $1)
202216
AND ($2::text IS NULL OR r.status = $2)
203217
AND ($3::text IS NULL OR r.report_type = $3)
@@ -233,6 +247,7 @@ pub async fn get_report(pool: &PgPool, report_id: Uuid) -> Result<Option<AdminRe
233247
r.channel_id, r.report_type, r.note, r.status, r.resolved_by,
234248
r.resolved_at, r.action_id, r.created_at,
235249
target.pubkey AS message_author_pubkey,
250+
target.pubkey AS target_author_pubkey,
236251
target.content AS message_content,
237252
target.created_at AS message_created_at,
238253
target.deleted_at AS message_deleted_at,
@@ -340,6 +355,9 @@ fn row_to_report(row: sqlx::postgres::PgRow) -> Result<AdminReport> {
340355
reporter_pubkey: hex::encode(row.try_get::<Vec<u8>, _>("reporter_pubkey")?),
341356
target_kind,
342357
target: hex::encode(target),
358+
target_author_pubkey: row
359+
.try_get::<Option<Vec<u8>>, _>("target_author_pubkey")?
360+
.map(hex::encode),
343361
channel_id: row.try_get("channel_id")?,
344362
report_type: row.try_get("report_type")?,
345363
note: row.try_get("note")?,
@@ -628,6 +646,67 @@ mod postgres_tests {
628646
.expect("delete community fixtures");
629647
}
630648

649+
#[tokio::test]
650+
#[ignore = "requires Postgres"]
651+
async fn list_reports_names_same_community_event_author_including_deleted() {
652+
let pool = setup_pool().await;
653+
let report_community = insert_community(&pool, "list-author").await;
654+
let other_community = insert_community(&pool, "list-author-other").await;
655+
let event_id = vec![2_u8; 32];
656+
insert_event(
657+
&pool,
658+
report_community,
659+
&event_id,
660+
&[5_u8; 32],
661+
"gone",
662+
Some(Utc::now()),
663+
)
664+
.await;
665+
insert_event(
666+
&pool,
667+
other_community,
668+
&event_id,
669+
&[6_u8; 32],
670+
"wrong tenant",
671+
None,
672+
)
673+
.await;
674+
let event_report = insert_event_report(&pool, report_community, &event_id).await;
675+
let pubkey_report = insert_pubkey_report(&pool, report_community).await;
676+
677+
let reports = list_reports(
678+
&pool,
679+
Some(report_community),
680+
None,
681+
None,
682+
None,
683+
None,
684+
None,
685+
None,
686+
50,
687+
)
688+
.await
689+
.expect("list reports");
690+
let author_of = |id: Uuid| {
691+
reports
692+
.iter()
693+
.find(|r| r.id == id)
694+
.expect("report listed")
695+
.target_author_pubkey
696+
.clone()
697+
};
698+
assert_eq!(author_of(event_report), Some(hex::encode([5_u8; 32])));
699+
assert_eq!(author_of(pubkey_report), None);
700+
701+
sqlx::query("DELETE FROM events WHERE community_id = ANY($1)")
702+
.bind(vec![report_community, other_community])
703+
.execute(&pool)
704+
.await
705+
.expect("delete event fixtures");
706+
delete_report_fixture(&pool, report_community).await;
707+
delete_report_fixture(&pool, other_community).await;
708+
}
709+
631710
#[tokio::test]
632711
#[ignore = "requires Postgres"]
633712
async fn report_detail_has_no_message_for_non_event_target() {

‎crates/buzz-relay/src/api/admin/auth.rs‎

Lines changed: 55 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -96,14 +96,23 @@ pub(crate) fn admin_source_str(source: &AdminSource) -> &'static str {
9696
}
9797
}
9898

99+
/// Compare an inbound Host against the configured admin host case-insensitively.
100+
/// Host names are case-insensitive (RFC 3986 §6.2.2.1), and `config.host` is
101+
/// already lowercased at config load — but a proxy, curl, or non-desktop client
102+
/// can still send a mixed-case Host header, so the comparison itself must fold
103+
/// case rather than relying on the inbound value already being lowercase.
104+
fn host_matches(inbound: &str, configured: &str) -> bool {
105+
inbound.eq_ignore_ascii_case(configured)
106+
}
107+
99108
pub(crate) fn is_admin_host(state: &AppState, headers: &HeaderMap) -> bool {
100109
let Some(config) = state.config.admin.as_ref() else {
101110
return false;
102111
};
103112
headers
104113
.get(header::HOST)
105114
.and_then(|value| value.to_str().ok())
106-
.is_some_and(|host| host == config.host)
115+
.is_some_and(|host| host_matches(host, &config.host))
107116
}
108117

109118
/// Scheme for an admin authority: `http://` for loopback hosts (`localhost`,
@@ -443,19 +452,47 @@ fn nostr_credential(value: &str) -> Option<&str> {
443452
}
444453

445454
fn origin_matches_host(origin: &str, host: &str) -> bool {
446-
// Compare against the exact canonical origin: https:// for non-loopback,
447-
// http:// for loopback. Accepting either scheme for non-loopback would
448-
// allow plaintext origins for production hosts.
449-
let expected = format!("{}://{host}", scheme_for_host(host));
450-
origin == expected
455+
// The scheme is matched exactly — https:// for non-loopback, http:// for
456+
// loopback. Accepting either scheme for non-loopback would allow plaintext
457+
// origins for production hosts, so the scheme check must not fold anything.
458+
// The host portion, by contrast, is case-insensitive (RFC 3986 §6.2.2.1)
459+
// and may arrive mixed-case from a browser, so it folds case.
460+
let Some(origin_host) = origin
461+
.strip_prefix(scheme_for_host(host))
462+
.and_then(|rest| rest.strip_prefix("://"))
463+
else {
464+
return false;
465+
};
466+
origin_host.eq_ignore_ascii_case(host)
451467
}
452468

453469
#[cfg(test)]
454470
mod tests {
455471
use super::{
456-
admin_api_origin, canonical_url, method_has_body, nostr_credential, origin_matches_host,
472+
admin_api_origin, canonical_url, host_matches, method_has_body, nostr_credential,
473+
origin_matches_host,
457474
};
458475

476+
#[test]
477+
fn admin_host_compare_is_case_insensitive() {
478+
// config.host is lowercased at load, but a proxy/curl/non-desktop
479+
// client can still send a mixed-case Host header — it must match.
480+
assert!(host_matches(
481+
"Admin.Example.Com:8443",
482+
"admin.example.com:8443"
483+
));
484+
// Exact same-case is trivially a match.
485+
assert!(host_matches(
486+
"admin.example.com:8443",
487+
"admin.example.com:8443"
488+
));
489+
// A genuinely different host never matches.
490+
assert!(!host_matches(
491+
"attacker.example:8443",
492+
"admin.example.com:8443"
493+
));
494+
}
495+
459496
#[test]
460497
fn browser_origin_must_match_admin_host() {
461498
assert!(origin_matches_host(
@@ -492,6 +529,17 @@ mod tests {
492529
"https://admin.localhost:3000",
493530
"admin.localhost:3000"
494531
));
532+
// Host is case-insensitive (RFC 3986 §6.2.2.1): a mixed-case Origin
533+
// host matches the lowercased configured host, but the scheme is still
534+
// matched exactly (http rejected for a non-loopback host).
535+
assert!(origin_matches_host(
536+
"https://Admin.Example.Com",
537+
"admin.example.com"
538+
));
539+
assert!(!origin_matches_host(
540+
"http://Admin.Example.Com",
541+
"admin.example.com"
542+
));
495543
}
496544

497545
#[test]

0 commit comments

Comments
 (0)