Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

26.9 KB
Raw Blame
//! Links that open another app (`tiktok://`, `snssdk1233://`, `intent:`, `itms-apps:`...).
//!
//! Chrome answers one with an "Open <app>?" prompt that is tab-modal: while it is up the tab
//! ignores every click and key, yet scripts, animations and screenshots carry on. A headless
//! browser draws the prompt nowhere the live view can see, and DevTools has no way to answer
//! it. It closes only on a cross-site navigation, so even a reload leaves the page dead.
//!
//! kwnt keeps it from opening in the first place: [`GUARD_JS`] runs in an isolated world of every
//! document and cancels a navigation to such a link before it reaches Chrome. A frame leaving its
//! first, empty document fires no `navigate` event, so the guard can't see that one: TikTok's
//! sign-in fires `bytedance://dispatch_message/` that way, from a hidden iframe it removes after
//! 300 ms, again on every new QR code. For frames the guard also gives every document a content
//! security policy that only lets frames load web pages ([`FRAME_POLICY`]): Chrome blocks such a
//! frame itself, before it would ask, and says so in its log ([`blocked_frame`]).
//! Anything that still gets past both is caught by [`AppLinkWatch`], which tells the live view
//! to step the tab off the page and back, the one thing that closes the prompt, once per app in
//! [`WINDOW`]: a page that opens the same app again on every load isn't reloaded in a loop.
//! A link that fired while no live view was open is found when one opens: [`PROBE_ARM_JS`] and
//! [`PROBE_READ_JS`] check that the page still gets a mouse move, and a tab that doesn't is
//! stepped off and back the same way.
use std::{collections::VecDeque, time::Duration};
use tokio::time::Instant;

/// The isolated world the guard runs in: the page's own scripts can't see or undo it.
pub const WORLD: &str = "kwnt-applinks";
/// Called from [`WORLD`] with the scheme of a link the guard stopped.
pub const BINDING: &str = "kwntAppLink";

/// Schemes a tab opens itself; everything else is handed to the operating system.
const IN_BROWSER: &[&str] = &[
    "http", "https", "about", "data", "blob", "javascript", "file", "filesystem", "ws", "wss",
    "chrome", "chrome-error", "chrome-extension", "chrome-untrusted", "devtools", "view-source",
];
/// Handed to the operating system without a prompt, so they can't freeze the tab.
const NO_PROMPT: &[&str] = &["mailto", "news", "snews"];

/// Chrome's console line when it refuses a link outright (no user gesture) instead of asking.
pub const REFUSED_LOG: &str = "Not allowed to launch";

/// The content security policy every document gets: frames may load web pages (`*` is any
/// http(s) address or one of the page's own scheme) and what a tab opens itself, never another
/// app. Policies only add up, so a page's own policy still holds as it was.
pub const FRAME_POLICY: &str = "frame-src * data: blob: about: filesystem: chrome-extension:";

/// Cancels navigations to another app in this document, and sets [`FRAME_POLICY`] so a frame
/// can't load one either. Runs in [`WORLD`], once per world, before the page's own scripts.
/// The policy goes in as a `<meta>` at the top of `<head>` (as soon as there is one) and the
/// element is taken out again at once: the policy stays, and the page never sees the tag.
pub const GUARD_JS: &str = r#"(() => {
  if (self.__kwntAppLinks || !self.navigation) return;
  self.__kwntAppLinks = true;
  const inBrowser = new Set(__IN_BROWSER__);
  navigation.addEventListener('navigate', (event) => {
    let scheme;
    try { scheme = new URL(event.destination.url).protocol.slice(0, -1).toLowerCase(); } catch (e) { return; }
    if (inBrowser.has(scheme) || !event.cancelable) return;
    event.preventDefault();
    try { self.__BINDING__(scheme); } catch (e) {}
  });
  // a frame leaving its first, empty document fires no navigate event: Chrome blocks that one
  const policy = () => {
    const head = document.head;
    if (!head) return false;
    const meta = document.createElement('meta');
    meta.httpEquiv = 'Content-Security-Policy';
    meta.content = __FRAME_POLICY__;
    head.prepend(meta);
    meta.remove();
    return true;
  };
  if (!policy()) {
    const watch = new MutationObserver(() => { if (policy()) watch.disconnect(); });
    watch.observe(document, { childList: true, subtree: true });
  }
})()"#;

