Skip to main content

cosmic_applet_avestruz/nostr/
private_relay.rs

1// SPDX-License-Identifier: MIT
2
3//! The relay Avestruz runs itself, for what is the account's alone: what is
4//! written and not published, and whatever else is not for any other relay.
5//!
6//! It is a relay like any other, over the same event store the client
7//! keeps, but it listens nowhere: on no port, and on no socket file. A
8//! connection to it is a pipe made inside this process, one end handed to
9//! the relay and the other kept, so there is nothing for another program
10//! to open, and Avestruz is the only client it has.
11//!
12//! That is the relay, not the store under it: the store is a file, and
13//! whoever can read the user's files can read that one. What is written
14//! and not published is encrypted in it.
15//!
16//! The relay takes the events of the account that is signed in, and no
17//! others. Avestruz talks to it as a client talks to any relay: an event
18//! is sent and its `OK` waited for, a question is asked and its answers
19//! read until the relay says that is all.
20//!
21//! ```mermaid
22//! sequenceDiagram
23//!     participant client as PrivateRelay: send or ask
24//!     participant near as The near end of a pipe
25//!     participant far as The far end
26//!     participant relay as LocalRelay
27//!     participant store as Event store
28//!     client->>near: a pipe is made, in memory
29//!     client->>relay: take this connection (the far end)
30//!     client->>near: EVENT, or REQ, as WebSocket frames
31//!     near->>far: bytes
32//!     far->>relay: the message
33//!     relay->>relay: is the event signed by the account signed in?
34//!     relay->>store: kept, or read
35//!     relay-->>client: OK, or the events and EOSE, back the same way
36//!     client->>near: closed, and the relay's end of it is done
37//! ```
38//!
39//! Each `send` and each `ask` makes a pipe of its own and closes it. The
40//! two ends speak WebSocket from the first byte, since that is what the
41//! relay library takes a connection as; there is no HTTP request to open
42//! it, and nothing listens.
43//!
44//! What goes to this relay, and why, is in [`crate::guide::relays`].
45
46use std::future::Future;
47use std::net::{Ipv4Addr, SocketAddr};
48use std::pin::Pin;
49use std::sync::{Arc, Mutex, PoisonError};
50use std::time::Duration;
51
52use futures_util::{SinkExt, StreamExt};
53use nostr_sdk::prelude::{
54    ClientMessage, Event, Filter, LocalRelay, MachineReadablePrefix, NostrDatabase, PublicKey, RelayMessage, SubscriptionId,
55    WritePolicy, WritePolicyResult,
56};
57use tokio::io::DuplexStream;
58use tokio_tungstenite::WebSocketStream;
59use tokio_tungstenite::tungstenite::Message;
60use tokio_tungstenite::tungstenite::protocol::Role;
61
62/// How much either end of a connection may have written that the other
63/// has not read yet. The writer waits when it is that much.
64const PIPE_BYTES: usize = 64 * 1024;
65
66/// How long the relay has to answer.
67const ANSWER_TIMEOUT: Duration = Duration::from_secs(5);
68
69/// The address the relay is told its connections are from: they are all
70/// from this process, and a pipe has none.
71const PEER: SocketAddr = SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
72
73/// Takes the events the account signed in wrote, and no others; with
74/// nobody signed in, none at all.
75#[derive(Debug, Default)]
76struct OwnersAlone {
77    owner: Arc<Mutex<Option<PublicKey>>>,
78}
79
80impl WritePolicy for OwnersAlone {
81    fn admit_event<'a>(
82        &'a self,
83        event: &'a Event,
84        _addr: &'a SocketAddr,
85    ) -> Pin<Box<dyn Future<Output = WritePolicyResult> + Send + 'a>> {
86        let owner = *self.owner.lock().unwrap_or_else(PoisonError::into_inner);
87        Box::pin(async move {
88            if owner == Some(event.pubkey) {
89                WritePolicyResult::Accept
90            } else {
91                WritePolicyResult::reject(MachineReadablePrefix::Restricted, "this relay keeps its own account's events")
92            }
93        })
94    }
95}
96
97/// The relay Avestruz runs itself, and the way to it. Clones are the same
98/// relay; it is gone when the last of them is.
99#[derive(Debug, Clone)]
100pub struct PrivateRelay {
101    /// Shared rather than cloned: the relay is large, and this is passed
102    /// about with the client it belongs to.
103    relay: Arc<LocalRelay>,
104    /// Whose events it takes.
105    owner: Arc<Mutex<Option<PublicKey>>>,
106}
107
108impl PrivateRelay {
109    /// A relay over `database`, which is reached from here and from
110    /// nowhere else.
111    pub fn over(database: Arc<dyn NostrDatabase>) -> Self {
112        let owner: Arc<Mutex<Option<PublicKey>>> = Arc::default();
113        let relay = LocalRelay::builder().database(database).write_policy(OwnersAlone { owner: owner.clone() }).build();
114        Self { relay: Arc::new(relay), owner }
115    }
116
117    /// Take the events of `owner` from now on, and no others: the account
118    /// that is signed in, or nobody's when none is.
119    pub fn set_owner(&self, owner: Option<PublicKey>) {
120        *self.owner.lock().unwrap_or_else(PoisonError::into_inner) = owner;
121    }
122
123    /// A connection to the relay, as its client: a pipe, with the relay
124    /// at the far end of it for as long as this end is held.
125    ///
126    /// The two ends speak WebSocket from the first byte, without the
127    /// request that opens one elsewhere: the relay takes a connection as
128    /// one that is already agreed to.
129    async fn connect(&self) -> WebSocketStream<DuplexStream> {
130        let (near, far) = tokio::io::duplex(PIPE_BYTES);
131        let relay = self.relay.clone();
132        tokio::spawn(async move {
133            if let Err(e) = relay.take_connection(far, PEER).await {
134                tracing::debug!("a connection to the relay of this machine ended: {e}");
135            }
136        });
137        WebSocketStream::from_raw_socket(near, Role::Client, None).await
138    }
139
140    /// Send `event` to the relay, and wait for it to say that it took it.
141    /// What it says otherwise is the error.
142    pub async fn send(&self, event: &Event) -> Result<(), String> {
143        let sending = async {
144            let mut relay = self.connect().await;
145            relay.send(Message::text(ClientMessage::event(event.clone()).as_json())).await.map_err(|e| e.to_string())?;
146            while let Some(message) = relay.next().await {
147                let Message::Text(text) = message.map_err(|e| e.to_string())? else {
148                    continue;
149                };
150                if let Ok(RelayMessage::Ok { event_id, status, message }) = RelayMessage::from_json(text.as_str())
151                    && event_id == event.id
152                {
153                    let _ = relay.close(None).await;
154                    return if status { Ok(()) } else { Err(message.into_owned()) };
155                }
156            }
157            Err("the relay hung up".to_string())
158        };
159        tokio::time::timeout(ANSWER_TIMEOUT, sending).await.map_err(|_| "the relay did not answer".to_string())?
160    }
161
162    /// The events the relay has that `filter` matches.
163    pub async fn ask(&self, filter: Filter) -> Result<Vec<Event>, String> {
164        let asking = async {
165            let mut relay = self.connect().await;
166            let question = SubscriptionId::generate();
167            let asked = ClientMessage::req(question.clone(), filter).as_json();
168            relay.send(Message::text(asked)).await.map_err(|e| e.to_string())?;
169            let mut events = Vec::new();
170            while let Some(message) = relay.next().await {
171                let Message::Text(text) = message.map_err(|e| e.to_string())? else {
172                    continue;
173                };
174                match RelayMessage::from_json(text.as_str()) {
175                    Ok(RelayMessage::Event { event, .. }) => events.push(event.into_owned()),
176                    Ok(RelayMessage::EndOfStoredEvents(_)) => {
177                        let _ = relay.send(Message::text(ClientMessage::close(question).as_json())).await;
178                        let _ = relay.close(None).await;
179                        return Ok(events);
180                    }
181                    Ok(RelayMessage::Closed { message, .. }) => return Err(message.into_owned()),
182                    _ => {}
183                }
184            }
185            Err("the relay hung up".to_string())
186        };
187        tokio::time::timeout(ANSWER_TIMEOUT, asking).await.map_err(|_| "the relay did not answer".to_string())?
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::PrivateRelay;
194    use nostr_lmdb::NostrLmdb;
195    use nostr_sdk::prelude::{Event, EventBuilder, Filter, FinalizeEvent, IntoNostrDatabase, Keys, Kind};
196
197    fn note(keys: &Keys, text: &str) -> Event {
198        EventBuilder::new(Kind::TextNote, text).finalize(keys).unwrap()
199    }
200
201    /// Every file under `directory`, however deep.
202    fn files_under(directory: &std::path::Path) -> Vec<std::path::PathBuf> {
203        let mut files = Vec::new();
204        for entry in std::fs::read_dir(directory).unwrap() {
205            let path = entry.unwrap().path();
206            if path.is_dir() { files.extend(files_under(&path)) } else { files.push(path) }
207        }
208        files
209    }
210
211    #[test]
212    fn the_relay_is_reached_from_here_and_leaves_nothing_to_open() {
213        let store = std::env::temp_dir().join(format!("avestruz-test-{}-private-relay", std::process::id()));
214        let _ = std::fs::remove_dir_all(&store);
215        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
216        runtime.block_on(async {
217            tokio::fs::create_dir_all(&store).await.unwrap();
218            let database = NostrLmdb::open(&store).await.unwrap().into_nostr_database();
219            let before = files_under(&store);
220            let relay = PrivateRelay::over(database.clone());
221
222            // With nobody signed in it takes nothing; then its account's
223            // events, and nobody else's.
224            let (me, other) = (Keys::generate(), Keys::generate());
225            let mine = note(&me, "mine");
226            assert!(relay.send(&mine).await.is_err());
227            relay.set_owner(Some(me.public_key()));
228            assert_eq!(relay.send(&mine).await, Ok(()));
229            let refused = relay.send(&note(&other, "somebody else's")).await.unwrap_err();
230            assert!(refused.contains("restricted"), "{refused}");
231
232            // What it has is what the store has, the event it took and
233            // one the store got another way.
234            let stored = note(&other, "from another relay");
235            database.save_event(&stored).await.unwrap();
236            let mut found: Vec<_> =
237                relay.ask(Filter::new().kind(Kind::TextNote)).await.unwrap().into_iter().map(|event| event.id).collect();
238            found.sort();
239            let mut expected = vec![mine.id, stored.id];
240            expected.sort();
241            assert_eq!(found, expected);
242            assert_eq!(database.query(Filter::new().id(mine.id)).await.unwrap().len(), 1);
243
244            // An answer longer than the pipe holds at once comes whole.
245            let long: Vec<Event> = (0..4).map(|nth| note(&me, &format!("{nth} {}", "a long note ".repeat(2_500)))).collect();
246            for note in &long {
247                assert_eq!(relay.send(note).await, Ok(()));
248            }
249            let asked = relay.ask(Filter::new().ids(long.iter().map(|note| note.id))).await.unwrap();
250            assert_eq!(asked.len(), 4);
251            assert!(asked.iter().map(|note| note.content.len()).sum::<usize>() > super::PIPE_BYTES);
252
253            // A clone is the same relay.
254            assert_eq!(relay.clone().ask(Filter::new().id(mine.id)).await.unwrap().len(), 1);
255
256            // Nothing was made beside the store's own files for anything
257            // else to connect to.
258            assert_eq!(files_under(&store), before);
259        });
260        drop(runtime);
261        let _ = std::fs::remove_dir_all(&store);
262    }
263}