1use std::time::{Duration, Instant};
12
13use serde_json::{json, Value};
14
15pub const MAX_WINDOWS: usize = 4;
17pub const KEY_GAP: Duration = Duration::from_millis(500);
21pub const FIRST: WindowId = 0;
23
24pub type WindowId = u32;
25
26#[derive(Debug, Clone, PartialEq)]
28pub struct Entry {
29 pub id: WindowId,
30 pub target: String,
32 pub session: String,
33 pub opener: Option<WindowId>,
35 pub url: String,
36 pub title: String,
37 pub moved: Option<(String, String)>,
39}
40
41#[derive(Debug, PartialEq, Eq)]
43pub struct Removed {
44 pub was_active: bool,
45 pub now_active: WindowId,
46}
47
48#[derive(Debug)]
49pub struct Windows {
50 list: Vec<Entry>,
51 active: WindowId,
52 next: WindowId,
53}
54
55impl Windows {
56 pub fn starting(target: String, session: String) -> Windows {
58 let first = Entry { id: FIRST, target, session, opener: None, url: String::new(), title: String::new(), moved: None };
59 Windows { list: vec![first], active: FIRST, next: FIRST + 1 }
60 }
61
62 pub fn len(&self) -> usize {
63 self.list.len()
64 }
65
66 pub fn has_room(&self) -> bool {
67 self.list.len() < MAX_WINDOWS
68 }
69
70 pub fn active(&self) -> WindowId {
71 self.active
72 }
73
74 pub fn entries(&self) -> &[Entry] {
75 &self.list
76 }
77
78 pub fn get(&self, id: WindowId) -> Option<&Entry> {
79 self.list.iter().find(|w| w.id == id)
80 }
81
82 pub fn by_session(&self, session: &str) -> Option<WindowId> {
83 self.list.iter().find(|w| w.session == session).map(|w| w.id)
84 }
85
86 pub fn by_target(&self, target: &str) -> Option<WindowId> {
87 self.list.iter().find(|w| w.target == target).map(|w| w.id)
88 }
89
90 pub fn add(&mut self, target: String, session: String, opener: Option<WindowId>) -> Option<WindowId> {
92 if !self.has_room() {
93 return None;
94 }
95 let id = self.next;
96 self.next += 1;
97 self.list.push(Entry { id, target, session, opener: opener.filter(|o| self.get(*o).is_some()), url: String::new(), title: String::new(), moved: None });
98 self.active = id;
99 Some(id)
100 }
101
102 pub fn remove(&mut self, id: WindowId) -> Option<Removed> {
105 if id == FIRST {
106 return None;
107 }
108 let at = self.list.iter().position(|w| w.id == id)?;
109 let gone = self.list.remove(at);
110 for w in &mut self.list {
112 if w.opener == Some(id) {
113 w.opener = gone.opener;
114 }
115 }
116 let was_active = self.active == id;
117 if was_active {
118 let back = gone.opener.filter(|o| self.get(*o).is_some());
119 self.active = back.or_else(|| self.list.get(at.saturating_sub(1)).map(|w| w.id)).unwrap_or(FIRST);
120 }
121 Some(Removed { was_active, now_active: self.active })
122 }
123
124 pub fn focus(&mut self, id: WindowId) -> bool {
126 if self.get(id).is_none() {
127 return false;
128 }
129 self.active = id;
130 true
131 }
132
133 pub fn set_location(&mut self, id: WindowId, url: String, title: String) {
134 let shown = self.active == id;
135 if let Some(w) = self.list.iter_mut().find(|w| w.id == id) {
136 if !shown {
137 let (was, now) = (site_of(&w.url), site_of(&url));
139 if was != now && was != NO_SITE {
140 let from = w.moved.take().map(|(from, _)| from).unwrap_or(was);
141 w.moved = if from == now { None } else { Some((from, now)) };
142 }
143 }
144 w.url = url;
145 w.title = title;
146 }
147 }
148
149 pub fn take_moved(&mut self, id: WindowId) -> Option<(String, String)> {
151 self.list.iter_mut().find(|w| w.id == id).and_then(|w| w.moved.take())
152 }
153
154 pub fn message(&self) -> Value {
156 let list: Vec<Value> = self
157 .list
158 .iter()
159 .map(|w| json!({ "id": w.id, "url": w.url, "title": w.title, "opener": w.opener, "closable": w.id != FIRST }))
160 .collect();
161 json!({ "t": "windows", "active": self.active, "windows": list })
162 }
163}
164
165const NO_SITE: &str = "a page";
167
168pub fn site_of(url: &str) -> String {
170 url::Url::parse(url).ok().and_then(|u| u.host_str().map(str::to_string)).filter(|h| !h.is_empty()).unwrap_or_else(|| NO_SITE.to_string())
171}
172
173fn is_hidden(c: char) -> bool {
176 c.is_control()
177 || matches!(c as u32, 0x061C | 0x00AD | 0x180E | 0x200B..=0x200F | 0x202A..=0x202E | 0x2060..=0x206F | 0xFEFF | 0xE0000..=0xE007F)
178}
179
180fn shorten(text: &str, max: usize) -> String {
182 let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" ").chars().filter(|c| !is_hidden(*c)).collect();
184 let one_line = one_line.split_whitespace().collect::<Vec<_>>().join(" ");
185 if one_line.chars().count() <= max {
186 return one_line;
187 }
188 format!("{}…", one_line.chars().take(max).collect::<String>())
189}
190
191pub fn too_many_windows(opener_url: &str) -> String {
193 format!("{} tried to open another window. A pane shows at most {MAX_WINDOWS} windows, so it was closed.", site_of(opener_url))
194}
195
196pub fn dialog_dismissed(page_url: &str, kind: &str, message: &str) -> String {
198 let what = match kind {
199 "confirm" => "a confirmation question",
200 "prompt" => "a question",
201 "beforeunload" => "a question about leaving the page",
202 _ => "a message box",
203 };
204 let said = shorten(message, 100);
205 if said.is_empty() {
206 format!("{} opened {what}. It was dismissed.", site_of(page_url))
207 } else {
208 format!("{} opened {what} (“{said}”). It was dismissed.", site_of(page_url))
209 }
210}
211
212pub fn window_not_shown(opener_url: &str) -> String {
214 format!("{} opened a window that could not be shown, so it was closed.", site_of(opener_url))
215}
216
217pub fn window_changed_site(from: &str, to: &str) -> String {
219 format!("This window went from {from} to {to} while it was not shown.")
220}
221
222const GOOGLE_REFUSAL: (&str, &str) = ("accounts.google.com", "/v3/signin/rejected");
224
225pub fn provider_refusal(url: &str) -> Option<String> {
227 let u = url::Url::parse(url).ok()?;
228 if u.scheme() == "https" && u.host_str() == Some(GOOGLE_REFUSAL.0) && u.path() == GOOGLE_REFUSAL.1 {
229 return Some("Google refused to sign in with this browser. Other sign-in methods on the site, or a Microsoft or GitHub account, may work.".to_string());
230 }
231 None
232}
233
234const NOTICE_EVERY: Duration = Duration::from_secs(3);
236
237#[derive(Debug, Default)]
238pub struct NoticeLimiter {
239 last: Option<Instant>,
240}
241
242impl NoticeLimiter {
243 pub fn allow(&mut self, now: Instant) -> bool {
245 if self.last.is_some_and(|t| now.saturating_duration_since(t) < NOTICE_EVERY) {
246 return false;
247 }
248 self.last = Some(now);
249 true
250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256
257 fn pane() -> Windows {
258 Windows::starting("t0".into(), "s0".into())
259 }
260
261 fn open(w: &mut Windows, n: u32, opener: Option<WindowId>) -> WindowId {
262 w.add(format!("t{n}"), format!("s{n}"), opener).expect("room")
263 }
264
265 #[test]
266 fn a_pane_starts_with_one_window_which_is_shown_and_cannot_be_closed() {
267 let w = pane();
268 assert_eq!((w.len(), w.active()), (1, FIRST));
269 let m = w.message();
270 assert_eq!(m["t"], "windows");
271 assert_eq!(m["windows"][0]["closable"], false);
272 let mut w = pane();
273 assert_eq!(w.remove(FIRST), None);
274 assert_eq!(w.len(), 1);
275 }
276
277 #[test]
278 fn a_window_a_page_opens_is_shown_and_knows_who_opened_it() {
279 let mut w = pane();
280 let popup = open(&mut w, 1, Some(FIRST));
281 assert_eq!(w.active(), popup);
282 assert_eq!(w.get(popup).unwrap().opener, Some(FIRST));
283 assert_eq!(w.message()["windows"][1]["closable"], true);
284 assert_eq!(w.message()["active"], popup);
285 }
286
287 #[test]
288 fn a_page_cannot_open_windows_without_limit() {
289 let mut w = pane();
290 for n in 1..MAX_WINDOWS as u32 {
291 assert!(w.has_room());
292 open(&mut w, n, Some(FIRST));
293 }
294 assert_eq!(w.len(), MAX_WINDOWS);
295 assert!(!w.has_room());
296 assert_eq!(w.add("tx".into(), "sx".into(), Some(FIRST)), None);
297 assert_eq!(w.len(), MAX_WINDOWS);
298 }
299
300 #[test]
301 fn when_the_shown_window_ends_the_one_that_opened_it_is_shown_again() {
302 let mut w = pane();
303 let a = open(&mut w, 1, Some(FIRST));
304 let b = open(&mut w, 2, Some(a));
305 assert_eq!(w.remove(b), Some(Removed { was_active: true, now_active: a }));
306 assert_eq!(w.remove(a), Some(Removed { was_active: true, now_active: FIRST }));
307 assert_eq!(w.active(), FIRST);
308 }
309
310 #[test]
311 fn a_window_that_ends_while_not_shown_changes_nothing_on_screen() {
312 let mut w = pane();
313 let a = open(&mut w, 1, Some(FIRST));
314 let b = open(&mut w, 2, Some(FIRST));
315 assert_eq!(w.active(), b);
316 assert_eq!(w.remove(a), Some(Removed { was_active: false, now_active: b }));
317 assert_eq!(w.remove(a), None, "once");
318 }
319
320 #[test]
321 fn windows_a_closed_window_opened_go_back_to_its_opener() {
322 let mut w = pane();
323 let a = open(&mut w, 1, Some(FIRST));
324 let b = open(&mut w, 2, Some(a));
325 w.remove(a);
326 assert_eq!(w.get(b).unwrap().opener, Some(FIRST));
327 assert_eq!(w.remove(b), Some(Removed { was_active: true, now_active: FIRST }));
328 }
329
330 #[test]
331 fn the_person_can_show_any_window_and_a_window_that_is_not_there_is_refused() {
332 let mut w = pane();
333 let a = open(&mut w, 1, Some(FIRST));
334 assert!(w.focus(FIRST));
335 assert_eq!(w.active(), FIRST);
336 assert!(w.focus(a));
337 assert!(!w.focus(99));
338 assert_eq!(w.active(), a);
339 }
340
341 #[test]
342 fn windows_are_found_by_the_browsers_ids_and_a_closed_ids_number_is_not_reused() {
343 let mut w = pane();
344 let a = open(&mut w, 1, Some(FIRST));
345 assert_eq!(w.by_target("t1"), Some(a));
346 assert_eq!(w.by_session("s1"), Some(a));
347 assert_eq!(w.by_target("nope"), None);
348 w.remove(a);
349 let b = open(&mut w, 2, Some(FIRST));
350 assert_ne!(a, b, "a late message about the old window cannot land on the new one");
351 }
352
353 #[test]
354 fn an_address_is_kept_per_window_and_shown_in_the_message() {
355 let mut w = pane();
356 let a = open(&mut w, 1, Some(FIRST));
357 w.set_location(a, "https://accounts.example.com/login".into(), "Sign in".into());
358 let m = w.message();
359 assert_eq!(m["windows"][1]["url"], "https://accounts.example.com/login");
360 assert_eq!(m["windows"][1]["title"], "Sign in");
361 assert_eq!(m["windows"][0]["url"], "");
362 }
363
364 #[test]
365 fn a_line_names_the_site_and_says_what_was_done() {
366 assert_eq!(site_of("https://login.example.com/a?b=1"), "login.example.com");
367 assert_eq!(site_of("about:blank"), "a page");
368 assert_eq!(site_of(""), "a page");
369 let line = too_many_windows("https://spam.example/x");
370 assert!(line.starts_with("spam.example tried to open another window"), "{line}");
371 assert!(line.contains(&MAX_WINDOWS.to_string()));
372 let d = dialog_dismissed("https://a.example/", "confirm", "Leave the\npage?");
373 assert_eq!(d, "a.example opened a confirmation question (“Leave the page?”). It was dismissed.");
374 assert_eq!(dialog_dismissed("https://a.example/", "alert", ""), "a.example opened a message box. It was dismissed.");
375 assert!(dialog_dismissed("https://a.example/", "alert", &"x".repeat(500)).contains('…'));
376 assert!(window_not_shown("https://a.example/").starts_with("a.example opened a window"));
377 }
378
379 #[test]
380 fn google_s_refusal_is_recognised_by_its_address_and_nothing_else_is() {
381 assert!(provider_refusal("https://accounts.google.com/v3/signin/rejected?dsh=x&flowName=GlifWebSignIn").is_some());
382 for other in [
383 "https://accounts.google.com/v3/signin/identifier",
384 "https://accounts.google.com/signin/rejected",
385 "http://accounts.google.com/v3/signin/rejected",
386 "https://evil.example/v3/signin/rejected",
387 "https://accounts.google.com.evil.example/v3/signin/rejected",
388 "about:blank",
389 "",
390 ] {
391 assert!(provider_refusal(other).is_none(), "{other}");
392 }
393 let line = provider_refusal("https://accounts.google.com/v3/signin/rejected").unwrap();
394 assert!(line.starts_with("Google refused"), "{line}");
395 }
396
397 #[test]
398 fn what_a_page_wrote_is_shown_with_nothing_hidden_in_it_and_after_the_site() {
399 let nasty = "Sign\u{202E}in\u{200B} to\u{2066} pay\u{FEFF}\u{7}\u{E0041} now\u{061C}\u{00AD}";
401 let line = dialog_dismissed("https://a.example/", "alert", nasty);
402 assert_eq!(line, "a.example opened a message box (“Signin to pay now”). It was dismissed.");
403 for c in line.chars() {
404 assert!(!is_hidden(c), "{:?} is still in the line", c);
405 }
406 assert!(line.starts_with("a.example opened"), "{line}");
408 assert_eq!(dialog_dismissed("https://a.example/", "alert", "\u{200B}\u{202E}\n\t"), "a.example opened a message box. It was dismissed.");
410 let link = dialog_dismissed("https://a.example/", "alert", "go to https://evil.example/login now");
412 assert!(link.contains("https://evil.example/login") && !link.contains('<') && !link.contains("]("), "{link}");
413 }
414
415 #[test]
416 fn a_window_that_changed_site_while_not_shown_is_told_once_on_return() {
417 let mut w = pane();
418 w.set_location(FIRST, "https://app.example/".into(), "App".into());
419 let a = open(&mut w, 1, Some(FIRST));
420 w.set_location(a, "https://idp.example/auth".into(), "Sign in".into());
422 assert_eq!(w.take_moved(a), None, "the shown window changing site is not news");
423 w.set_location(FIRST, "https://app.example/other".into(), "App".into());
424 assert_eq!(w.take_moved(FIRST), None, "same site, nothing to say");
425 w.set_location(FIRST, "https://evil.example/".into(), "x".into());
426 w.set_location(FIRST, "https://evil.example/again".into(), "x".into());
427 assert_eq!(w.take_moved(FIRST), Some(("app.example".to_string(), "evil.example".to_string())));
428 assert_eq!(w.take_moved(FIRST), None, "said once");
429 w.set_location(FIRST, "https://other.example/".into(), "x".into());
431 w.set_location(FIRST, "https://evil.example/".into(), "x".into());
432 w.take_moved(FIRST);
433 w.set_location(FIRST, "https://a2.example/".into(), "x".into());
434 w.set_location(FIRST, "https://evil.example/".into(), "x".into());
435 assert_eq!(w.take_moved(FIRST), None);
436 assert_eq!(window_changed_site("a.example", "b.example"), "This window went from a.example to b.example while it was not shown.");
437 }
438
439 #[test]
440 fn keys_are_held_for_half_a_second() {
441 assert_eq!(KEY_GAP, Duration::from_millis(500));
442 }
443
444 #[test]
445 fn notices_are_not_a_flood() {
446 let mut l = NoticeLimiter::default();
447 let t = Instant::now();
448 assert!(l.allow(t));
449 assert!(!l.allow(t + Duration::from_millis(500)));
450 assert!(!l.allow(t + Duration::from_millis(2900)));
451 assert!(l.allow(t + Duration::from_secs(3)));
452 }
453}