/// [`GUARD_JS`] with its scheme list, binding and policy filled in.
pub fn guard_js() -> String {
    GUARD_JS
        .replace("__IN_BROWSER__", &serde_json::to_string(IN_BROWSER).unwrap_or_default())
        .replace("__BINDING__", BINDING)
        .replace("__FRAME_POLICY__", &serde_json::to_string(FRAME_POLICY).unwrap_or_default())
}

/// Whether Chrome logged `text` because [`FRAME_POLICY`] blocked a frame from opening another
/// app: "Framing '' violates the following Content Security Policy directive: "frame-src *"…".
/// Chrome didn't ask, so the page still takes input.
pub fn blocked_frame(text: &str) -> bool {
    text.starts_with("Framing '") && text.contains("Content Security Policy directive: \"frame-src")
}

/// The scheme of `url` when it opens another app, lowercased. A link the tab opens itself, or
/// one that isn't a URL, gives `None`.
pub fn app_scheme(url: &str) -> Option<String> {
    let (scheme, _) = url.trim_start().split_once(':')?;
    let mut chars = scheme.chars();
    if !chars.next()?.is_ascii_alphabetic() || !chars.all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)) {
        return None;
    }
    let scheme = scheme.to_ascii_lowercase();
    (!IN_BROWSER.contains(&scheme.as_str())).then_some(scheme)
}

/// Schemes that take a phone number (`tel:+38640123456`, `sms:5551234`): digits after the colon
/// are the number, never a port, so `tel:555` is a call, not a host called `tel`.
const NUMBERS: &[&str] = &["tel", "sms", "mms", "callto", "facetime", "facetime-audio", "fax", "sip", "sips"];

/// The port of `url` when it is a web address written without its scheme, `host:port` with an
/// optional path (`localhost:8080/x`, `127.0.0.1:9381`, `example.com:443`). Chrome would read the
/// host as a scheme (`localhost:`) and hand it to the operating system.
pub fn host_port(url: &str) -> Option<u16> {
    let (host, rest) = url.trim().split_once(':')?;
    if host.is_empty() || !host.chars().all(|c| c.is_ascii_alphanumeric() || "-.".contains(c)) { return None; }
    if NUMBERS.iter().any(|n| host.eq_ignore_ascii_case(n)) { return None; }
    let digits = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());
    let (port, after) = rest.split_at(digits);
    if !(after.is_empty() || after.starts_with(['/', '?', '#'])) { return None; }
    port.parse::<u16>().ok().filter(|p| *p > 0)
}

/// The scheme of `url` when it is a link to another app a bot must not open: Chrome would hand it
/// to the operating system or freeze the tab behind an "Open <app>?" prompt. `host:port` without
/// a scheme (`localhost:8080`, see [`host_port`]) isn't one, and neither is a Windows drive
/// (`C:\…`, `c:/…`). A phone number is (`tel:5551234`), digits or not.
pub fn refused_scheme(url: &str) -> Option<String> {
    if host_port(url).is_some() { return None; }
    app_scheme(url).filter(|s| s.len() > 1)
}

/// Why a bot's browser didn't open `url`, a link to another app.
pub fn refused_text(url: &str, scheme: &str) -> String {
    let shown: String = url.trim().chars().take(120).collect();
    format!("{shown} opens another app ({scheme}:), not a web page, so the browser didn't open it: kwnt only opens web pages (http:// and https://). \
             Use a web address instead, or another way on the page such as signing in with a password or code.")
}

/// The scheme of `url` when following it makes Chrome ask whether to open another app.
pub fn prompting_scheme(url: &str) -> Option<String> {
    app_scheme(url).filter(|s| !NO_PROMPT.contains(&s.as_str()))
}

