Skip to content

Commit 836e7d0

Browse files
wpfleger96HaytDuncan
authored
feat(desktop): browse and moderate every community in the Admin Console (#8027)
The Admin Console only ever saw the community the desktop happened to be connected to. With #8011's community reads, the console can now browse every community on the relay and, for signed staff, moderate any of them by name without switching connections. 🤖 ## What changes - **Communities tab.** Lists every live community on the relay, searchable by host prefix with "Load more" paging. The connected community is pinned at the top by exact host match. Report rows get a community badge that opens that community. - **Community page.** Reports, Restrictions, Members and Actions, each scoped to the community on the page. The Actions form has no host field: it always acts on the page's community, and the TypeScript host normalization is gone from the Actions tab. - **Native reads** (`admin_list_communities`, `admin_search_members`, `admin_get_member`, `admin_get_event`). Every request validates the explicit community host and NIP-98-signs the real method and URL. Failures come back as a structured error (`status`, `bodyComplete`, `bodyEmpty`, `code`), so the UI can tell an older relay's empty 404, a coded `event_not_found` and a transport failure apart, and never says "not found" unless the relay did. - **Explicit-host lifts.** `admin_lift_restriction` sends the page's community host, not the active relay's. It freezes the relay and signer the intent was reviewed under, and refuses to send if either has changed. - **Pending actions survive navigation.** A panel-level `DirectActionsProvider` holds the frozen intent, so switching communities or tabs mid-confirm doesn't lose it. Only Discard drops it. A signer change remounts the controller and drops it. - **Fenced lookups.** Member and event lookups are keyed by origin, signer, community, target and a generation counter, so a late answer for one community can't unlock Review in another. - **Shared member picker** (`MemberSearchResult`, also used by Add Member), showing the truncated npub so members with the same name can be told apart. Delete accepts a note link and previews the message before Review. Relay staff are blocked before Review. - **Disabled admin auth is read-only.** With `BUZZ_ADMIN_AUTH=disabled` the Communities tab and community pages still render, and report badges still open them, but every ban, timeout, delete, add-member and lift control is disabled. The settings badge says the console is read-only and that acting needs `nip98`. Staffing stays hidden. - #7904's protections in the Actions tab are kept: frozen intent, `requestId`, Retry, `notSent` and the key-backup guard. - **Readable load errors.** Admin list and detail loads show the relay's error message (for example "request is not authorized"), never the raw JSON envelope. - **Failed kicks reload the report.** A resolve that fails with `enforcement_failed` reloads the report, so its failed action and "Cancel & reopen" appear immediately. - **Key backups never leave in a search.** Every admin API request URL passes the NIP-49 key-backup guard before it is signed or sent: community and legacy reads, mutations, the connection probe (before its first, unsigned request) and feedback-attachment fetches. The community and member search boxes, including the directory's Load more, refuse a pasted `nsec` or `ncryptsec` anywhere in the input without calling the relay. - **`just admin-seed` for multi-community testing.** Besides the local community, it seeds `beta.localhost:3000`, `gamma.localhost:3000` and 50 filler communities, with named members, a ban and a timeout in each named community, a report with Kick available, and a message for the delete preview. Rerunning it restores all of that to the starting state. It refuses, writing nothing, while a moderation action is unfinished on a seeded report. - The bodyless `GET /events/{id}` preview is added to the events-URL egress inventory. It sends no body, so it carries no key material. ## Tests Native (Rust): - `empty_404_and_405_read_as_complete_and_empty`, `coded_404_carries_the_relay_code`, `truncated_and_over_cap_bodies_are_incomplete`, `transport_failure_has_no_status`: the structured read error tells an older relay, a coded refusal, a cut-off body and a transport failure apart. - `a_401_retry_is_signed_by_the_same_keys`, `lift_signs_the_send_and_401_retry_with_the_checked_keys`: the 401 retry never switches keys. - `read_urls_validate_the_explicit_host_and_encode_the_query`, `lift_url_sends_the_page_host_not_the_active_relay`, `list_url_carries_host_and_cursor_and_refuses_a_changed_relay`, `lift_refuses_before_sending_on_signer_change_or_bad_host`: requests target the explicit host and refuse to send after a relay or signer change. jsdom: - `actions-pending-nav`: a pending intent survives a community change, and only Discard drops it. - `actions-fenced-lookup`, `fenced-load`: a late lookup for an old key never shows under, or unlocks, the new one. - `actions-same-ids`: the same pubkey and event id are read separately in each community. - `actions-community-change-drops-member`, `actions-page-host`, `actions-success`, `actions-identity`: the form acts only in the page's community, and confirm sends the frozen intent. - `actions-preview-errors`, `actions-delete-link`, `actions-staff-target`, `actions-disabled-auth`: preview errors, delete by note link, the staff block, and community pages rendering read-only with every action control disabled under disabled admin auth. - `communities-directory`, `communities-unsupported`, `community-badge`, `community-badge-disabled-auth`: the directory, older relays, and report badges, which open community pages under disabled admin auth too. - `restrictions-lift-signer-change`. The existing restriction tests now run on the community page and use `admin_lift_restriction`. Mutation checks: removing the pending-navigation guard turns `actions-pending-nav` red, and dropping the host from the fence key turns `actions-fenced-lookup`, `actions-same-ids` and `fenced-load` red. Ungating restriction lifts on `canMutate` turns `actions-disabled-auth` red. --------- Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent a918e60 commit 836e7d0

41 files changed

Lines changed: 4232 additions & 1251 deletions

Some content is hidden

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

‎desktop/src-tauri/src/commands/admin/attachment.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ pub(super) async fn fetch_feedback_attachment(
4545
},
4646
&routes::AdminQuery::default(),
4747
);
48+
crate::egress_guard::assert_no_key_backup(&url, "admin API request URL")?;
4849
let http_client = client::ADMIN_CLIENT
4950
.get()
5051
.ok_or_else(|| "admin client not initialised".to_string())?;

