Skip to content

Commit 67373d9

Browse files
npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67dTyler Longwell
andcommitted
feat(moderation): Phase 1 contract scaffold — schema, kinds, module seams
Community moderation build (design: docs/moderation/PLAN.md, decisions locked by Tyler 2026-07-07). This commit pins the cross-lane contract: - migrations/0006_moderation.sql: moderation_reports (NIP-56 queue), community_bans (ban + muted_until timeout), moderation_actions (audit). All tenant-scoped, community_id-leading keys per the isolation lints. - buzz-core kinds: KIND_REPORT (1984), moderation commands 9040-9044. - buzz-db::moderation: persistence contract (signatures + row types). - buzz-relay handler seams: moderation_authz (capability helper), report (1984 ingest), moderation_commands (9040-9044 dispatch), moderation_notices (relay-signed DM notices). Bodies are todo!() stubs owned by implementation lanes; signatures are the interface. Reports are signals, never triggers (NIP-56); targets resolve under the requesting TenantContext only. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent c258ffc commit 67373d9

11 files changed

Lines changed: 953 additions & 1 deletion

File tree

‎crates/buzz-core/src/kind.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,14 @@ pub const KIND_TEAM: u32 = 30176;
173173
/// since these events are world-readable on the relay.
174174
pub const KIND_MANAGED_AGENT: u32 = 30177;
175175

176+
// NIP-56 reporting
177+
/// NIP-56: Report an event, pubkey, or blob to relay moderators (kind:1984).
178+
///
179+
/// Accepted at ingest, persisted to the tenant-scoped `moderation_reports`
180+
/// queue, and never fanned out publicly. Reports are signals, not triggers:
181+
/// the relay never auto-actions on them (NIP-56).
182+
pub const KIND_REPORT: u32 = 1984;
183+
176184
// NIP-29 group admin events
177185
/// NIP-29: Add a user to a group.
178186
pub const KIND_NIP29_PUT_USER: u32 = 9000;
@@ -193,6 +201,23 @@ pub const KIND_NIP29_JOIN_REQUEST: u32 = 9021;
193201
/// NIP-29: Request to leave a group.
194202
pub const KIND_NIP29_LEAVE_REQUEST: u32 = 9022;
195203

204+
// Buzz community moderation commands (mod-signed, processed like 9030-series:
205+
// validated + executed directly, never stored as regular events; every
206+
// accepted command writes a `moderation_actions` audit row).
207+
/// Moderation: ban a pubkey from the community (`p` tag target, optional
208+
/// `expiration` + `reason` tags).
209+
pub const KIND_MODERATION_BAN: u32 = 9040;
210+
/// Moderation: lift a community ban (`p` tag target).
211+
pub const KIND_MODERATION_UNBAN: u32 = 9041;
212+
/// Moderation: timeout (write-block) a pubkey until an `expiration` tag
213+
/// timestamp (`p` tag target, optional `reason`).
214+
pub const KIND_MODERATION_TIMEOUT: u32 = 9042;
215+
/// Moderation: clear a timeout early (`p` tag target).
216+
pub const KIND_MODERATION_UNTIMEOUT: u32 = 9043;
217+
/// Moderation: resolve a report queue row (`report` tag = row UUID,
218+
/// `status` tag = resolved|dismissed|escalated).
219+
pub const KIND_MODERATION_RESOLVE_REPORT: u32 = 9044;
220+
196221
// NIP-43 relay membership admin commands
197222
/// NIP-43: Add a pubkey to the relay member list.
198223
pub const RELAY_ADMIN_ADD_MEMBER: u32 = 9030;

‎crates/buzz-db/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ pub mod feed;
2727
pub mod git_repo;
2828
/// Embedded database migrations.
2929
pub mod migration;
30+
/// Community moderation: reports, bans/timeouts, audit actions.
31+
pub mod moderation;
3032
/// Monthly table partition management.
3133
pub mod partition;
3234
/// Reaction persistence.