/// A scheme as the person may read it: a scheme the guard reported, checked and cut short.
pub fn shown_scheme(raw: &str) -> Option<String> {
    let scheme = raw.trim().trim_end_matches(':');
    (scheme.len() <= 40).then(|| app_scheme(&format!("{scheme}:"))).flatten()
}

/// How long after a link starts loading Chrome may still refuse it outright (no prompt).
pub const SETTLE: Duration = Duration::from_millis(400);
/// At most this many recoveries in [`WINDOW`], and at most one per app: a page that opens its
/// app again on every load would otherwise be stepped off and back forever.
pub const MAX_RECOVERIES: usize = 3;
pub const WINDOW: Duration = Duration::from_secs(60);
/// The person is told about a stopped link at most this often.
pub const NOTICE_GAP: Duration = Duration::from_secs(5);

/// What the live view should do about a link to another app. The scheme is `None` when the
/// tab was found ignoring input without the live view seeing the link (it fired before it opened).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
    /// Chrome is asking: step the tab off the page and back, then tell the person.
    Recover(Option<String>),
    /// Chrome is asking again too often, or again for an app it was just recovered from: leave
    /// the page as it is and tell the person why.
    GiveUp(Option<String>),
}

/// Marks where a mouse move should land in the page and starts counting the moves that reach
/// it: `[x, y]`, or `null` when there is no point to probe (the page is all frames, or has no
/// size, or no one sees it). Runs in the page's main world; the probe removes itself in
/// [`PROBE_READ_JS`]. A frame in a closed shadow root can't be seen from the page, so a point
/// over one is still probed.
pub const PROBE_ARM_JS: &str = r#"(() => {
  const w = innerWidth, h = innerHeight, key = Symbol.for('kwnt.inputProbe');
  // Chrome holds mouse moves for a page no one sees until its next frame, which a hidden page
  // doesn't draw: they would never arrive, and a live background tab would look stuck
  if (document.visibilityState !== 'visible') return null;
  if (!(w > 32 && h > 32)) return null;
  for (const [x, y] of [[8, 8], [w - 9, h - 9], [8, h - 9], [w - 9, 8], [w >> 1, h >> 1]]) {
    let el = document.elementFromPoint(x, y);
    // a frame inside a web component: the page sees its host, the move goes to the frame
    for (let i = 0; el && el.shadowRoot && i < 16; i++) {
      const inner = el.shadowRoot.elementFromPoint(x, y);
      if (!inner || inner === el) break;
      el = inner;
    }
    if (!el || /^(IFRAME|FRAME|EMBED|OBJECT|FENCEDFRAME|PORTAL)$/.test(el.tagName)) continue;
    if (self[key]) removeEventListener('mousemove', self[key].on, true);
    const probe = { n: 0, on: () => { probe.n++; } };
    self[key] = probe;
    addEventListener('mousemove', probe.on, true);
    return [x, y];
  }
  return null;
})()"#;

/// How many probe moves reached the page, or -1 when the probe is gone (a new document).
pub const PROBE_READ_JS: &str = r#"(() => {
  const key = Symbol.for('kwnt.inputProbe'), probe = self[key];
  if (!probe) return -1;
  removeEventListener('mousemove', probe.on, true);
  delete self[key];
  return probe.n;
})()"#;

/// Watches the page's navigations for a link to another app that got past the guard.
#[derive(Debug, Default)]
pub struct AppLinkWatch {
    pending: Option<(String, Instant)>,
    /// When each recovery in the last [`WINDOW`] ran, and for which app (`None`: a tab found stuck).
    recoveries: VecDeque<(Instant, Option<String>)>,
    noticed: Option<Instant>,
}

impl AppLinkWatch {
    /// A frame started loading `url`.
    pub fn started(&mut self, url: &str, now: Instant) {
        if self.pending.is_some() { return; }
        if let Some(scheme) = prompting_scheme(url) { self.pending = Some((scheme, now + SETTLE)); }
    }

    /// Chrome logged `text`. A refusal, or a frame [`FRAME_POLICY`] blocked, means it didn't
    /// ask, so the page still takes input.
    pub fn logged(&mut self, text: &str) {
        if text.starts_with(REFUSED_LOG) || blocked_frame(text) { self.pending = None; }
    }

