1use std::io;
6use std::path::Path;
7
8use futures_util::{SinkExt, StreamExt};
9use teter_common::account::{AccountReply, AccountRequest, PATH};
10use tokio_tungstenite::tungstenite::Message as Frame;
11
12pub use teter_core::account::*;
13
14#[derive(Debug)]
19pub struct MachineUnknown(String);
20
21impl MachineUnknown {
22 pub fn is(error: &io::Error) -> bool {
24 error.get_ref().is_some_and(|inner| inner.is::<Self>())
25 }
26}
27
28impl std::fmt::Display for MachineUnknown {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.write_str(&self.0)
31 }
32}
33
34impl std::error::Error for MachineUnknown {}
35
36pub fn machine_refusal(reason: &str) -> io::Error {
39 let message = format!("the relay refused this machine: {reason}");
40 if reason == teter_common::account::MACHINE_UNKNOWN {
41 io::Error::new(io::ErrorKind::PermissionDenied, MachineUnknown(message))
42 } else {
43 io::Error::other(message)
44 }
45}
46
47pub async fn authenticate_machine<S>(ws: &mut S, id: &str, key: &MachineKey) -> io::Result<()>
56where
57 S: futures_util::Sink<Frame, Error = tokio_tungstenite::tungstenite::Error>
58 + futures_util::Stream<Item = Result<Frame, tokio_tungstenite::tungstenite::Error>>
59 + Unpin,
60{
61 use teter_common::{Message, MessagePayload, MessageType};
62 let hello = Message {
63 msg_type: MessageType::MachineHello,
64 session: None,
65 channel: None,
66 payload: Some(MessagePayload::MachineId {
67 machine: id.to_owned(),
68 protocol: teter_common::PROTOCOL,
69 }),
70 };
71 crate::send(ws, hello).await?;
72 let challenge = crate::recv(ws)
73 .await?
74 .ok_or_else(|| io::Error::other("the relay closed the connection before its challenge"))?;
75 let nonce = match (challenge.msg_type, challenge.payload) {
76 (MessageType::Challenge, Some(MessagePayload::Challenge { nonce, protocol })) => {
77 teter_common::check_relay_protocol(protocol).map_err(io::Error::other)?;
79 nonce
80 }
81 (MessageType::SessionError, payload) => {
82 let reason = match payload {
83 Some(MessagePayload::ErrorReason { reason }) => reason,
84 _ => "no reason given".to_owned(),
85 };
86 return Err(machine_refusal(&reason));
90 }
91 (other, _) => {
92 return Err(io::Error::other(format!(
93 "the relay answered the machine's hello with {}",
94 other.to_str()
95 )));
96 }
97 };
98 let proof = Message {
99 msg_type: MessageType::MachineProof,
100 session: None,
101 channel: None,
102 payload: Some(MessagePayload::Signature {
103 signature: key.sign(&teter_common::machine_proof_message(&nonce, id)),
104 }),
105 };
106 crate::send(ws, proof).await
107}
108
109pub async fn request(
117 relay: &str,
118 ca_cert: Option<&Path>,
119 request: &AccountRequest,
120) -> Result<AccountReply, AccountError> {
121 let mut ws = crate::connect(&account_url(relay), ca_cert).await?;
122 let text = serde_json::to_string(request).map_err(io::Error::other)?;
123 ws.send(Frame::text(text)).await.map_err(io::Error::other)?;
124 loop {
125 match ws.next().await {
126 Some(Ok(Frame::Text(text))) => {
127 drop(ws.close(None).await);
128 return serde_json::from_str(&text).map_err(|e| {
129 AccountError::Refused(format!("an answer teter does not read: {e}"))
130 });
131 }
132 Some(Ok(_)) => {}
133 Some(Err(e)) => return Err(io::Error::other(e).into()),
134 None => {
135 return Err(AccountError::Refused(
136 "the relay closed the connection without an answer".to_owned(),
137 ));
138 }
139 }
140 }
141}
142
143fn account_url(relay: &str) -> String {
145 let host_at = relay.find("://").map_or(0, |at| at + 3);
146 let path_at = relay
147 .get(host_at..)
148 .and_then(|rest| rest.find('/'))
149 .map_or(relay.len(), |at| host_at + at);
150 let (origin, path) = relay.split_at(path_at);
151 let path = path.trim_end_matches('/');
152 let path = ["/backend", "/frontend", PATH]
153 .into_iter()
154 .find_map(|endpoint| path.strip_suffix(endpoint))
155 .unwrap_or(path);
156 format!("{origin}{path}{PATH}")
157}
158
159#[cfg(test)]
160mod tests {
161 use super::account_url;
162
163 #[test]
164 fn the_account_service_is_the_relays_account_path() {
165 for relay in [
166 "wss://relay.example.com",
167 "wss://relay.example.com/",
168 "wss://relay.example.com/backend",
169 "wss://relay.example.com/frontend",
170 "wss://relay.example.com/account",
171 ] {
172 assert_eq!(account_url(relay), "wss://relay.example.com/account");
173 }
174 assert_eq!(account_url("ws://backend"), "ws://backend/account");
175 }
176}