‎crates/buzz-db/src/migration.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ mod tests {
471471
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
472472
migrations.sort_by_key(|migration| migration.version);
473473

474-
assert_eq!(migrations.len(), 5);
474+
assert_eq!(migrations.len(), 6);
475475
assert_eq!(migrations[0].version, 1);
476476
assert_eq!(&*migrations[0].description, "initial schema");
477477
assert!(migrations[0]
@@ -532,6 +532,23 @@ mod tests {
532532
assert!(migrations[4].sql.as_str().contains("search_tsv"));
533533
assert!(migrations[4].sql.as_str().contains("44200"));
534534
assert!(!migrations[0].sql.as_str().contains("44200"));
535+
536+
// Community moderation (reports/bans/audit): additive migration, never
537+
// folded into 0001 — same brownfield checksum rule as above.
538+
assert_eq!(migrations[5].version, 6);
539+
assert!(migrations[5]
540+
.sql
541+
.as_str()
542+
.contains("CREATE TABLE moderation_reports"));
543+
assert!(migrations[5]
544+
.sql
545+
.as_str()
546+
.contains("CREATE TABLE community_bans"));
547+
assert!(migrations[5]
548+
.sql
549+
.as_str()
550+
.contains("CREATE TABLE moderation_actions"));
551+
assert!(!migrations[0].sql.as_str().contains("moderation_reports"));
535552
}
536553

537554
#[test]

‎crates/buzz-db/src/moderation.rs‎

Lines changed: 291 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,291 @@
1+
//! Community moderation persistence (Phase 1 contract).
2+
//!
3+
//! Backs the NIP-56 report queue (`moderation_reports`), ban/timeout state
4+
//! (`community_bans`), and the moderation audit trail (`moderation_actions`)
5+
//! from `migrations/0006_moderation.sql`.
6+
//!
7+
//! ## Tenant invariant
8+
//! Every function takes a [`CommunityId`] and touches exactly one community's
9+
//! rows. Report/ban targets are resolved by callers under the requesting
10+
//! `TenantContext` **before** they reach this module — no function here may
11+
//! perform a cross-community or global lookup (MOD invariants,
12+
//! `docs/spec/MultiTenantRelay.tla`).
13+
//!
14+
//! Lane ownership: L1 (Max). Signatures below are the contract; changes go
15+
//! through the integration thread.
16+
17+
use chrono::{DateTime, Utc};
18+
use sqlx::PgPool;
19+
use uuid::Uuid;
20+
21+
use crate::error::Result;
22+
use crate::CommunityId;
23+
24+
/// What a report points at. Exactly one target class per report row.
25+
#[derive(Debug, Clone, PartialEq, Eq)]
26+
pub enum ReportTarget {
27+
/// `e`-tag target: an event that must resolve inside the tenant.
28+
Event(Vec<u8>),
29+
/// `p`-only target: a community-local report about a pubkey.
30+
Pubkey(Vec<u8>),
31+
/// `x`-tag target: a media blob sha256, resolved via tenant-scoped refs.
32+
Blob(Vec<u8>),
33+
}
34+
35+
/// Insert parameters for a new report row (from an accepted kind:1984 event).
36+
#[derive(Debug, Clone)]
37+
pub struct NewReport<'a> {
38+
/// Signed kind:1984 event id (32 bytes) — idempotency key per community.
39+
pub report_event_id: &'a [u8],
40+
/// Reporter pubkey bytes. Mod-queue-visible; never revealed to the author.
41+
pub reporter_pubkey: &'a [u8],
42+
/// Resolved (in-tenant) target.
43+
pub target: ReportTarget,
44+
/// Channel inferred from an in-tenant target event row, when resolvable.
45+
pub channel_id: Option<Uuid>,
46+
/// NIP-56 report type (already validated by ingest).
47+
pub report_type: &'a str,
48+
/// Reporter's optional free-text note.
49+
pub note: Option<&'a str>,
50+
}
51+
52+
/// A report row as read back for the moderation queue.
53+
#[derive(Debug, Clone)]
54+
pub struct ReportRecord {
55+
/// Row id (unique within the community).
56+
pub id: Uuid,
57+
/// Signed kind:1984 event id.
58+
pub report_event_id: Vec<u8>,
59+
/// Reporter pubkey bytes.
60+
pub reporter_pubkey: Vec<u8>,
61+
/// Report target.
62+
pub target: ReportTarget,
63+
/// Inferred channel, if the target resolved to one.
64+
pub channel_id: Option<Uuid>,
65+
/// NIP-56 report type.
66+
pub report_type: String,
67+
/// Reporter's note.
68+
pub note: Option<String>,
69+
/// `open` | `resolved` | `dismissed` | `escalated`.
70+
pub status: String,
71+
/// Resolving moderator, once resolved.
72+
pub resolved_by: Option<Vec<u8>>,
73+
/// Resolution timestamp.
74+
pub resolved_at: Option<DateTime<Utc>>,
75+
/// `moderation_actions` row that resolved this report.
76+
pub action_id: Option<Uuid>,
77+
/// Report creation time.
78+
pub created_at: DateTime<Utc>,
79+
}
80+
81+
/// Ban/timeout state for one member in one community.
82+
#[derive(Debug, Clone)]
83+
pub struct BanRecord {
84+
/// Member pubkey bytes.
85+
pub pubkey: Vec<u8>,
86+
/// Whether the member is currently banned (check `ban_expires_at`).
87+
pub banned: bool,
88+
/// Ban expiry; `None` while `banned` ⇒ permanent.
89+
pub ban_expires_at: Option<DateTime<Utc>>,
90+
/// Moderator-supplied ban reason (private).
91+
pub ban_reason: Option<String>,
92+
/// Write-block until this timestamp; `None` or past ⇒ not timed out.
93+
pub muted_until: Option<DateTime<Utc>>,
94+
/// Moderator-supplied timeout reason (private).
95+
pub mute_reason: Option<String>,
96+
/// Moderator who last modified this row.
97+
pub actor_pubkey: Vec<u8>,
98+
/// Last modification time.
99+
pub updated_at: DateTime<Utc>,
100+
}
101+
102+
/// Insert parameters for a moderation audit row.
103+
#[derive(Debug, Clone)]
104+
pub struct NewAction<'a> {
105+
/// Acting moderator pubkey bytes.
106+
pub actor_pubkey: &'a [u8],
107+
/// `delete_message` | `kick` | `ban` | `unban` | `timeout` | `untimeout`
108+
/// | `dismiss_report` | `escalate` (DB CHECK-enforced).
109+
pub action: &'a str,
110+
/// Actioned member, when the action targets a pubkey.
111+
pub target_pubkey: Option<&'a [u8]>,
112+
/// Actioned event, when the action targets an event.
113+
pub target_event_id: Option<&'a [u8]>,
114+
/// Channel context, when known.
115+
pub channel_id: Option<Uuid>,
116+
/// Machine-readable rule/reason code.
117+
pub reason_code: Option<&'a str>,
118+
/// Sanitized reason, safe for the public tombstone.
119+
pub public_reason: Option<&'a str>,
120+
/// Mod-only context; never leaves the audit surface.
121+
pub private_reason: Option<&'a str>,
122+
/// NIP-OA matched principal (`self` | `owner`) for ban enforcement audit.
123+
pub matched_principal: Option<&'a str>,
124+
}
125+
126+
/// An audit row as read back for `buzz moderation audit`.
127+
#[derive(Debug, Clone)]
128+
pub struct ActionRecord {
129+
/// Row id.
130+
pub id: Uuid,
131+
/// Acting moderator pubkey bytes.
132+
pub actor_pubkey: Vec<u8>,
133+
/// Action name.
134+
pub action: String,
135+
/// Actioned member.
136+
pub target_pubkey: Option<Vec<u8>>,
137+
/// Actioned event.
138+
pub target_event_id: Option<Vec<u8>>,
139+
/// Channel context.
140+
pub channel_id: Option<Uuid>,
141+
/// Machine-readable rule/reason code.
142+
pub reason_code: Option<String>,
143+
/// Sanitized public reason.
144+
pub public_reason: Option<String>,
145+
/// Mod-only reason.
146+
pub private_reason: Option<String>,
147+
/// Action time.
148+
pub created_at: DateTime<Utc>,
149+
}
150+
151+
/// Insert a new report row. Idempotent on `(community, report_event_id)`:
152+
/// re-ingesting the same signed report is a no-op returning the existing id.
153+
pub async fn insert_report(
154+
_pool: &PgPool,
155+
_community: CommunityId,
156+
_report: NewReport<'_>,
157+
) -> Result<Uuid> {
158+
todo!("L1 (Max): INSERT ... ON CONFLICT (community_id, report_event_id) DO NOTHING + return id")
159+
}
160+
161+
/// List reports for the moderation queue, newest first.
162+
/// `status = None` lists all; `Some("open")` etc. filters.
163+
pub async fn list_reports(
164+
_pool: &PgPool,
165+
_community: CommunityId,
166+
_status: Option<&str>,
167+
_limit: i64,
168+
) -> Result<Vec<ReportRecord>> {
169+
todo!("L1 (Max)")
170+
}
171+
172+
/// Fetch one report by row id.
173+
pub async fn get_report(
174+
_pool: &PgPool,
175+
_community: CommunityId,
176+
_report_id: Uuid,
177+
) -> Result<Option<ReportRecord>> {
178+
todo!("L1 (Max)")
179+
}
180+
181+
/// Mark a report resolved/dismissed/escalated, linking the audit action.
182+
/// Returns `false` if the report was not found or already closed.
183+
pub async fn resolve_report(
184+
_pool: &PgPool,
185+
_community: CommunityId,
186+
_report_id: Uuid,
187+
_status: &str,
188+
_resolved_by: &[u8],
189+
_action_id: Option<Uuid>,
190+
) -> Result<bool> {
191+
todo!("L1 (Max)")
192+
}
193+
194+
/// Upsert a ban: sets `banned = true` with optional expiry + reason.
195+
pub async fn ban_member(
196+
_pool: &PgPool,
197+
_community: CommunityId,
198+
_pubkey: &[u8],
199+
_actor: &[u8],
200+
_reason: Option<&str>,
201+
_expires_at: Option<DateTime<Utc>>,
202+
) -> Result<()> {
203+
todo!("L1 (Max): INSERT ... ON CONFLICT (community_id, pubkey) DO UPDATE")
204+
}
205+
206+
/// Lift a ban. Returns `false` if the member was not banned.
207+
pub async fn unban_member(
208+
_pool: &PgPool,
209+
_community: CommunityId,
210+
_pubkey: &[u8],
211+
_actor: &[u8],
212+
) -> Result<bool> {
213+
todo!("L1 (Max)")
214+
}
215+
216+
/// Upsert a timeout: sets `muted_until` + reason.
217+
pub async fn timeout_member(
218+
_pool: &PgPool,
219+
_community: CommunityId,
220+
_pubkey: &[u8],
221+
_actor: &[u8],
222+
_muted_until: DateTime<Utc>,
223+
_reason: Option<&str>,
224+
) -> Result<()> {
225+
todo!("L1 (Max)")
226+
}
227+
228+
/// Clear a timeout early. Returns `false` if the member was not timed out.
229+
pub async fn untimeout_member(
230+
_pool: &PgPool,
231+
_community: CommunityId,
232+
_pubkey: &[u8],
233+
_actor: &[u8],
234+
) -> Result<bool> {
235+
todo!("L1 (Max)")
236+
}
237+
238+
/// Restriction snapshot consumed by the auth-seam gate (L4) and write gates.
239+
///
240+
/// One cheap read per check: `banned` already accounts for expiry;
241+
/// `muted_until` is returned raw so the caller can render the timestamp in
242+
/// the `restricted:` message.
243+
#[derive(Debug, Clone, Default, PartialEq, Eq)]
244+
pub struct RestrictionState {
245+
/// Currently banned (row exists, `banned`, unexpired).
246+
pub banned: bool,
247+
/// Active timeout expiry, if in the future.
248+
pub muted_until: Option<DateTime<Utc>>,
249+
}
250+
251+
/// Fetch the current restriction state for a pubkey in one community.
252+
/// Missing row ⇒ `RestrictionState::default()` (unrestricted).
253+
pub async fn restriction_state(
254+
_pool: &PgPool,
255+
_community: CommunityId,
256+
_pubkey: &[u8],
257+
) -> Result<RestrictionState> {
258+
todo!("L1 (Max): single SELECT evaluating ban expiry + mute window in SQL")
259+
}
260+
261+
/// Fetch the full ban/timeout row (moderation queue / audit views).
262+
pub async fn get_ban(
263+
_pool: &PgPool,
264+
_community: CommunityId,
265+
_pubkey: &[u8],
266+
) -> Result<Option<BanRecord>> {
267+
todo!("L1 (Max)")
268+
}
269+
270+
/// List currently-restricted members (active ban or timeout) for the queue.
271+
pub async fn list_restricted(_pool: &PgPool, _community: CommunityId) -> Result<Vec<BanRecord>> {
272+
todo!("L1 (Max)")
273+
}
274+
275+
/// Insert a moderation audit row, returning its id.
276+
pub async fn insert_action(
277+
_pool: &PgPool,
278+
_community: CommunityId,
279+
_action: NewAction<'_>,
280+
) -> Result<Uuid> {
281+
todo!("L1 (Max)")
282+
}
283+
284+
/// List audit rows, newest first (`buzz moderation audit`).
285+
pub async fn list_actions(
286+
_pool: &PgPool,
287+
_community: CommunityId,
288+
_limit: i64,
289+
) -> Result<Vec<ActionRecord>> {
290+
todo!("L1 (Max)")
291+
}

‎crates/buzz-relay/src/handlers/mod.rs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,16 @@ pub mod imeta;
1616
pub mod ingest;
1717
/// Mesh hole-punch signaling: validate membership + emit paired call-me-now.
1818
pub mod mesh_signaling;
19+
/// Community moderation authorization seam (capability helper).
20+
pub mod moderation_authz;
21+
/// Community moderation command handler (kinds 9040–9044).
22+
pub mod moderation_commands;
23+
/// Relay-signed moderation notice DMs.
24+
pub mod moderation_notices;
1925
/// NIP-43 relay membership admin command handler (kinds 9030–9032).
2026
pub mod relay_admin;
27+
/// NIP-56 report (kind:1984) validation + moderation queue persistence.
28+
pub mod report;
2129
/// REQ handler — subscribe, deliver historical events, then EOSE.
2230
pub mod req;
2331
/// NIP-29 and NIP-25 side-effect handlers.

0 commit comments

Comments
 (0)