    /// When [`Self::due`] has something to say.
    pub fn deadline(&self) -> Option<Instant> {
        self.pending.as_ref().map(|(_, at)| *at)
    }

    /// What to do once the link has had [`SETTLE`] to be refused.
    pub fn due(&mut self, now: Instant) -> Option<Verdict> {
        let (_, at) = self.pending.as_ref()?;
        if now < *at { return None; }
        let (scheme, _) = self.pending.take()?;
        Some(self.verdict(Some(scheme), now))
    }

    /// The tab was found ignoring input when the live view opened: a link fired before it did.
    /// Counts against the same cap as a link the live view saw.
    pub fn stuck(&mut self, now: Instant) -> Verdict {
        self.verdict(None, now)
    }

    fn verdict(&mut self, scheme: Option<String>, now: Instant) -> Verdict {
        while self.recoveries.front().is_some_and(|(t, _)| now.duration_since(*t) >= WINDOW) { self.recoveries.pop_front(); }
        // the page loads again on a recovery and opens the same app again: one reload is enough
        let again = scheme.is_some() && self.recoveries.iter().any(|(_, s)| *s == scheme);
        if again || self.recoveries.len() >= MAX_RECOVERIES { return Verdict::GiveUp(scheme); }
        self.recoveries.push_back((now, scheme.clone()));
        Verdict::Recover(scheme)
    }

    /// Whether the person may be told about another stopped link now.
    pub fn may_notice(&mut self, now: Instant) -> bool {
        if self.noticed.is_some_and(|t| now.duration_since(t) < NOTICE_GAP) { return false; }
        self.noticed = Some(now);
        true
    }
}

/// Said when the guard stopped a link to another app.
pub fn stopped_text(scheme: &str) -> String {
    format!("This page tried to open another app ({scheme}:), which can't open from here, so kwnt stopped it. Use another way on the page, such as signing in with a password or code.")
}

/// Said after kwnt stepped the tab off the page and back to close Chrome's prompt.
pub fn recovered_text(scheme: Option<&str>) -> String {
    match scheme {
        Some(scheme) => format!("This page tried to open another app ({scheme}:), and the browser stopped taking clicks and keys while it waited. kwnt reloaded the page so you can use it again."),
        None => "This page had stopped taking clicks and keys, most likely because it tried to open another app before you opened the view. kwnt reloaded the page so you can use it again.".into(),
    }
}

