Skip to content

Commit 8db239b

Browse files
npub1jmc9dt2lyvzu3h0kxlwxt5zg4fxp9476awyxw6gwxn72g6cw7exqs64whmTyler Longwell
andcommitted
moderation(L6): command handler (9040-9044) + mod-queue read endpoints
Phase-1 community moderation lane L6: the moderation command dispatch and the three HTTP read endpoints that back the mod queue. Command handler (handlers/moderation_commands.rs), kinds 9040-9044: - 9040 ban, 9041 unban, 9042 timeout, 9043 untimeout, 9044 resolve-report. - Every command routes authorization through the single `authorize_moderation_action` capability helper (L2) — never an inline role check — then performs its DB write (L1), records the audit row, and best-effort sends the relay-signed notice DM (L5). - Freshness gate rejects stale/replayed commands (never stored). - 9040 ban drives live enforcement via the paired `AppState::disconnect_pubkey_clusterwide` (L4): one call closes this pod's fenced sockets and fans the disconnect out cross-pod, so a live ban takes effect immediately, everywhere (decision 4). The DB ban row is the durable backstop for a dropped fan-out. Read endpoints (api/bridge.rs) + routes (router.rs): - GET /moderation/reports, /moderation/audit, /moderation/restricted. - Each mirrors the existing count_events shape: HOST-bound tenant, NIP-98 auth + replay check, then the mod-authz gate (ViewQueue) rather than plain relay membership. Reads resolve tenant-scoped rows (L1) only. Depends on L2's `authorize_moderation_action` body, still `todo!()` and human-gated: the authz-gated paths compile against the pinned signature but panic at runtime until L2 lands. Handler unit tests cover the pure helpers (tag parse, expiration vocab, report-tag validation) which do not hit authz. Validation on base 0bff742: fmt --check, check -p buzz-relay, clippy -p buzz-relay, test -p buzz-relay --lib all green (492 passed / 0 failed; 7 L6 handler tests included). git diff --check clean. Diff is three buzz-relay lane files only. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent 0bff742 commit 8db239b

3 files changed

Lines changed: 774 additions & 4 deletions

File tree

‎crates/buzz-relay/src/api/bridge.rs‎

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1635,6 +1635,178 @@ async fn synthesize_presence(
16351635
Some(events)
16361636
}
16371637

