@@ -89,47 +89,34 @@ pub async fn handle_req(
8989 // #h presence to prevent mixed-filter bypass: a client could send
9090 // [{#h:..., kinds:[44100]}, {authors:[...]}] which resolves to global scope
9191 // but would skip the #p check if we only looked at per-filter #h tags.
92+ // Kinds that are globally stored and require #p = authed pubkey.
93+ // Without this, a client could subscribe to another user's membership
94+ // notifications or gift-wrapped DMs.
95+ const P_GATED_KINDS : [ u32 ; 3 ] = [
96+ KIND_MEMBER_ADDED_NOTIFICATION ,
97+ KIND_MEMBER_REMOVED_NOTIFICATION ,
98+ KIND_GIFT_WRAP ,
99+ ] ;
100+
92101 if channel_id. is_none ( ) {
93102 let authed_pubkey_hex = hex:: encode ( & pubkey_bytes) ;
94103 let p_tag = nostr:: SingleLetterTag :: lowercase ( nostr:: Alphabet :: P ) ;
95104
96105 for filter in & filters {
97- // Membership notifications (kind:44100/44101) require #p = authed pubkey.
98- let can_match_membership = filter. kinds . as_ref ( ) . is_none_or ( |ks| {
99- ks. iter ( ) . any ( |k| {
100- let ku = k. as_u16 ( ) as u32 ;
101- ku == KIND_MEMBER_ADDED_NOTIFICATION || ku == KIND_MEMBER_REMOVED_NOTIFICATION
102- } )
106+ let can_match_p_gated = filter. kinds . as_ref ( ) . is_none_or ( |ks| {
107+ ks. iter ( )
108+ . any ( |k| P_GATED_KINDS . contains ( & ( k. as_u16 ( ) as u32 ) ) )
103109 } ) ;
104- if can_match_membership {
110+ if can_match_p_gated {
105111 // ALL #p values must match the authenticated pubkey — prevents
106- // a client from sneaking in a victim's pubkey alongside their own
107- // (e.g. #p:[my_key, victim_key]) to receive the victim's notifications.
108- let has_matching_p = filter. generic_tags . get ( & p_tag) . is_some_and ( |values| {
109- !values. is_empty ( ) && values. iter ( ) . all ( |v| * v == authed_pubkey_hex)
110- } ) ;
111- if !has_matching_p {
112- conn. send ( RelayMessage :: closed (
113- & sub_id,
114- "restricted: membership notifications require #p matching your pubkey" ,
115- ) ) ;
116- return ;
117- }
118- }
119-
120- // NIP-17 gift wraps (kind:1059) require #p = authed pubkey.
121- // Same pattern as membership notifications — prevents reading others' DMs.
122- let can_match_gift_wrap = filter. kinds . as_ref ( ) . is_none_or ( |ks| {
123- ks. iter ( ) . any ( |k| k. as_u16 ( ) as u32 == KIND_GIFT_WRAP )
124- } ) ;
125- if can_match_gift_wrap {
112+ // a client from sneaking in a victim's pubkey alongside their own.
126113 let has_matching_p = filter. generic_tags . get ( & p_tag) . is_some_and ( |values| {
127114 !values. is_empty ( ) && values. iter ( ) . all ( |v| * v == authed_pubkey_hex)
128115 } ) ;
129116 if !has_matching_p {
130117 conn. send ( RelayMessage :: closed (
131118 & sub_id,
132- "restricted: gift-wrap events require #p matching your pubkey" ,
119+ "restricted: p-gated events require #p matching your pubkey" ,
133120 ) ) ;
134121 return ;
135122 }
@@ -235,6 +222,9 @@ pub async fn handle_req(
235222
236223/// Handle a NIP-50 search REQ: query Typesense, fetch full events, deliver results, EOSE.
237224/// Search subscriptions are one-shot — no persistent subscription is registered.
225+ /// Maximum Typesense pages to fetch per filter (prevents unbounded loops).
226+ const MAX_SEARCH_PAGES : u32 = 5 ;
227+
238228async fn handle_search_req (
239229 sub_id : & str ,
240230 filters : & [ Filter ] ,
@@ -247,7 +237,6 @@ async fn handle_search_req(
247237 return ;
248238 }
249239
250- // Build channel scope filter for Typesense
251240 let channel_filter = {
252241 let ids: Vec < String > = accessible_channels. iter ( ) . map ( |id| id. to_string ( ) ) . collect ( ) ;
253242 format ! ( "channel_id:=[{}]" , ids. join( "," ) )
@@ -266,7 +255,8 @@ async fn handle_search_req(
266255 . map ( |l| ( l as u32 ) . min ( MAX_HISTORICAL_LIMIT as u32 ) )
267256 . unwrap_or ( MAX_HISTORICAL_LIMIT as u32 ) ;
268257
269- // Build Typesense filter_by — channel scope + optional kind constraint
258+ // Push as many NIP-01 constraints into Typesense as possible so
259+ // post-filtering is a correction step, not the primary filter.
270260 let mut filter_parts = vec ! [ channel_filter. clone( ) ] ;
271261 if let Some ( ref kinds) = filter. kinds {
272262 if !kinds. is_empty ( ) {
@@ -275,85 +265,108 @@ async fn handle_search_req(
275265 filter_parts. push ( format ! ( "kind:=[{}]" , kind_vals. join( "," ) ) ) ;
276266 }
277267 }
278-
279- let search_query = sprout_search:: SearchQuery {
280- q : search_text,
281- filter_by : Some ( filter_parts. join ( " && " ) ) ,
282- sort_by : None , // Typesense default = relevance (text_match score)
283- page : 1 ,
284- per_page : limit,
285- } ;
286-
287- let search_result = match state. search . search ( & search_query) . await {
288- Ok ( r) => r,
289- Err ( e) => {
290- warn ! ( sub_id = %sub_id, "NIP-50 search failed: {e}" ) ;
291- continue ;
268+ if let Some ( ref authors) = filter. authors {
269+ if !authors. is_empty ( ) {
270+ let author_vals: Vec < String > = authors. iter ( ) . map ( |a| a. to_hex ( ) ) . collect ( ) ;
271+ filter_parts. push ( format ! ( "pubkey:=[{}]" , author_vals. join( "," ) ) ) ;
292272 }
293- } ;
294-
295- // Collect event IDs from search hits (skip hits with no channel_id)
296- let hit_ids: Vec < Vec < u8 > > = search_result
297- . hits
298- . iter ( )
299- . filter ( |h| h. channel_id . is_some ( ) )
300- . filter_map ( |h| hex:: decode ( & h. event_id ) . ok ( ) )
301- . filter ( |bytes| bytes. len ( ) == 32 )
302- . collect ( ) ;
303-
304- if hit_ids. is_empty ( ) {
305- continue ;
273+ }
274+ if let Some ( since) = filter. since {
275+ filter_parts. push ( format ! ( "created_at:>={}" , since. as_u64( ) ) ) ;
276+ }
277+ if let Some ( until) = filter. until {
278+ filter_parts. push ( format ! ( "created_at:<={}" , until. as_u64( ) ) ) ;
306279 }
307280
308- // Batch-fetch full events from DB
309- let id_refs: Vec < & [ u8 ] > = hit_ids. iter ( ) . map ( |b| b. as_slice ( ) ) . collect ( ) ;
310- let events = match state. db . get_events_by_ids ( & id_refs) . await {
311- Ok ( evs) => evs,
312- Err ( e) => {
313- warn ! ( sub_id = %sub_id, "NIP-50 batch fetch failed: {e}" ) ;
314- continue ;
281+ let filter_by = filter_parts. join ( " && " ) ;
282+
283+ // Paginate: keep fetching pages until we've emitted `limit` results
284+ // or exhausted the search result set. This ensures post-filtering
285+ // doesn't silently reduce the result count below the requested limit.
286+ let mut emitted: u32 = 0 ;
287+ let per_page = limit. min ( 100 ) ; // Typesense max per_page is typically 250
288+
289+ for page in 1 ..=MAX_SEARCH_PAGES {
290+ if emitted >= limit {
291+ break ;
315292 }
316- } ;
317293
318- // Build a lookup map for preserving Typesense relevance order
319- let event_map: std:: collections:: HashMap < [ u8 ; 32 ] , & sprout_core:: StoredEvent > = events
320- . iter ( )
321- . map ( |ev| ( ev. event . id . to_bytes ( ) , ev) )
322- . collect ( ) ;
323-
324- // Deliver in Typesense relevance order
325- for hit_id in & hit_ids {
326- let id_array: [ u8 ; 32 ] = match hit_id. as_slice ( ) . try_into ( ) {
327- Ok ( a) => a,
328- Err ( _) => continue ,
294+ let search_query = sprout_search:: SearchQuery {
295+ q : search_text. clone ( ) ,
296+ filter_by : Some ( filter_by. clone ( ) ) ,
297+ sort_by : None , // Typesense default = relevance (text_match score)
298+ page,
299+ per_page,
329300 } ;
330301
331- let stored = match event_map. get ( & id_array) {
332- Some ( ev) => ev,
333- None => continue , // Deleted between search and fetch
302+ let search_result = match state. search . search ( & search_query) . await {
303+ Ok ( r) => r,
304+ Err ( e) => {
305+ warn ! ( sub_id = %sub_id, "NIP-50 search failed: {e}" ) ;
306+ break ;
307+ }
334308 } ;
335309
336- if !seen_ids. insert ( stored. event . id ) {
337- continue ; // Cross-filter dedup
338- }
310+ let page_empty = search_result. hits . is_empty ( ) ;
311+ let exhausted = ( page as u64 ) * ( per_page as u64 ) >= search_result. found ;
312+
313+ let hit_ids: Vec < Vec < u8 > > = search_result
314+ . hits
315+ . into_iter ( )
316+ . filter ( |h| h. channel_id . is_some ( ) )
317+ . filter_map ( |h| hex:: decode ( & h. event_id ) . ok ( ) )
318+ . filter ( |bytes| bytes. len ( ) == 32 )
319+ . collect ( ) ;
320+
321+ if !hit_ids. is_empty ( ) {
322+ let id_refs: Vec < & [ u8 ] > = hit_ids. iter ( ) . map ( |b| b. as_slice ( ) ) . collect ( ) ;
323+ let events = match state. db . get_events_by_ids ( & id_refs) . await {
324+ Ok ( evs) => evs,
325+ Err ( e) => {
326+ warn ! ( sub_id = %sub_id, "NIP-50 batch fetch failed: {e}" ) ;
327+ break ;
328+ }
329+ } ;
339330
340- // NIP-01 post-filtering: check ids, since, until, generic tags against THIS filter.
341- // Use single-element slice so we match against only this filter's constraints,
342- // not the OR of all filters (which could let a hit from filter A pass filter B's
343- // non-search fields).
344- if !filters_match ( & [ filter. clone ( ) ] , stored) {
345- continue ;
346- }
331+ let event_map: std:: collections:: HashMap < [ u8 ; 32 ] , & sprout_core:: StoredEvent > =
332+ events
333+ . iter ( )
334+ . map ( |ev| ( ev. event . id . to_bytes ( ) , ev) )
335+ . collect ( ) ;
347336
348- // Access check (belt and suspenders — Typesense already filtered by channel)
349- if let Some ( ch_id) = stored. channel_id {
350- if !accessible_channels. contains ( & ch_id) {
351- continue ;
337+ for hit_id in & hit_ids {
338+ if emitted >= limit {
339+ break ;
340+ }
341+ let id_array: [ u8 ; 32 ] = match hit_id. as_slice ( ) . try_into ( ) {
342+ Ok ( a) => a,
343+ Err ( _) => continue ,
344+ } ;
345+ let stored = match event_map. get ( & id_array) {
346+ Some ( ev) => ev,
347+ None => continue ,
348+ } ;
349+ if !seen_ids. insert ( stored. event . id ) {
350+ continue ;
351+ }
352+ // NIP-01 post-filtering against THIS filter only (not OR of all filters).
353+ if !filters_match ( std:: slice:: from_ref ( filter) , stored) {
354+ continue ;
355+ }
356+ if let Some ( ch_id) = stored. channel_id {
357+ if !accessible_channels. contains ( & ch_id) {
358+ continue ;
359+ }
360+ }
361+ if !conn. send ( RelayMessage :: event ( sub_id, & stored. event ) ) {
362+ return ;
363+ }
364+ emitted += 1 ;
352365 }
353366 }
354367
355- if !conn . send ( RelayMessage :: event ( sub_id , & stored . event ) ) {
356- return ; // Connection closed
368+ if page_empty || exhausted {
369+ break ;
357370 }
358371 }
359372 }
0 commit comments