/// Said when the page keeps opening its app and kwnt stopped reloading it.
pub fn gave_up_text(scheme: Option<&str>) -> String {
    match scheme {
        Some(scheme) => format!("This page keeps trying to open another app ({scheme}:), and the browser ignores clicks and keys while it does. Open another page from the address bar to carry on."),
        None => "This page keeps ignoring clicks and keys, most likely because it keeps trying to open another app. Open another page from the address bar to carry on.".into(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn links_to_other_apps_are_told_from_pages_the_tab_opens_itself() {
        for url in ["snssdk1233://login?x=1", "tiktok://user", "TikTok://x", "intent://scan/#Intent;scheme=z;end", "itms-apps://a", "zoommtg:join", "web+app:x"] {
            assert!(prompting_scheme(url).is_some(), "{url}");
        }
        assert_eq!(prompting_scheme("TikTok://x").as_deref(), Some("tiktok"));
        for url in ["https://www.tiktok.com/login", "http://a", "about:blank", "about:srcdoc", "data:text/html,x", "blob:https://a/1", "javascript:void(0)",
            "chrome-error://chromewebdata/", "file:///tmp/a", "", "no scheme", "/relative", "1abc:x", "a b:c"] {
            assert_eq!(prompting_scheme(url), None, "{url}");
        }
        // mail links are handed over without a prompt, so they can't freeze the tab
        assert_eq!(app_scheme("mailto:[email protected]").as_deref(), Some("mailto"));
        assert_eq!(prompting_scheme("mailto:[email protected]"), None);
        assert_eq!(shown_scheme("snssdk1233:").as_deref(), Some("snssdk1233"));
        assert_eq!(shown_scheme("https"), None);
        assert_eq!(shown_scheme(&"a".repeat(41)), None);
        assert_eq!(shown_scheme("<b>x</b>"), None);
    }

    #[test]
    fn the_guard_lets_the_tab_open_what_it_opens_itself() {
        let js = guard_js();
        for scheme in IN_BROWSER { assert!(js.contains(&format!("\"{scheme}\"")), "{scheme}"); }
        assert!(js.contains("self.kwntAppLink(scheme)"));
        assert!(js.contains("event.preventDefault()"));
        assert!(!js.contains("__IN_BROWSER__") && !js.contains("__BINDING__"), "{js}");
    }

    #[test]
    fn a_link_chrome_refuses_outright_needs_no_recovery() {
        let mut watch = AppLinkWatch::default();
        let t = Instant::now();
        watch.started("snssdk1233://login", t);
        assert_eq!(watch.deadline(), Some(t + SETTLE));
        watch.logged("Not allowed to launch 'snssdk1233://login' because a user gesture is required.");
        assert_eq!(watch.due(t + SETTLE), None);
        assert_eq!(watch.deadline(), None);
        // web pages and mail links never start one
        watch.started("https://www.tiktok.com/", t);
        watch.started("mailto:[email protected]", t);
        assert_eq!(watch.deadline(), None);
    }

    #[test]
    fn a_prompt_is_recovered_after_it_settles_a_few_times_a_minute_at_most() {
        let mut watch = AppLinkWatch::default();
        let t = Instant::now();
        let apps = ["snssdk1233", "tiktok", "zoommtg"];
        for (i, app) in apps.iter().enumerate() {
            let at = t + Duration::from_secs(i as u64);
            watch.started(&format!("{app}://login"), at);
            watch.started("intent://second-in-the-same-burst", at);
            assert_eq!(watch.due(at + SETTLE / 2), None, "Chrome may still refuse it");
            assert_eq!(watch.due(at + SETTLE), Some(Verdict::Recover(Some(app.to_string()))));
            assert_eq!(watch.due(at + SETTLE), None, "once per link");
        }
        assert_eq!(apps.len(), MAX_RECOVERIES);
        watch.started("itms-apps://x", t + Duration::from_secs(10));
        assert_eq!(watch.due(t + Duration::from_secs(11)), Some(Verdict::GiveUp(Some("itms-apps".into()))));
        // a minute after the first, one may run again
        watch.started("snssdk1233://login", t + WINDOW);
        assert_eq!(watch.due(t + WINDOW + SETTLE), Some(Verdict::Recover(Some("snssdk1233".into()))));
    }

    #[test]
    fn a_page_that_opens_the_same_app_on_every_load_is_reloaded_once() {
        // TikTok's sign-in fires bytedance: on every new QR code, and a reload makes a new one
        let mut watch = AppLinkWatch::default();
        let t = Instant::now();
        let link = "bytedance://dispatch_message/";
        watch.started(link, t);
        assert_eq!(watch.due(t + SETTLE), Some(Verdict::Recover(Some("bytedance".into()))));
        for secs in [2, 5, 30, 59] {
            let at = t + Duration::from_secs(secs);
            watch.started(link, at);
            assert_eq!(watch.due(at + SETTLE), Some(Verdict::GiveUp(Some("bytedance".into()))), "{secs}s: not reloaded again");
        }
        // another app may still be recovered, and the same one once the window has passed
        watch.started("snssdk1233://login", t + Duration::from_secs(3));
        assert_eq!(watch.due(t + Duration::from_secs(4)), Some(Verdict::Recover(Some("snssdk1233".into()))));
        watch.started(link, t + WINDOW);
        assert_eq!(watch.due(t + WINDOW + SETTLE), Some(Verdict::Recover(Some("bytedance".into()))));
    }

    #[test]
    fn a_frame_the_policy_blocked_needs_no_recovery() {
        // Chrome 154's line when FRAME_POLICY blocks TikTok's hidden bytedance: frame
        let blocked = "Framing '' violates the following Content Security Policy directive: \"frame-src * data: blob: about: filesystem: chrome-extension:\". \
                       The request has been blocked. Note that '*' matches only URLs with network schemes ('http', 'https', 'ws', 'wss'), or URLs whose scheme matches `self`'s scheme.";
        assert!(blocked_frame(blocked));
        for other in ["Framing 'https://a/' violates the following Content Security Policy directive: \"default-src 'self'\".",
            "Refused to load the script 'x' because it violates the following Content Security Policy directive: \"frame-src *\"", "Not allowed to launch 'x:'", ""] {
            assert!(!blocked_frame(other), "{other}");
        }
        let mut watch = AppLinkWatch::default();
        let t = Instant::now();
        watch.started("bytedance://dispatch_message/", t);
        watch.logged(blocked);
        assert_eq!(watch.deadline(), None);
        assert_eq!(watch.due(t + SETTLE), None);
    }

    #[test]
    fn the_guard_keeps_frames_to_web_pages_only() {
        let js = guard_js();
        assert!(js.contains(&format!("meta.content = {};", serde_json::to_string(FRAME_POLICY).unwrap())), "{js}");
        assert!(js.contains("'Content-Security-Policy'") && js.contains("meta.remove()") && js.contains("MutationObserver"));
        // the policy names no app scheme and every frame scheme the tab opens itself
        assert!(FRAME_POLICY.starts_with("frame-src * "));
        for scheme in ["data:", "blob:", "about:", "filesystem:", "chrome-extension:"] { assert!(FRAME_POLICY.contains(scheme), "{scheme}"); }
        assert!(!js.contains("__FRAME_POLICY__"));
    }

    #[test]
    fn a_tab_found_stuck_is_recovered_under_the_same_cap() {
        let mut watch = AppLinkWatch::default();
        let t = Instant::now();
        assert_eq!(watch.stuck(t), Verdict::Recover(None));
        for i in 1..MAX_RECOVERIES as u64 {
            watch.started(&format!("app{i}://login"), t + Duration::from_secs(i));
            assert!(matches!(watch.due(t + Duration::from_secs(i) + SETTLE), Some(Verdict::Recover(_))));
        }
        assert_eq!(watch.stuck(t + Duration::from_secs(10)), Verdict::GiveUp(None));
        assert_eq!(watch.stuck(t + WINDOW), Verdict::Recover(None));
        assert!(recovered_text(None).contains("reloaded the page"));
        assert!(!gave_up_text(None).contains("reloaded"));
    }

    #[test]
    fn a_bot_is_refused_links_to_other_apps_but_not_web_pages() {
        for (url, scheme) in [("tiktok://open", "tiktok"), ("snssdk1233://login", "snssdk1233"), ("intent://scan/#Intent;scheme=zxing;end", "intent"),
            ("intent:#Intent;end", "intent"), (" TikTok://x", "tiktok"), ("mailto:[email protected]", "mailto"), ("itms-apps://a", "itms-apps"), ("zoommtg:join", "zoommtg")] {
            assert_eq!(refused_scheme(url).as_deref(), Some(scheme), "{url}");
        }
        for url in ["https://www.tiktok.com/login", "http://a", "about:blank", "data:text/html,x", "javascript:void(0)", "chrome://version",
            "localhost:8080", "example.com:443/x", "127.0.0.1:9381", "www.tiktok.com", "", "/relative", "C:\\Users\\me\\file.txt", "c:/Users/me/file.txt"] {
            assert_eq!(refused_scheme(url), None, "{url}");
        }
        let text = refused_text("tiktok://open", "tiktok");
        assert!(text.contains("another app (tiktok:)") && text.contains("only opens web pages"), "{text}");
        assert!(refused_text(&"x".repeat(500), "x").len() < 400, "a long link is cut short");
    }

    #[test]
    fn a_phone_number_opens_another_app_and_host_port_is_a_web_address() {
        // digits after the colon are a number to call or text, not a port
        for (url, scheme) in [("tel:5551234", "tel"), ("tel:+38640123456", "tel"), ("TEL:555", "tel"), ("sms:5551234", "sms"), ("sms:+38640123456?body=hi", "sms"),
            ("tel:555/1", "tel"), ("callto:5551234", "callto"), ("facetime:5551234", "facetime"), ("zoommtg:123456789", "zoommtg"), ("tiktok:12x", "tiktok")] {
            assert_eq!(refused_scheme(url).as_deref(), Some(scheme), "{url}");
            assert_eq!(host_port(url), None, "{url}");
        }
        // a host and a port with no scheme: Chrome must not read the host as one
        for (url, port) in [("localhost:8080", 8080), ("localhost:8080/target.html", 8080), (" LocalHost:3000?x=1", 3000), ("127.0.0.1:9411/a", 9411),
            ("example.com:443/x", 443), ("dev-box:5173#top", 5173)] {
            assert_eq!(host_port(url), Some(port), "{url}");
            assert_eq!(refused_scheme(url), None, "{url}");
        }
        for url in ["localhost", "localhost:", "localhost:0", "localhost:70000", "localhost:80abc", "http://localhost:8080", "a b:80", ":80", "C:\\x"] {
            assert_eq!(host_port(url), None, "{url}");
        }
    }

    /// Runs [`PROBE_ARM_JS`] in Node against a stand-in page: `page` sets `visibilityState` and
    /// what `elementFromPoint` finds. Gives the probe's answer as JSON.
    fn arm_probe_in(page: &str) -> String {
        let script = format!(r#"
          globalThis.self = globalThis; globalThis.innerWidth = 800; globalThis.innerHeight = 600;
          globalThis.addEventListener = () => {{}}; globalThis.removeEventListener = () => {{}};
          const el = (tagName, shadow) => ({{ tagName, shadowRoot: shadow ? {{ elementFromPoint: () => shadow }} : null }});
          globalThis.document = {{ visibilityState: 'visible', elementFromPoint: () => el('DIV') }};
          {page}
          console.log(JSON.stringify({PROBE_ARM_JS}));"#);
        let out = std::process::Command::new("node").args(["-e", &script]).output().expect("node runs the probe (CI and dev machines have it)");
        assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    #[test]
    fn the_input_probe_leaves_a_page_no_one_sees_alone() {
        assert_eq!(arm_probe_in(""), "[8,8]", "a page on screen is probed");
        // a background tab gets no mouse moves until it is shown, so it would read as stuck
        assert_eq!(arm_probe_in("document.visibilityState = 'hidden';"), "null");
        assert_eq!(arm_probe_in("document.visibilityState = 'prerender';"), "null");
    }

    #[test]
    fn the_input_probe_skips_a_frame_inside_a_web_component() {
        // the page sees the component's host; the move goes to the frame inside it
        assert_eq!(arm_probe_in("document.elementFromPoint = () => el('EMBED-WIDGET', el('IFRAME'));"), "null");
        assert_eq!(arm_probe_in("document.elementFromPoint = () => el('OUTER-X', el('INNER-Y', el('IFRAME')));"), "null", "nested components");
        // a component with ordinary content is still probed, and one whose root finds itself ends the walk
        assert_eq!(arm_probe_in("document.elementFromPoint = () => el('MY-APP', el('DIV'));"), "[8,8]");
        assert_eq!(arm_probe_in("const host = el('MY-APP'); host.shadowRoot = { elementFromPoint: () => host }; document.elementFromPoint = () => host;"), "[8,8]");
    }

    #[test]
    fn the_input_probe_skips_frames_and_cleans_up() {
        assert!(PROBE_ARM_JS.contains("elementFromPoint") && PROBE_ARM_JS.contains("IFRAME"));
        assert!(PROBE_ARM_JS.contains("addEventListener('mousemove'") && PROBE_READ_JS.contains("removeEventListener('mousemove'"));
        assert!(PROBE_READ_JS.contains("return -1"), "a new document is no proof the tab is stuck");
    }

    #[test]
    fn notices_are_spaced_out() {
        let mut watch = AppLinkWatch::default();
        let t = Instant::now();
        assert!(watch.may_notice(t));
        assert!(!watch.may_notice(t + NOTICE_GAP / 2));
        assert!(watch.may_notice(t + NOTICE_GAP));
    }
}