‎desktop/src-tauri/src/commands/admin/error.rs‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ pub struct AdminMutationError {
3838
pub body_complete: bool,
3939
/// Refused before sending; see the type docs.
4040
pub not_sent: bool,
41+
/// The complete error body had zero bytes: a relay without the route
42+
/// answers this way. Derived from the received bytes, never the message.
43+
pub body_empty: bool,
4144
}
4245

4346
impl AdminMutationError {
@@ -51,12 +54,17 @@ impl AdminMutationError {
5154

5255
/// The relay answered with an HTTP status and its full body was read — an
5356
/// authoritative verdict.
54-
pub(super) fn authoritative(status: reqwest::StatusCode, message: String) -> Self {
57+
pub(super) fn authoritative(
58+
status: reqwest::StatusCode,
59+
message: String,
60+
body_empty: bool,
61+
) -> Self {
5562
Self {
5663
message,
5764
relay_status: Some(status.as_u16()),
5865
body_complete: true,
5966
not_sent: false,
67+
body_empty,
6068
}
6169
}
6270

@@ -68,6 +76,7 @@ impl AdminMutationError {
6876
relay_status: Some(status.as_u16()),
6977
body_complete: false,
7078
not_sent: false,
79+
body_empty: false,
7180
}
7281
}
7382
}
@@ -81,6 +90,48 @@ impl From<String> for AdminMutationError {
8190
relay_status: None,
8291
body_complete: false,
8392
not_sent: false,
93+
body_empty: false,
94+
}
95+
}
96+
}
97+
98+
/// Error from a staff read command (`/communities`, `/members/...`,
99+
/// `/events/{id}`), keeping what the UI needs to tell "this relay has no such
100+
/// route" (complete empty 404/405), "not in this community" (a coded 404) and
101+
/// "unknown" (truncated body or no answer) apart without reading the message.
102+
#[derive(Debug, PartialEq, serde::Serialize)]
103+
#[serde(rename_all = "camelCase")]
104+
pub struct AdminReadError {
105+
pub message: String,
106+
/// The relay's HTTP status; `None` when no response arrived.
107+
pub relay_status: Option<u16>,
108+
/// Whether the whole error body was read.
109+
pub body_complete: bool,
110+
/// The complete body had zero bytes (false whenever it is incomplete).
111+
pub body_empty: bool,
112+
/// The relay envelope's `error.code`, when the complete body carried one.
113+
pub code: Option<String>,
114+
}
115+
116+
impl AdminReadError {
117+
/// The relay answered but its body was not fully read.
118+
pub(super) fn partial(status: reqwest::StatusCode, message: String) -> Self {
119+
Self {
120+
relay_status: Some(status.as_u16()),
121+
..Self::from(message)
122+
}
123+
}
124+
}
125+
126+
/// Pre-send and transport failures: no relay answer.
127+
impl From<String> for AdminReadError {
128+
fn from(message: String) -> Self {
129+
Self {
130+
message,
131+
relay_status: None,
132+
body_complete: false,
133+
body_empty: false,
134+
code: None,
84135
}
85136
}
86137
}

