|
| 1 | +//! Strict, canonical NIP-CW thread-mode requests. Unknown constraints fail rather than |
| 2 | +//! silently describing different rows from the ones the caller requested. |
| 3 | +
|
| 4 | +use chrono::{DateTime, Utc}; |
| 5 | +use serde::Serialize; |
| 6 | +use serde_json::{json, Value}; |
| 7 | +use sha2::{Digest, Sha256}; |
| 8 | +use uuid::Uuid; |
| 9 | + |
| 10 | +/// Maximum reply scan candidates per window. |
| 11 | +pub const MAX_LIMIT: u32 = 200; |
| 12 | +/// Conversation row kinds. Edits, reactions, deletions and metadata are aux, |
| 13 | +/// never reply-budget candidates, even if they have thread metadata. |
| 14 | +pub const ROW_KINDS: [u32; 4] = [9, 40002, 45001, 45003]; |
| 15 | + |
| 16 | +/// A position in `(created_at DESC, id ASC)` order. |
| 17 | +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] |
| 18 | +pub struct Cursor { |
| 19 | + /// Nonnegative Unix seconds, representable by PostgreSQL/chrono. |
| 20 | + pub created_at: i64, |
| 21 | + /// Full lowercase hexadecimal event id. |
| 22 | + pub id: String, |
| 23 | +} |
| 24 | + |
| 25 | +impl Cursor { |
| 26 | + /// Checked timestamp conversion (also used at the database boundary). |
| 27 | + pub fn timestamp(&self) -> Result<DateTime<Utc>, String> { |
| 28 | + DateTime::from_timestamp(self.created_at, 0) |
| 29 | + .filter(|_| self.created_at >= 0) |
| 30 | + .ok_or_else(|| "thread_window: cursor timestamp out of range".into()) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +/// Validated pagination and response-affecting arguments. Construct with |
| 35 | +/// [`Request::parse`]; the database also validates public inputs defensively. |
| 36 | +#[derive(Clone, Debug, PartialEq, Eq)] |
| 37 | +pub struct Request { |
| 38 | + /// Exactly one canonical channel UUID. |
| 39 | + pub channel: Uuid, |
| 40 | + /// Exactly one lowercase full root event id. |
| 41 | + pub root: String, |
| 42 | + /// Raw reply candidate budget, 1..=200. |
| 43 | + pub limit: u32, |
| 44 | + /// Maximum absolute depth below the root, 1..=100. |
| 45 | + pub depth: u32, |
| 46 | + /// Sorted, deduplicated conversation row kinds. |
| 47 | + pub kinds: Vec<u32>, |
| 48 | + /// Request upper bound; absent means newest page. |
| 49 | + pub cursor: Option<Cursor>, |
| 50 | + /// Include root/retained-row edits, reactions and deletion closure. |
| 51 | + pub include_aux: bool, |
| 52 | +} |
| 53 | + |
| 54 | +fn event_id(v: &Value) -> Result<String, String> { |
| 55 | + v.as_str() |
| 56 | + .filter(|s| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())) |
| 57 | + .map(str::to_ascii_lowercase) |
| 58 | + .ok_or_else(|| "thread_window: expected a full 64-hex event id".into()) |
| 59 | +} |
| 60 | + |
| 61 | +fn singleton<'a>(raw: &'a Value, key: &str) -> Result<&'a Value, String> { |
| 62 | + raw.get(key) |
| 63 | + .and_then(Value::as_array) |
| 64 | + .filter(|a| a.len() == 1) |
| 65 | + .and_then(|a| a.first()) |
| 66 | + .ok_or_else(|| format!("thread_window requires exactly one {key}")) |
| 67 | +} |
| 68 | + |
| 69 | +fn bounded(raw: &Value, key: &str, default: u32, max: u32) -> Result<u32, String> { |
| 70 | + match raw.get(key) { |
| 71 | + None => Ok(default), |
| 72 | + Some(v) => v |
| 73 | + .as_u64() |
| 74 | + .filter(|n| (1..=u64::from(max)).contains(n)) |
| 75 | + .map(|n| n as u32) |
| 76 | + .ok_or_else(|| format!("thread_window: {key} must be an integer in 1..={max}")), |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +impl Request { |
| 81 | + /// Parse only an explicitly opted-in filter. Unsupported filter fields, |
| 82 | + /// including legacy cursors, offsets and other bridge modes, are errors. |
| 83 | + pub fn parse(raw: &Value) -> Result<Self, String> { |
| 84 | + let object = raw.as_object().ok_or("thread_window: expected object")?; |
| 85 | + const FIELDS: &[&str] = &[ |
| 86 | + "thread_window", |
| 87 | + "#h", |
| 88 | + "#e", |
| 89 | + "kinds", |
| 90 | + "limit", |
| 91 | + "depth_limit", |
| 92 | + "until", |
| 93 | + "before_id", |
| 94 | + "include_aux", |
| 95 | + ]; |
| 96 | + if object.keys().any(|key| !FIELDS.contains(&key.as_str())) { |
| 97 | + return Err("thread_window: unsupported or conflicting filter field".into()); |
| 98 | + } |
| 99 | + if raw.get("thread_window") != Some(&Value::Bool(true)) { |
| 100 | + return Err("thread_window must be true".into()); |
| 101 | + } |
| 102 | + let channel = singleton(raw, "#h")? |
| 103 | + .as_str() |
| 104 | + .and_then(|s| Uuid::parse_str(s).ok()) |
| 105 | + .ok_or("thread_window: #h must be a channel UUID")?; |
| 106 | + let root = event_id(singleton(raw, "#e")?)?; |
| 107 | + let limit = bounded(raw, "limit", 50, MAX_LIMIT)?; |
| 108 | + let depth = bounded(raw, "depth_limit", 100, 100)?; |
| 109 | + let mut kinds = raw |
| 110 | + .get("kinds") |
| 111 | + .and_then(Value::as_array) |
| 112 | + .filter(|a| !a.is_empty() && a.len() <= ROW_KINDS.len()) |
| 113 | + .ok_or("thread_window requires nonempty conversation kinds")? |
| 114 | + .iter() |
| 115 | + .map(|v| { |
| 116 | + v.as_u64() |
| 117 | + .and_then(|n| u32::try_from(n).ok()) |
| 118 | + .filter(|n| ROW_KINDS.contains(n)) |
| 119 | + .ok_or_else(|| { |
| 120 | + "thread_window supports row kinds 9, 40002, 45001, 45003 only".to_string() |
| 121 | + }) |
| 122 | + }) |
| 123 | + .collect::<Result<Vec<_>, _>>()?; |
| 124 | + kinds.sort_unstable(); |
| 125 | + kinds.dedup(); |
| 126 | + let cursor = match (raw.get("until"), raw.get("before_id")) { |
| 127 | + (None, None) => None, |
| 128 | + (Some(ts), Some(id)) => { |
| 129 | + let cursor = Cursor { |
| 130 | + created_at: ts |
| 131 | + .as_i64() |
| 132 | + .filter(|n| *n >= 0) |
| 133 | + .ok_or("thread_window: until must be nonnegative integer seconds")?, |
| 134 | + id: event_id(id)?, |
| 135 | + }; |
| 136 | + cursor.timestamp()?; |
| 137 | + Some(cursor) |
| 138 | + } |
| 139 | + _ => return Err("thread_window requires both until and before_id, or neither".into()), |
| 140 | + }; |
| 141 | + let include_aux = match raw.get("include_aux") { |
| 142 | + None => false, |
| 143 | + Some(v) => v |
| 144 | + .as_bool() |
| 145 | + .ok_or("thread_window: include_aux must be boolean")?, |
| 146 | + }; |
| 147 | + Ok(Self { |
| 148 | + channel, |
| 149 | + root, |
| 150 | + limit, |
| 151 | + depth, |
| 152 | + kinds, |
| 153 | + cursor, |
| 154 | + include_aux, |
| 155 | + }) |
| 156 | + } |
| 157 | + |
| 158 | + /// Canonical NIP-CW thread-mode v1 request identity. SHA-256 over a compact JSON array |
| 159 | + /// avoids ambiguous separators and binds all normalized response options. |
| 160 | + /// The host is server-resolved; the reader is the authenticated lowercase |
| 161 | + /// public key. Neither may be taken from filter-supplied fields. |
| 162 | + pub fn binding(&self, resolved_host: &str, reader_hex: &str) -> String { |
| 163 | + let cursor = self.cursor.as_ref().map(|c| json!([c.created_at, c.id])); |
| 164 | + let canonical = json!([ |
| 165 | + "tw", |
| 166 | + 1, |
| 167 | + "older", |
| 168 | + resolved_host, |
| 169 | + reader_hex, |
| 170 | + self.channel.to_string(), |
| 171 | + self.root, |
| 172 | + self.limit, |
| 173 | + self.depth, |
| 174 | + self.kinds, |
| 175 | + cursor, |
| 176 | + self.include_aux |
| 177 | + ]); |
| 178 | + format!( |
| 179 | + "tw:1:{}", |
| 180 | + hex::encode(Sha256::digest(canonical.to_string().as_bytes())) |
| 181 | + ) |
| 182 | + } |
| 183 | +} |
| 184 | + |
| 185 | +#[cfg(test)] |
| 186 | +mod tests { |
| 187 | + use super::*; |
| 188 | + fn filter() -> Value { |
| 189 | + json!({"thread_window":true,"#h":[Uuid::nil()],"#e":["ab".repeat(32)],"kinds":[9]}) |
| 190 | + } |
| 191 | + #[test] |
| 192 | + fn rejects_malformed_and_conflicting_constraints() { |
| 193 | + for (key, value) in [ |
| 194 | + ("until", json!(1)), |
| 195 | + ("before_id", json!("ab".repeat(32))), |
| 196 | + ("limit", json!(0)), |
| 197 | + ("limit", json!(201)), |
| 198 | + ("depth_limit", json!(101)), |
| 199 | + ("depth_limit", json!(-1)), |
| 200 | + ("include_aux", json!("true")), |
| 201 | + ("thread_cursor", json!(0)), |
| 202 | + ("threadCursorId", json!(null)), |
| 203 | + ("top_level", json!(false)), |
| 204 | + ("page", json!(1)), |
| 205 | + ("offset", json!(0)), |
| 206 | + ("authors", json!([])), |
| 207 | + ("since", json!(1)), |
| 208 | + ("#p", json!([])), |
| 209 | + ("kinds", json!([7])), |
| 210 | + ("kinds", json!([])), |
| 211 | + ("search", json!("hello")), |
| 212 | + ("#h", json!([Uuid::nil(), Uuid::nil()])), |
| 213 | + ("#e", json!(["bad"])), |
| 214 | + ] { |
| 215 | + let mut f = filter(); |
| 216 | + f[key] = value; |
| 217 | + assert!(Request::parse(&f).is_err(), "{f}"); |
| 218 | + } |
| 219 | + for ts in [ |
| 220 | + json!(-1), |
| 221 | + json!(1.5), |
| 222 | + json!(null), |
| 223 | + json!(u64::MAX), |
| 224 | + json!(i64::MAX), |
| 225 | + ] { |
| 226 | + let mut f = filter(); |
| 227 | + f["until"] = ts; |
| 228 | + f["before_id"] = json!("a".repeat(64)); |
| 229 | + assert!(Request::parse(&f).is_err(), "{f}"); |
| 230 | + } |
| 231 | + } |
| 232 | + #[test] |
| 233 | + fn binding_normalizes_defaults_and_binds_every_argument() { |
| 234 | + let f = filter(); |
| 235 | + let binding = |raw: &Value| { |
| 236 | + Request::parse(raw) |
| 237 | + .unwrap() |
| 238 | + .binding("relay.example", &"ab".repeat(32)) |
| 239 | + }; |
| 240 | + let expected = binding(&f); |
| 241 | + assert_eq!( |
| 242 | + expected, |
| 243 | + "tw:1:5252322dfd797ddb1d5f1150acd4cf914b9fc09e39bcf3048d25aed514b3546d" |
| 244 | + ); |
| 245 | + let mut explicit = f.clone(); |
| 246 | + explicit["limit"] = json!(50); |
| 247 | + explicit["depth_limit"] = json!(100); |
| 248 | + explicit["include_aux"] = json!(false); |
| 249 | + explicit["#e"] = json!(["AB".repeat(32)]); |
| 250 | + assert_eq!(expected, binding(&explicit)); |
| 251 | + for (key, val) in [ |
| 252 | + ("limit", json!(49)), |
| 253 | + ("depth_limit", json!(1)), |
| 254 | + ("include_aux", json!(true)), |
| 255 | + ("kinds", json!([40002])), |
| 256 | + ("#e", json!(["cd".repeat(32)])), |
| 257 | + ("#h", json!([Uuid::new_v4()])), |
| 258 | + ] { |
| 259 | + let mut changed = f.clone(); |
| 260 | + changed[key] = val; |
| 261 | + assert_ne!(expected, binding(&changed), "{key} must affect binding"); |
| 262 | + } |
| 263 | + let request = Request::parse(&f).unwrap(); |
| 264 | + for (host, reader) in [("other.example", "ab"), ("relay.example", "cd")] { |
| 265 | + assert_ne!(expected, request.binding(host, &reader.repeat(32))); |
| 266 | + } |
| 267 | + let mut changed = f; |
| 268 | + changed["until"] = json!(0); |
| 269 | + changed["before_id"] = json!("ab".repeat(32)); |
| 270 | + assert_ne!(expected, binding(&changed)); |
| 271 | + } |
| 272 | +} |
0 commit comments