1638+
// ── Moderation queue reads (L6 — Quinn) ───────────────────────────────────────
1639+
//
1640+
// Mod-only structured rows (`moderation_reports`/`moderation_actions`/
1641+
// `community_bans`) are not nostr events, so they are served over dedicated
1642+
// NIP-98-authed GET endpoints rather than the REQ/`/query` path (which would
1643+
// force a synthetic event shape and thread a privileged branch onto the shared
1644+
// read hot path). Gated on `ModerationAction::ViewQueue` via the one capability
1645+
// helper — never an inline role check. Host-scoped: community from the request
1646+
// host, no channel context (queue reads are community-wide).
1647+
1648+
/// Shared prelude for a moderation read: bind tenant, verify NIP-98 GET auth,
1649+
/// replay-check, and confirm the caller may view the queue.
1650+
async fn authorize_moderation_read(
1651+
state: &Arc<AppState>,
1652+
headers: &HeaderMap,
1653+
path: &str,
1654+
) -> Result<TenantContext, (StatusCode, Json<Value>)> {
1655+
let raw_host = headers
1656+
.get(axum::http::header::HOST)
1657+
.and_then(|v| v.to_str().ok())
1658+
.unwrap_or("");
1659+
let tenant = crate::tenant::bind_community(&state.db, raw_host)
1660+
.await
1661+
.map_err(|_| {
1662+
api_error(
1663+
StatusCode::NOT_FOUND,
1664+
"relay: no community is configured for this host",
1665+
)
1666+
})?;
1667+
1668+
let url = nip98_expected_url(&state.config.relay_url, &tenant, path);
1669+
let (pubkey, event_id_bytes) =
1670+
verify_bridge_auth(headers, "GET", &url, None, state.config.require_auth_token)?;
1671+
check_nip98_replay(state, &tenant, event_id_bytes).await?;
1672+
let pubkey_bytes = pubkey.to_bytes().to_vec();
1673+
1674+
crate::handlers::moderation_authz::authorize_moderation_action(
1675+
&tenant,
1676+
state,
1677+
&pubkey_bytes,
1678+
None,
1679+
crate::handlers::moderation_authz::ModerationTarget::None,
1680+
crate::handlers::moderation_authz::ModerationAction::ViewQueue,
1681+
)
1682+
.await
1683+
.map_err(|_| {
1684+
api_error(
1685+
StatusCode::FORBIDDEN,
1686+
"restricted: moderator access required",
1687+
)
1688+
})?;
1689+
1690+
Ok(tenant)
1691+
}
1692+
1693+
/// Cap on rows returned by a single moderation read.
1694+
const MODERATION_READ_LIMIT: i64 = 500;
1695+
1696+
/// Optional `?status=` and `?limit=` query for moderation reads.
1697+
#[derive(serde::Deserialize, Default)]
1698+
pub struct ModerationReadQuery {
1699+
status: Option<String>,
1700+
limit: Option<i64>,
1701+
}
1702+
1703+
fn clamp_limit(requested: Option<i64>) -> i64 {
1704+
requested
1705+
.filter(|n| *n > 0)
1706+
.map(|n| n.min(MODERATION_READ_LIMIT))
1707+
.unwrap_or(MODERATION_READ_LIMIT)
1708+
}
1709+
1710+
/// `GET /moderation/reports` — the moderation queue (NIP-98 + mod-authz).
1711+
pub async fn moderation_reports(
1712+
State(state): State<Arc<AppState>>,
1713+
headers: HeaderMap,
1714+
Query(q): Query<ModerationReadQuery>,
1715+
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
1716+
let tenant = authorize_moderation_read(&state, &headers, "/moderation/reports").await?;
1717+
let rows = state
1718+
.db
1719+
.list_moderation_reports(
1720+
tenant.community(),
1721+
q.status.as_deref(),
1722+
clamp_limit(q.limit),
1723+
)
1724+
.await
1725+
.map_err(|e| internal_error(&format!("list reports: {e}")))?;
1726+
Ok(Json(Value::Array(rows.iter().map(report_json).collect())))
1727+
}
1728+
1729+
/// `GET /moderation/audit` — the moderation audit log (NIP-98 + mod-authz).
1730+
pub async fn moderation_audit(
1731+
State(state): State<Arc<AppState>>,
1732+
headers: HeaderMap,
1733+
Query(q): Query<ModerationReadQuery>,
1734+
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
1735+
let tenant = authorize_moderation_read(&state, &headers, "/moderation/audit").await?;
1736+
let rows = state
1737+
.db
1738+
.list_moderation_actions(tenant.community(), clamp_limit(q.limit))
1739+
.await
1740+
.map_err(|e| internal_error(&format!("list actions: {e}")))?;
1741+
Ok(Json(Value::Array(rows.iter().map(action_json).collect())))
1742+
}
1743+
1744+
/// `GET /moderation/restricted` — currently banned/timed-out members.
1745+
pub async fn moderation_restricted(
1746+
State(state): State<Arc<AppState>>,
1747+
headers: HeaderMap,
1748+
) -> Result<Json<Value>, (StatusCode, Json<Value>)> {
1749+
let tenant = authorize_moderation_read(&state, &headers, "/moderation/restricted").await?;
1750+
let rows = state
1751+
.db
1752+
.list_community_restrictions(tenant.community())
1753+
.await
1754+
.map_err(|e| internal_error(&format!("list restrictions: {e}")))?;
1755+
Ok(Json(Value::Array(rows.iter().map(ban_json).collect())))
1756+
}
1757+
1758+
fn report_json(r: &buzz_db::moderation::ReportRecord) -> Value {
1759+
let (target_kind, target) = match &r.target {
1760+
buzz_db::moderation::ReportTarget::Event(id) => ("event", hex::encode(id)),
1761+
buzz_db::moderation::ReportTarget::Pubkey(pk) => ("pubkey", hex::encode(pk)),
1762+
buzz_db::moderation::ReportTarget::Blob(sha) => ("blob", hex::encode(sha)),
1763+
};
1764+
serde_json::json!({
1765+
"id": r.id,
1766+
"report_event_id": hex::encode(&r.report_event_id),
1767+
"reporter_pubkey": hex::encode(&r.reporter_pubkey),
1768+
"target_kind": target_kind,
1769+
"target": target,
1770+
"channel_id": r.channel_id,
1771+
"report_type": r.report_type,
1772+
"note": r.note,
1773+
"status": r.status,
1774+
"resolved_by": r.resolved_by.as_ref().map(hex::encode),
1775+
"resolved_at": r.resolved_at,
1776+
"action_id": r.action_id,
1777+
"created_at": r.created_at,
1778+
})
1779+
}
1780+
1781+
fn action_json(a: &buzz_db::moderation::ActionRecord) -> Value {
1782+
serde_json::json!({
1783+
"id": a.id,
1784+
"actor_pubkey": hex::encode(&a.actor_pubkey),
1785+
"action": a.action,
1786+
"target_pubkey": a.target_pubkey.as_ref().map(hex::encode),
1787+
"target_event_id": a.target_event_id.as_ref().map(hex::encode),
1788+
"channel_id": a.channel_id,
1789+
"reason_code": a.reason_code,
1790+
"public_reason": a.public_reason,
1791+
"private_reason": a.private_reason,
1792+
"matched_principal": a.matched_principal,
1793+
"created_at": a.created_at,
1794+
})
1795+
}
1796+
1797+
fn ban_json(b: &buzz_db::moderation::BanRecord) -> Value {
1798+
serde_json::json!({
1799+
"pubkey": hex::encode(&b.pubkey),
1800+
"banned": b.banned,
1801+
"ban_expires_at": b.ban_expires_at,
1802+
"ban_reason": b.ban_reason,
1803+
"muted_until": b.muted_until,
1804+
"mute_reason": b.mute_reason,
1805+
"actor_pubkey": hex::encode(&b.actor_pubkey),
1806+
"updated_at": b.updated_at,
1807+
})
1808+
}
1809+
16381810
#[cfg(test)]
16391811
mod tests {
16401812
use super::*;

0 commit comments

Comments
 (0)