‎desktop/src-tauri/src/commands/admin/helpers.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ pub(super) async fn fetch_admin_json(
1414
) -> Result<Vec<u8>, String> {
1515
use crate::relay::build_nip98_auth_header_for_keys;
1616

17+
crate::egress_guard::assert_no_key_backup(url, "admin API request URL")?;
1718
let keys = state.signing_keys()?;
1819
let http_client = client::ADMIN_CLIENT
1920
.get()
@@ -163,6 +164,9 @@ pub(super) async fn send_admin_mutation(
163164
/// [`crate::relay::build_nip98_auth_header_for_keys`]), which is why the
164165
/// 401-retry re-invokes this rather than resending the first request.
165166
///
167+
/// The URL passes the key-backup egress guard before signing: the NIP-98
168+
/// header embeds it, and admin searches put typed text in its query.
169+
///
166170
/// State-free (`&Client` + `&Keys`) so the wire shape is unit-testable without
167171
/// a running Tauri app.
168172
pub(super) fn build_admin_mutation_request(
@@ -172,6 +176,7 @@ pub(super) fn build_admin_mutation_request(
172176
url: &str,
173177
body: Option<&[u8]>,
174178
) -> Result<reqwest::RequestBuilder, String> {
179+
crate::egress_guard::assert_no_key_backup(url, "admin API request URL")?;
175180
let auth_header =
176181
crate::relay::build_nip98_auth_header_for_keys(keys, method, url, body.unwrap_or(&[]))
177182
.map_err(|e| format!("nip98 build failed: {e}"))?;
@@ -378,6 +383,7 @@ async fn read_admin_mutation_response(
378383
return Err(AdminMutationError::authoritative(
379384
status,
380385
format!("admin API error: {body}"),
386+
bytes.is_empty(),
381387
));
382388
}
383389

‎desktop/src-tauri/src/commands/admin/mod.rs‎

Lines changed: 11 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,16 @@ use helpers::{
5858
pub(crate) mod error;
5959

6060
mod attachment;
61+
#[cfg(test)]
62+
mod read_stub;
63+
mod reads;
64+
mod restrictions;
6165
pub use error::AdminMutationError;
66+
pub use reads::{
67+
admin_connected_community_host, admin_get_event, admin_get_member, admin_list_communities,
68+
admin_search_members,
69+
};
70+
pub use restrictions::{admin_lift_restriction, admin_list_restrictions};
6271

6372
// ── Typed probe result ────────────────────────────────────────────────────
6473

@@ -159,6 +168,7 @@ async fn admin_probe_inner(
159168
) -> Result<AdminProbeResult, String> {
160169
let origin = origin::AdminOrigin::parse(origin)?;
161170
let url = origin.route_url(&routes::AdminRoute::Probe, &routes::AdminQuery::default());
171+
crate::egress_guard::assert_no_key_backup(&url, "admin API request URL")?;
162172

163173
let http_client = client::ADMIN_CLIENT
164174
.get()
@@ -465,6 +475,7 @@ pub async fn admin_list_reports(
465475
scope: query.scope,
466476
cursor: None,
467477
community_host: None,
478+
q: None,
468479
};
469480
let url = origin.route_url(&routes::AdminRoute::ReportsList, &q);
470481
let bytes = fetch_admin_json(&url, SUCCESS_JSON_CAP, &state).await?;
@@ -747,121 +758,6 @@ pub async fn admin_save_attachment(
747758
.await
748759
}
749760

750-
// ── Member restrictions ───────────────────────────────────────────────────
751-
752-
/// Shown by the UI when a restriction call targets a relay other than the one
753-
/// its list loaded from.
754-
const RELAY_SCOPE_CHANGED: &str =
755-
"active community changed since restrictions loaded; nothing was sent. Reload to continue.";
756-
757-
/// Build a restrictions-route URL scoped to the active relay's community.
758-
///
759-
/// The community is named by the active relay's host authority — the same
760-
/// `relay_url_authority` the relay's own connection binding uses — so the relay
761-
/// resolves its tenant. The desktop's local community ids are never sent.
762-
///
763-
/// `expected_relay` is the relay the caller's restriction list loaded from. The
764-
/// native relay is read once; if it no longer matches, the call fails before
765-
/// any request so a workspace switch cannot retarget a page or removal.
766-
fn restrictions_url(
767-
origin: &str,
768-
route: &routes::AdminRoute,
769-
cursor: Option<String>,
770-
expected_relay: &str,
771-
state: &crate::app_state::AppState,
772-
) -> Result<String, String> {
773-
let origin = origin::AdminOrigin::parse(origin)?;
774-
let relay_base = crate::relay::relay_api_base_url_with_override(state);
775-
if expected_relay.trim().is_empty()
776-
|| crate::relay::assert_expected_relay_scope(Some(expected_relay), &relay_base).is_err()
777-
{
778-
return Err(RELAY_SCOPE_CHANGED.to_string());
779-
}
780-
let host = buzz_core_pkg::tenant::relay_url_authority(&relay_base);
781-
if host.is_empty() {
782-
return Err("admin_community_host_unresolved".to_string());
783-
}
784-
let q = routes::AdminQuery {
785-
community_host: Some(host),
786-
cursor,
787-
..Default::default()
788-
};
789-
Ok(origin.route_url(route, &q))
790-
}
791-
792-
/// List active bans and timeouts for the active relay's community —
793-
/// GET /api/admin/v1/members/restrictions?communityHost={host}[&cursor={token}].
794-
///
795-
/// Returns `{ items: [...], nextCursor: string|null }`. Pass the previous
796-
/// page's `nextCursor` as `cursor` to fetch the next page (relay page size 200).
797-
#[tauri::command]
798-
pub async fn admin_list_restrictions(
799-
origin: String,
800-
cursor: Option<String>,
801-
expected_relay: String,
802-
state: tauri::State<'_, crate::app_state::AppState>,
803-
) -> Result<serde_json::Value, String> {
804-
let url = restrictions_url(
805-
&origin,
806-
&routes::AdminRoute::MemberRestrictionsList,
807-
cursor,
808-
&expected_relay,
809-
&state,
810-
)?;
811-
let bytes = fetch_admin_json(&url, SUCCESS_JSON_CAP, &state).await?;
812-
serde_json::from_slice(&bytes).map_err(|e| format!("invalid JSON from relay: {e}"))
813-
}
814-
815-
/// Lift an active ban — DELETE /api/admin/v1/members/{pubkey}/ban?communityHost={host}.
816-
///
817-
/// Returns 204 on success, 409 when no active ban exists for this member.
818-
/// A 409 is surfaced as an `AdminMutationError` so the UI can handle it
819-
/// gracefully ("no active ban").
820-
#[tauri::command]
821-
pub async fn admin_lift_ban(
822-
origin: String,
823-
pubkey: String,
824-
expected_relay: String,
825-
state: tauri::State<'_, crate::app_state::AppState>,
826-
) -> Result<(), AdminMutationError> {
827-
let pubkey =
828-
routes::Hex64::parse(&pubkey).map_err(|e| format!("invalid member pubkey: {e}"))?;
829-
let url = restrictions_url(
830-
&origin,
831-
&routes::AdminRoute::MemberBanDelete { pubkey },
832-
None,
833-
&expected_relay,
834-
&state,
835-
)?;
836-
// 204 No Content: empty body is the success signal. delete_admin_json
837-
// returns Ok(vec![]) for 204; we discard the bytes and return ().
838-
let _bytes = delete_admin_json(&url, SUCCESS_JSON_CAP, &state).await?;
839-
Ok(())
840-
}
841-
842-
/// Lift an active timeout — DELETE /api/admin/v1/members/{pubkey}/timeout?communityHost={host}.
843-
///
844-
/// Returns 204 on success, 409 when no active timeout exists for this member.
845-
#[tauri::command]
846-
pub async fn admin_lift_timeout(
847-
origin: String,
848-
pubkey: String,
849-
expected_relay: String,
850-
state: tauri::State<'_, crate::app_state::AppState>,
851-
) -> Result<(), AdminMutationError> {
852-
let pubkey =
853-
routes::Hex64::parse(&pubkey).map_err(|e| format!("invalid member pubkey: {e}"))?;
854-
let url = restrictions_url(
855-
&origin,
856-
&routes::AdminRoute::MemberTimeoutDelete { pubkey },
857-
None,
858-
&expected_relay,
859-
&state,
860-
)?;
861-
let _bytes = delete_admin_json(&url, SUCCESS_JSON_CAP, &state).await?;
862-
Ok(())
863-
}
864-
865761
// ── Direct moderation actions ─────────────────────────────────────────────
866762

867763
/// A direct ban, timeout, or delete as the confirm dialog froze it. The same

0 commit comments

Comments
 (0)