1use std::collections::HashMap;
23use std::sync::Mutex;
24
25use serde::{Deserialize, Serialize};
26
27use crate::model::{Actor, Timestamp};
28use crate::security::{same_secret, token_hash};
29use crate::Error;
30
31pub const TTL: u64 = 10 * 60;
33pub const INTERVAL: u64 = 2;
35pub const REGISTER_PER_MINUTE: usize = 10;
37const MAX_PENDING: usize = 1000;
39const MAX_TEXT: usize = 64;
41const CODE_ALPHABET: &[u8] = b"ABCDEFGHJKMNPQRSTUVWXYZ23456789";
43
44#[derive(Debug, Clone, Default, Deserialize, Serialize)]
46pub struct Asker {
47 #[serde(default)]
48 pub host: String,
49 #[serde(default)]
50 pub os: String,
51 #[serde(default)]
52 pub app_version: String,
53}
54
55impl Asker {
56 fn tidy(self) -> Self {
58 let tidy = |text: String| -> String {
59 text.chars().map(|c| if c.is_control() { ' ' } else { c }).collect::<String>().trim().chars().take(MAX_TEXT).collect()
60 };
61 Self { host: tidy(self.host), os: tidy(self.os), app_version: tidy(self.app_version) }
62 }
63}
64
65#[derive(Debug, Clone, Serialize)]
67pub struct Registered {
68 pub link_token: String,
69 pub poll_secret: String,
70 pub code: String,
71 pub path: String,
73 pub expires_in: u64,
74 pub interval: u64,
75}
76
77#[derive(Debug, Clone, Serialize)]
79pub struct LinkView {
80 pub code: String,
81 pub host: String,
82 pub os: String,
83 pub app_version: String,
84 pub ip: String,
86 pub expires_in: u64,
87}
88
89#[derive(Debug, Clone)]
91pub enum Poll {
92 Pending,
93 Denied,
94 Approved { by: Actor, asker: Asker },
96 Unknown,
98}
99
100#[derive(Clone)]
101enum Decision {
102 Pending,
103 Denied,
104 Approved(Actor),
105}
106
107#[derive(Clone)]
108struct Link {
109 token_hash: String,
111 secret_hash: String,
112 code: String,
113 asker: Asker,
114 ip: String,
115 expires_at: Timestamp,
116 decision: Decision,
117}
118
119#[derive(Default)]
121pub struct DesktopLinks {
122 links: Mutex<Vec<Link>>,
123 registrations: Mutex<HashMap<String, Vec<Timestamp>>>,
124}
125
126impl std::fmt::Debug for DesktopLinks {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129 let pending = self.links.lock().map(|l| l.len()).unwrap_or(0);
130 f.debug_struct("DesktopLinks").field("pending", &pending).finish()
131 }
132}
133
134impl DesktopLinks {
135 fn links(&self) -> std::sync::MutexGuard<'_, Vec<Link>> {
136 self.links.lock().unwrap_or_else(|e| e.into_inner())
137 }
138
139 pub fn register(&self, asker: Asker, ip: Option<String>, now: Timestamp) -> Result<Registered, Error> {
142 let ip = ip.unwrap_or_default();
143 {
144 let mut counts = self.registrations.lock().unwrap_or_else(|e| e.into_inner());
145 counts.retain(|_, times| {
146 times.retain(|&t| now.saturating_sub(t) < 60);
147 !times.is_empty()
148 });
149 let times = counts.entry(ip.clone()).or_default();
150 if times.len() >= REGISTER_PER_MINUTE {
151 return Err(Error::too_many("too many sign-in requests from this address — wait a minute and try again"));
152 }
153 times.push(now);
154 }
155 let mut links = self.links();
156 links.retain(|link| link.expires_at > now);
157 if links.len() >= MAX_PENDING {
158 return Err(Error::too_many("too many sign-in requests are waiting — try again in a few minutes"));
159 }
160 let link_token = crate::auth::random_token(32);
161 let poll_secret = crate::auth::random_token(32);
162 let code = new_code();
163 links.push(Link {
164 token_hash: token_hash(&link_token),
165 secret_hash: token_hash(&poll_secret),
166 code: code.clone(),
167 asker: asker.tidy(),
168 ip,
169 expires_at: now + TTL,
170 decision: Decision::Pending,
171 });
172 Ok(Registered {
173 path: format!("/desktop-link?token={link_token}"),
174 link_token,
175 poll_secret,
176 code,
177 expires_in: TTL,
178 interval: INTERVAL,
179 })
180 }
181
182 pub fn inspect(&self, token: &str, now: Timestamp) -> Option<LinkView> {
184 let hash = token_hash(token);
185 let links = self.links();
186 let link = links.iter().find(|l| l.expires_at > now && !l.token_hash.is_empty() && same_secret(&l.token_hash, &hash))?;
187 Some(LinkView {
188 code: link.code.clone(),
189 host: link.asker.host.clone(),
190 os: link.asker.os.clone(),
191 app_version: link.asker.app_version.clone(),
192 ip: link.ip.clone(),
193 expires_in: link.expires_at - now,
194 })
195 }
196
197 pub fn decide(&self, token: &str, by: Option<Actor>, now: Timestamp) -> Result<Asker, Error> {
201 let hash = token_hash(token);
202 let mut links = self.links();
203 let link = links
204 .iter_mut()
205 .find(|l| l.expires_at > now && !l.token_hash.is_empty() && same_secret(&l.token_hash, &hash))
206 .ok_or_else(gone)?;
207 link.token_hash.clear();
208 link.decision = match by {
209 Some(actor) => Decision::Approved(actor),
210 None => Decision::Denied,
211 };
212 Ok(link.asker.clone())
213 }
214
215 pub fn poll(&self, secret: &str, now: Timestamp) -> Poll {
218 let hash = token_hash(secret);
219 let mut links = self.links();
220 links.retain(|link| link.expires_at > now);
221 let Some(at) = links.iter().position(|l| same_secret(&l.secret_hash, &hash)) else {
222 return Poll::Unknown;
223 };
224 match &links[at].decision {
225 Decision::Pending => Poll::Pending,
226 Decision::Denied => Poll::Denied,
227 Decision::Approved(_) => {
228 let link = links.remove(at);
229 let Decision::Approved(by) = link.decision else { unreachable!() };
230 Poll::Approved { by, asker: link.asker }
231 }
232 }
233 }
234}
235
236pub fn gone() -> Error {
239 Error {
240 status: axum::http::StatusCode::NOT_FOUND,
241 message: "this sign-in link has expired or was already used — start the sign-in again from BREP".into(),
242 }
243}
244
245fn new_code() -> String {
246 let len = CODE_ALPHABET.len();
250 let limit = 256 - 256 % len;
251 let mut code = String::with_capacity(6);
252 let mut byte = [0u8; 1];
253 while code.len() < 6 {
254 crate::auth::fill_random(&mut byte);
255 if (byte[0] as usize) < limit {
256 code.push(CODE_ALPHABET[byte[0] as usize % len] as char);
257 }
258 }
259 code
260}