Skip to main content

egui_pop_model/
links.rs

1//! Links' pure parts (ADR 0017): a target parsed and classified, the
2//! request to open it, and the one policy deciding how it opens and
3//! whether the user confirms first. No egui and no system call: the
4//! service, the openers, the widget and the confirmation are
5//! `egui_pop_api::links`'.
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! - A **target** ([`Target`]) is a URL (`https:`, `mailto:`, `file:`,
11//!   `docs:`, `command:`, the application's own scheme) or an absolute
12//!   local path, parsed once; its host is kept in punycode and shown in
13//!   Unicode.
14//! - A **request** ([`Request`]) names the target, **how** ([`How`]:
15//!   `Auto`, `Outside`, `Inside`, `Reveal`), its **source** ([`Source`]:
16//!   declared by the application, found in content, asked by an agent),
17//!   the text it was shown under, and who asks.
18//! - The **policy** ([`Policy::decide`]) classifies the target
19//!   ([`Kind`]), resolves `Auto` against what the opener can do
20//!   ([`Caps`]) and says whether to confirm, or why it is refused.
21//!
22//! ```
23//! use egui_pop_model::links::{Caps, Facts, How, Kind, Policy, Request, Source};
24//!
25//! let policy = Policy::default();
26//! let about = Request::new("https://github.com/quazardous/egui-pop");
27//! let d = policy.decide(&about, &Caps::ALL, None);
28//! assert_eq!((d.kind, d.how, d.confirm), (Kind::Web, How::Outside, false));
29//!
30//! // The same page found in a document asks first, until its host is
31//! // trusted for the session.
32//! let found = about.clone().source(Source::Content);
33//! assert!(policy.decide(&found, &Caps::ALL, None).confirm);
34//!
35//! // A local executable is never opened: Reveal is offered instead.
36//! let tool = Request::new("/opt/tool/run.sh");
37//! let d = policy.decide(&tool, &Caps::ALL, Some(&Facts::file()));
38//! assert!(d.refused.is_some() && d.reveal_instead);
39//! ```
40
41pub mod inline;
42
43use std::collections::BTreeSet;
44use std::fmt;
45
46use serde::{Deserialize, Serialize};
47use serde_json::Value as Json;
48use url::Url;
49
50use crate::commands::Origin;
51
52/// How a link opens.
53#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
54#[serde(rename_all = "lowercase")]
55pub enum How {
56    /// What the policy picks for its kind (a plain click).
57    #[default]
58    Auto,
59    /// Outside the application: the browser, the mail client, the
60    /// system's default application, the file manager (Ctrl+click,
61    /// middle click).
62    Outside,
63    /// Inside the application: its viewer, its own scheme, a command.
64    Inside,
65    /// The file manager, with the file selected.
66    Reveal,
67}
68
69impl How {
70    pub fn as_str(self) -> &'static str {
71        match self {
72            How::Auto => "auto",
73            How::Outside => "outside",
74            How::Inside => "inside",
75            How::Reveal => "reveal",
76        }
77    }
78}
79
80/// Where a link comes from: what the policy trusts.
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
82#[serde(rename_all = "lowercase")]
83pub enum Source {
84    /// Declared by the application: its About, menus, tips, toasts,
85    /// `docs:` pages.
86    #[default]
87    Declared,
88    /// Found in content: a document, a remote page, a terminal's output,
89    /// a paste.
90    Content,
91    /// Asked by an agent (or a script, a remote process).
92    Agent,
93}
94
95impl Source {
96    pub fn as_str(self) -> &'static str {
97        match self {
98            Source::Declared => "declared",
99            Source::Content => "content",
100            Source::Agent => "agent",
101        }
102    }
103}
104
105/// What a target is, from its scheme, host and extension (never by
106/// fetching it).
107#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
108#[serde(rename_all = "snake_case")]
109pub enum Kind {
110    /// A web page (`https:`, `http:`).
111    Web,
112    /// A video: a video host's page, or a video file, remote or local.
113    Video,
114    /// A page the application ships (`docs:`).
115    Doc,
116    /// A remote markdown file.
117    Markdown,
118    /// A remote HTML file.
119    Html,
120    /// An image, remote or local.
121    Image,
122    /// A local file.
123    File,
124    /// A local folder.
125    Folder,
126    /// An address (`mailto:`).
127    Mail,
128    /// The application's own scheme (`<app>://`).
129    AppLink,
130    /// A command (`command:<id>?<json>`).
131    Command,
132    /// Nothing that may be opened (see the decision's reason).
133    Blocked,
134}
135
136impl Kind {
137    pub fn as_str(self) -> &'static str {
138        match self {
139            Kind::Web => "web",
140            Kind::Video => "video",
141            Kind::Doc => "doc",
142            Kind::Markdown => "markdown",
143            Kind::Html => "html",
144            Kind::Image => "image",
145            Kind::File => "file",
146            Kind::Folder => "folder",
147            Kind::Mail => "mail",
148            Kind::AppLink => "app_link",
149            Kind::Command => "command",
150            Kind::Blocked => "blocked",
151        }
152    }
153}
154
155/// Why a link is refused.
156#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
157#[serde(tag = "code", content = "detail", rename_all = "snake_case")]
158pub enum Reason {
159    /// Nothing to open.
160    Empty,
161    /// Neither a URL nor an absolute path.
162    Unparsable(String),
163    /// A scheme the policy does not allow (`javascript:`, `data:`...).
164    Scheme(String),
165    /// A device (`/dev/...`, `\\.\...`).
166    Device,
167    /// An executable or a script: never opened, Reveal offered.
168    Executable,
169    /// A file that is not there.
170    Missing,
171    /// A `command:` link outside text the application declared, or asked
172    /// by an agent.
173    UndeclaredCommand,
174    /// Content opens only on a click.
175    NoGesture,
176    /// The way asked does not apply to this kind (Reveal of a web page).
177    NotApplicable(String),
178    /// The opener cannot do it here (local files on the web build, no
179    /// viewer).
180    Unsupported(String),
181}
182
183impl fmt::Display for Reason {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        match self {
186            Reason::Empty => write!(f, "the link is empty"),
187            Reason::Unparsable(t) => write!(f, "`{t}` is neither an address nor a full path"),
188            Reason::Scheme(s) => write!(f, "`{s}:` links are blocked"),
189            Reason::Device => write!(f, "a device cannot be opened"),
190            Reason::Executable => {
191                write!(f, "a program or a script is never opened from a link")
192            }
193            Reason::Missing => write!(f, "the file is not there"),
194            Reason::UndeclaredCommand => {
195                write!(
196                    f,
197                    "a command link runs only from the application's own text"
198                )
199            }
200            Reason::NoGesture => write!(f, "a link in content opens only on a click"),
201            Reason::NotApplicable(w) | Reason::Unsupported(w) => write!(f, "{w}"),
202        }
203    }
204}
205
206/// A parsed target.
207#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct Target {
209    url: Url,
210    /// It was given as a local path.
211    path_given: bool,
212}
213
214/// Extensions of programs and scripts: never opened from a link.
215pub const EXECUTABLE: &[&str] = &[
216    "exe", "com", "bat", "cmd", "msi", "msp", "scr", "pif", "cpl", "ps1", "psm1", "vbs", "vbe",
217    "js", "jse", "wsf", "wsh", "hta", "jar", "reg", "lnk", "sh", "bash", "zsh", "csh", "fish",
218    "ksh", "command", "run", "bin", "desktop", "app", "appimage", "deb", "rpm", "pkg", "dmg", "py",
219    "pyw", "pl", "rb", "php",
220];
221
222const IMAGES: &[&str] = &[
223    "png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "svg", "tif", "tiff", "heic", "jxl",
224];
225/// The extensions of video files, in lower case.
226pub const VIDEOS: &[&str] = &["mp4", "webm", "mov", "mkv", "ogv", "m4v", "avi"];
227
228impl Target {
229    /// Parses a URL, or an absolute local path (`/home/a.png`,
230    /// `C:\a.png`, `\\server\share\a.png`) made a `file:` URL.
231    pub fn parse(text: &str) -> Result<Target, Reason> {
232        let t = text.trim();
233        if t.is_empty() {
234            return Err(Reason::Empty);
235        }
236        if is_path(t) {
237            return path_url(t)
238                .map(|url| Target {
239                    url,
240                    path_given: true,
241                })
242                .ok_or_else(|| Reason::Unparsable(t.into()));
243        }
244        Url::parse(t)
245            .map(|url| Target {
246                url,
247                path_given: false,
248            })
249            .map_err(|_| Reason::Unparsable(t.into()))
250    }
251
252    /// The target as a URL, canonical (`https://example.org/`).
253    pub fn as_str(&self) -> &str {
254        self.url.as_str()
255    }
256
257    pub fn url(&self) -> &Url {
258        &self.url
259    }
260
261    /// The scheme, lowercase (`https`).
262    pub fn scheme(&self) -> &str {
263        self.url.scheme()
264    }
265
266    /// The host as the address carries it (punycode for an
267    /// internationalised one).
268    pub fn host_ascii(&self) -> Option<&str> {
269        self.url.host_str().filter(|h| !h.is_empty())
270    }
271
272    /// The host as a person reads it (Unicode).
273    pub fn host(&self) -> Option<String> {
274        let ascii = self.host_ascii()?;
275        if !ascii.contains("xn--") {
276            return Some(ascii.to_string());
277        }
278        let (unicode, ok) = idna::domain_to_unicode(ascii);
279        Some(if ok.is_ok() { unicode } else { ascii.into() })
280    }
281
282    /// Whether the host is internationalised: its Unicode form and its
283    /// punycode differ, and both are shown.
284    pub fn is_idn(&self) -> bool {
285        self.host_ascii().is_some_and(|h| h.contains("xn--"))
286    }
287
288    /// The host as shown to the user: Unicode, with its punycode beside
289    /// it when they differ (`bücher.example (xn--bcher-kva.example)`).
290    pub fn host_shown(&self) -> Option<String> {
291        let ascii = self.host_ascii()?;
292        let unicode = self.host()?;
293        Some(if unicode == ascii {
294            unicode
295        } else {
296            format!("{unicode} ({ascii})")
297        })
298    }
299
300    /// The video of a YouTube link, when it names one: `watch?v=<id>`,
301    /// `youtu.be/<id>`, `embed/<id>`, `shorts/<id>` and `live/<id>` on
302    /// `youtube.com`, `youtube-nocookie.com` and their subdomains, over
303    /// `https:` only. The id is YouTube's eleven letters, digits, `-` and
304    /// `_`; anything else names no video.
305    pub fn youtube_id(&self) -> Option<String> {
306        if self.scheme() != "https" {
307            return None;
308        }
309        let host = self
310            .host_ascii()?
311            .trim_end_matches('.')
312            .to_ascii_lowercase();
313        let on = |domain: &str| host == domain || host.ends_with(&format!(".{domain}"));
314        let mut path = self.url.path_segments()?.filter(|s| !s.is_empty());
315        let id = if host == "youtu.be" {
316            path.next()?.to_string()
317        } else if on("youtube.com") || on("youtube-nocookie.com") {
318            match path.next()? {
319                "watch" => self
320                    .url
321                    .query_pairs()
322                    .find(|(k, _)| k == "v")
323                    .map(|(_, v)| v.into_owned())?,
324                "embed" | "shorts" | "live" => path.next()?.to_string(),
325                _ => return None,
326            }
327        } else {
328            return None;
329        };
330        let valid = id.len() == 11
331            && id
332                .bytes()
333                .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
334        valid.then_some(id)
335    }
336
337    /// The local path of a `file:` target.
338    pub fn local_path(&self) -> Option<String> {
339        if self.scheme() != "file" {
340            return None;
341        }
342        file_path(&self.url)
343    }
344
345    /// The text to show for it: the path when one was given, else the
346    /// URL.
347    pub fn shown(&self) -> String {
348        match (self.path_given, self.local_path()) {
349            (true, Some(p)) => p,
350            _ => self.url.as_str().to_string(),
351        }
352    }
353
354    /// The extension of its last path segment, lowercase.
355    pub fn extension(&self) -> Option<String> {
356        let last = self.url.path_segments()?.next_back()?;
357        let (_, ext) = last.rsplit_once('.')?;
358        (!ext.is_empty()).then(|| ext.to_ascii_lowercase())
359    }
360
361    /// Whether its extension is a program's or a script's.
362    pub fn looks_executable(&self) -> bool {
363        self.extension()
364            .is_some_and(|e| EXECUTABLE.contains(&e.as_str()))
365    }
366
367    /// A `command:` target's command and arguments (`command:view.zoom?{"to":2}`,
368    /// the JSON percent-encoded or not).
369    pub fn command(&self) -> Option<(String, Json)> {
370        if self.scheme() != "command" {
371            return None;
372        }
373        let id = percent_decode(self.url.path());
374        if id.is_empty() {
375            return None;
376        }
377        let args = match self.url.query() {
378            Some(q) if !q.is_empty() => serde_json::from_str(&percent_decode(q)).ok()?,
379            _ => Json::Null,
380        };
381        Some((id, args))
382    }
383
384    /// A `docs:` target's page (`docs:guide/start#install` gives
385    /// `guide/start`).
386    pub fn doc_page(&self) -> Option<String> {
387        (self.scheme() == "docs").then(|| percent_decode(self.url.path()))
388    }
389}
390
391impl fmt::Display for Target {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        f.write_str(&self.shown())
394    }
395}
396
397fn is_path(t: &str) -> bool {
398    let b = t.as_bytes();
399    t.starts_with('/')
400        || t.starts_with("\\\\")
401        || (b.len() >= 3
402            && b[0].is_ascii_alphabetic()
403            && b[1] == b':'
404            && matches!(b[2], b'\\' | b'/'))
405}
406
407#[cfg(any(unix, windows))]
408fn path_url(p: &str) -> Option<Url> {
409    Url::from_file_path(p).ok()
410}
411
412#[cfg(not(any(unix, windows)))]
413fn path_url(_: &str) -> Option<Url> {
414    None
415}
416
417#[cfg(any(unix, windows))]
418fn file_path(url: &Url) -> Option<String> {
419    url.to_file_path().ok().map(|p| p.display().to_string())
420}
421
422#[cfg(not(any(unix, windows)))]
423fn file_path(url: &Url) -> Option<String> {
424    Some(percent_decode(url.path()))
425}
426
427/// Decodes `%xx` sequences (invalid ones are kept as they are).
428pub fn percent_decode(text: &str) -> String {
429    let b = text.as_bytes();
430    let mut out = Vec::with_capacity(b.len());
431    let mut i = 0;
432    while i < b.len() {
433        if b[i] == b'%'
434            && i + 2 < b.len()
435            && let (Some(h), Some(l)) = (hex(b[i + 1]), hex(b[i + 2]))
436        {
437            out.push(h * 16 + l);
438            i += 3;
439        } else {
440            out.push(b[i]);
441            i += 1;
442        }
443    }
444    String::from_utf8_lossy(&out).into_owned()
445}
446
447fn hex(c: u8) -> Option<u8> {
448    match c {
449        b'0'..=b'9' => Some(c - b'0'),
450        b'a'..=b'f' => Some(c - b'a' + 10),
451        b'A'..=b'F' => Some(c - b'A' + 10),
452        _ => None,
453    }
454}
455
456/// Whether a text looks like an address (`https://…`, `www.…`,
457/// `example.org/…`, `mailto:…`): a link shown under such a text must go
458/// there, or it is confirmed with both shown.
459pub fn looks_like_url(text: &str) -> bool {
460    let t = text.trim();
461    if t.is_empty() || t.contains(char::is_whitespace) {
462        return false;
463    }
464    let lower = t.to_lowercase();
465    if [
466        "http://", "https://", "www.", "mailto:", "file://", "ftp://",
467    ]
468    .iter()
469    .any(|p| lower.starts_with(p))
470    {
471        return true;
472    }
473    let host = lower.split(['/', '?', '#']).next().unwrap_or_default();
474    let parts: Vec<&str> = host.split('.').collect();
475    let Some(tld) = parts.last() else {
476        return false;
477    };
478    parts.len() >= 2
479        && parts
480            .iter()
481            .all(|p| !p.is_empty() && p.chars().all(|c| c.is_alphanumeric() || c == '-'))
482        && tld.chars().count() >= 2
483        && tld.chars().all(char::is_alphabetic)
484}
485
486/// Whether a link's text looks like an address other than its target's
487/// (another host, or another page on it).
488pub fn disguised(label: &str, target: &Target) -> bool {
489    if !looks_like_url(label) {
490        return false;
491    }
492    let l = label.trim();
493    let lower = l.to_lowercase();
494    if let Some(addr) = lower.strip_prefix("mailto:") {
495        return target.scheme() != "mailto" || target.url.path().to_lowercase() != addr;
496    }
497    let shown = if lower.contains("://") {
498        l.to_string()
499    } else {
500        format!("https://{l}")
501    };
502    let Ok(said) = Url::parse(&shown) else {
503        return true;
504    };
505    let host = |u: &Url| {
506        u.host_str()
507            .map(|h| h.trim_start_matches("www.").to_string())
508    };
509    if host(&said) != host(&target.url) {
510        return true;
511    }
512    let path = |u: &Url| u.path().trim_end_matches('/').to_string();
513    // A text naming only the host stands for any page of it.
514    !(path(&said).is_empty() || path(&said) == path(&target.url))
515}
516
517/// What the opener can do here.
518#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
519pub struct Caps {
520    /// Web pages and `mailto:` outside (the browser, the mail client).
521    pub web: bool,
522    /// Local files and folders outside (the default application, the
523    /// file manager).
524    pub files: bool,
525    /// The file manager with a file selected.
526    pub reveal: bool,
527    /// A viewer inside the application for pages and images.
528    pub inside: bool,
529    /// That viewer plays local video files too (the viewer's video page,
530    /// an opt-in feature).
531    #[serde(default)]
532    pub video: bool,
533    /// That viewer plays YouTube links too, in a web view (the viewer's
534    /// opt-in `webview` feature). Other remote video stays outside.
535    #[serde(default)]
536    pub web_video: bool,
537}
538
539impl Caps {
540    /// Everything (tests, a forwarding opener).
541    pub const ALL: Caps = Caps {
542        web: true,
543        files: true,
544        reveal: true,
545        inside: true,
546        video: true,
547        web_video: true,
548    };
549    /// Web pages and mail only (egui's own opener).
550    pub const WEB: Caps = Caps {
551        web: true,
552        files: false,
553        reveal: false,
554        inside: false,
555        video: false,
556        web_video: false,
557    };
558    /// Nothing.
559    pub const NONE: Caps = Caps {
560        web: false,
561        files: false,
562        reveal: false,
563        inside: false,
564        video: false,
565        web_video: false,
566    };
567}
568
569/// What is known of a local target, read by the caller (the policy never
570/// touches the disk).
571#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
572pub struct Facts {
573    pub exists: bool,
574    pub dir: bool,
575    /// The executable bit (Unix), beside the extensions.
576    pub executable: bool,
577}
578
579impl Facts {
580    /// A plain file that exists.
581    pub fn file() -> Facts {
582        Facts {
583            exists: true,
584            dir: false,
585            executable: false,
586        }
587    }
588
589    /// A folder that exists.
590    pub fn dir() -> Facts {
591        Facts {
592            exists: true,
593            dir: true,
594            executable: false,
595        }
596    }
597}
598
599/// A request to open a link.
600#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
601pub struct Request {
602    /// The target, as written (a URL or an absolute path).
603    pub target: String,
604    #[serde(default)]
605    pub how: How,
606    #[serde(default)]
607    pub source: Source,
608    /// The text the link was shown under, when it had one.
609    #[serde(default, skip_serializing_if = "Option::is_none")]
610    pub label: Option<String>,
611    /// Who asks.
612    #[serde(skip, default = "user")]
613    pub origin: Origin,
614}
615
616fn user() -> Origin {
617    Origin::User
618}
619
620impl Request {
621    /// A declared link, opened its kind's way, by the user.
622    pub fn new(target: &str) -> Request {
623        Request {
624            target: target.into(),
625            how: How::Auto,
626            source: Source::Declared,
627            label: None,
628            origin: Origin::User,
629        }
630    }
631
632    pub fn how(mut self, how: How) -> Request {
633        self.how = how;
634        self
635    }
636
637    pub fn source(mut self, source: Source) -> Request {
638        self.source = source;
639        self
640    }
641
642    /// The text it is shown under.
643    pub fn label(mut self, label: &str) -> Request {
644        self.label = Some(label.into());
645        self
646    }
647
648    pub fn origin(mut self, origin: Origin) -> Request {
649        self.origin = origin;
650        self
651    }
652}
653
654/// What the policy decided.
655#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
656pub struct Decision {
657    /// The target as parsed (canonical), or as given when it does not
658    /// parse.
659    pub target: String,
660    pub kind: Kind,
661    /// How it opens: never `Auto`.
662    pub how: How,
663    /// The user confirms first.
664    pub confirm: bool,
665    /// Why it is confirmed (`agent`, `local file`, `untrusted host`,
666    /// `disguised`).
667    #[serde(default, skip_serializing_if = "Option::is_none")]
668    pub why: Option<String>,
669    /// Why it is refused.
670    #[serde(default, skip_serializing_if = "Option::is_none")]
671    pub refused: Option<Reason>,
672    /// Refused, but showing it in its folder is offered instead.
673    #[serde(default)]
674    pub reveal_instead: bool,
675    /// The host, as shown (Unicode, punycode beside it).
676    #[serde(default, skip_serializing_if = "Option::is_none")]
677    pub host: Option<String>,
678    /// The host as the address carries it.
679    #[serde(default, skip_serializing_if = "Option::is_none")]
680    pub host_ascii: Option<String>,
681    /// The text it was shown under looks like another address.
682    #[serde(default)]
683    pub disguised: bool,
684}
685
686impl Decision {
687    fn refused(target: &str, reason: Reason) -> Decision {
688        Decision {
689            target: target.into(),
690            kind: Kind::Blocked,
691            how: How::Outside,
692            confirm: false,
693            why: None,
694            refused: Some(reason),
695            reveal_instead: false,
696            host: None,
697            host_ascii: None,
698            disguised: false,
699        }
700    }
701
702    /// Whether it may go on (after a confirmation when `confirm`).
703    pub fn allowed(&self) -> bool {
704        self.refused.is_none()
705    }
706}
707
708/// The schemes allowed by default.
709pub const SCHEMES: &[&str] = &["https", "http", "mailto", "file", "docs", "command"];
710
711/// Hosts whose pages are videos (a link there never shows inside).
712pub const VIDEO_HOSTS: &[&str] = &[
713    "youtube.com",
714    "youtu.be",
715    "youtube-nocookie.com",
716    "vimeo.com",
717    "dailymotion.com",
718    "peertube.tv",
719];
720
721/// The rules links follow: the schemes allowed, the hosts trusted for
722/// the session, the hosts holding the application's documentation, the
723/// application's own scheme.
724#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
725pub struct Policy {
726    /// Schemes allowed; everything else is blocked.
727    pub schemes: BTreeSet<String>,
728    /// The application's own schemes (`helios`), opened inside.
729    #[serde(default)]
730    pub app_schemes: BTreeSet<String>,
731    /// Hosts trusted for this session: content links to them open
732    /// without a confirmation (a host and its subdomains).
733    pub trusted: BTreeSet<String>,
734    /// Hosts holding the application's documentation: their markdown and
735    /// HTML pages open inside when a viewer is there; content links to
736    /// them are trusted.
737    pub docs_hosts: BTreeSet<String>,
738    /// Hosts whose pages are videos.
739    pub video_hosts: BTreeSet<String>,
740    /// Where the `docs:` pages are online (`https://example.org/docs/`):
741    /// without a viewer, `docs:<page>` opens `<base><page>` there.
742    #[serde(default, skip_serializing_if = "Option::is_none")]
743    pub docs_online: Option<String>,
744}
745
746impl Default for Policy {
747    fn default() -> Self {
748        Policy {
749            schemes: SCHEMES.iter().map(|s| s.to_string()).collect(),
750            app_schemes: BTreeSet::new(),
751            trusted: BTreeSet::new(),
752            docs_hosts: BTreeSet::new(),
753            video_hosts: VIDEO_HOSTS.iter().map(|s| s.to_string()).collect(),
754            docs_online: None,
755        }
756    }
757}
758
759/// Whether `host` is `listed` or one of its subdomains.
760fn under(host: &str, listed: &BTreeSet<String>) -> bool {
761    let host = host.trim_end_matches('.').to_ascii_lowercase();
762    listed.iter().any(|l| {
763        let l = l.trim_end_matches('.').to_ascii_lowercase();
764        host == l || host.ends_with(&format!(".{l}"))
765    })
766}
767
768impl Policy {
769    /// One of the application's own schemes, opened inside (allowed
770    /// too).
771    pub fn app_scheme(mut self, scheme: &str) -> Policy {
772        let s = scheme.trim_end_matches("://").to_ascii_lowercase();
773        self.schemes.insert(s.clone());
774        self.app_schemes.insert(s);
775        self
776    }
777
778    /// A host holding the application's documentation.
779    pub fn docs_host(mut self, host: &str) -> Policy {
780        self.docs_hosts.insert(host.to_ascii_lowercase());
781        self
782    }
783
784    /// Trusts a host (and its subdomains) for the session.
785    pub fn trust(&mut self, host: &str) {
786        self.trusted.insert(host.to_ascii_lowercase());
787    }
788
789    /// Whether content links to a host open without asking.
790    pub fn is_trusted(&self, host: &str) -> bool {
791        under(host, &self.trusted) || under(host, &self.docs_hosts)
792    }
793
794    /// What a target is, from its scheme, host and extension, and what
795    /// is known of it on disk.
796    pub fn classify(&self, t: &Target, facts: Option<&Facts>) -> Result<Kind, Reason> {
797        let scheme = t.scheme();
798        if !self.schemes.contains(scheme) {
799            return Err(Reason::Scheme(scheme.into()));
800        }
801        if self.app_schemes.contains(scheme) {
802            return Ok(Kind::AppLink);
803        }
804        Ok(match scheme {
805            "http" | "https" => {
806                let ext = t.extension().unwrap_or_default();
807                let host = t.host_ascii().unwrap_or_default();
808                if under(host, &self.video_hosts) || VIDEOS.contains(&ext.as_str()) {
809                    Kind::Video
810                } else if IMAGES.contains(&ext.as_str()) {
811                    Kind::Image
812                } else if matches!(ext.as_str(), "md" | "markdown") {
813                    Kind::Markdown
814                } else if matches!(ext.as_str(), "html" | "htm" | "xhtml") {
815                    Kind::Html
816                } else {
817                    Kind::Web
818                }
819            }
820            "mailto" => Kind::Mail,
821            "docs" => Kind::Doc,
822            "command" => {
823                if t.command().is_none() {
824                    return Err(Reason::Unparsable(t.as_str().into()));
825                }
826                Kind::Command
827            }
828            "file" => {
829                let path = t.local_path().unwrap_or_default();
830                if path.starts_with("/dev/")
831                    || path.starts_with("\\\\.\\")
832                    || path.starts_with("/proc/")
833                {
834                    return Err(Reason::Device);
835                }
836                match facts {
837                    Some(f) if f.dir => Kind::Folder,
838                    _ if t.url.path().ends_with('/') => Kind::Folder,
839                    _ if IMAGES.contains(&t.extension().unwrap_or_default().as_str()) => {
840                        Kind::Image
841                    }
842                    _ if VIDEOS.contains(&t.extension().unwrap_or_default().as_str()) => {
843                        Kind::Video
844                    }
845                    _ => Kind::File,
846                }
847            }
848            // An allowed scheme egui-pop knows nothing of: the system's
849            // handler.
850            _ => Kind::Web,
851        })
852    }
853
854    /// Decides how a request opens and whether the user confirms it
855    /// first: the one rule every link follows (ADR 0017).
856    pub fn decide(&self, r: &Request, caps: &Caps, facts: Option<&Facts>) -> Decision {
857        let t = match Target::parse(&r.target) {
858            Ok(t) => t,
859            Err(e) => return Decision::refused(r.target.trim(), e),
860        };
861        let mut d = Decision::refused(t.as_str(), Reason::Empty);
862        d.refused = None;
863        d.host = t.host_shown();
864        d.host_ascii = t.host_ascii().map(str::to_string);
865        d.disguised = r.label.as_deref().is_some_and(|l| disguised(l, &t));
866        let kind = match self.classify(&t, facts) {
867            Ok(k) => k,
868            Err(e) => {
869                d.refused = Some(e);
870                return d;
871            }
872        };
873        d.kind = kind;
874        let local = t.scheme() == "file";
875        let refuse = |mut d: Decision, why: Reason| {
876            d.refused = Some(why);
877            d.confirm = false;
878            d.why = None;
879            d
880        };
881        // Content opens on a click only: a person asks for it.
882        if r.source == Source::Content && r.origin != Origin::User {
883            return refuse(d, Reason::NoGesture);
884        }
885        // Command links run from the application's own text only.
886        if kind == Kind::Command && r.source != Source::Declared {
887            return refuse(d, Reason::UndeclaredCommand);
888        }
889        let viewer = |k: Kind| match k {
890            Kind::Doc => caps.inside,
891            Kind::Markdown | Kind::Html => {
892                caps.inside && t.host_ascii().is_some_and(|h| under(h, &self.docs_hosts))
893            }
894            Kind::Image => caps.inside && local,
895            Kind::Video if local => caps.inside && caps.video,
896            Kind::Video => caps.inside && caps.web_video && t.youtube_id().is_some(),
897            _ => false,
898        };
899        d.how = match (r.how, kind) {
900            (How::Reveal, Kind::File | Kind::Folder | Kind::Image | Kind::Video) if local => {
901                How::Reveal
902            }
903            (How::Reveal, _) => {
904                return refuse(
905                    d,
906                    Reason::NotApplicable(
907                        "only a local file or folder can be shown in its folder".into(),
908                    ),
909                );
910            }
911            (_, Kind::AppLink) => How::Inside,
912            (How::Outside, Kind::Command) => {
913                return refuse(
914                    d,
915                    Reason::NotApplicable("a command link runs inside the application".into()),
916                );
917            }
918            (_, Kind::Command) => How::Inside,
919            (How::Inside, k) if viewer(k) => How::Inside,
920            (How::Auto, k) if viewer(k) => How::Inside,
921            _ => How::Outside,
922        };
923        if d.how == How::Outside && kind == Kind::Doc {
924            match &self.docs_online {
925                Some(_) => {}
926                None => {
927                    return refuse(
928                        d,
929                        Reason::Unsupported(
930                            "this page needs the documentation viewer, and has no online copy"
931                                .into(),
932                        ),
933                    );
934                }
935            }
936        }
937        // What the opener cannot do.
938        let unsupported = match d.how {
939            How::Reveal if !caps.reveal => {
940                Some("showing a file in its folder is not available here")
941            }
942            How::Outside if local && !caps.files => Some("local files cannot be opened here"),
943            How::Outside if !local && !caps.web => Some("links cannot be opened here"),
944            _ => None,
945        };
946        if let Some(w) = unsupported {
947            return refuse(d, Reason::Unsupported(w.into()));
948        }
949        if local {
950            let program = t.looks_executable() || facts.is_some_and(|f| f.executable && !f.dir);
951            if program && d.how == How::Outside {
952                d.reveal_instead = caps.reveal && facts.is_none_or(|f| f.exists);
953                return refuse(d, Reason::Executable);
954            }
955            if facts.is_some_and(|f| !f.exists) {
956                return refuse(d, Reason::Missing);
957            }
958        }
959        // Whether the user confirms first.
960        let why = if r.source == Source::Agent || matches!(r.origin, Origin::Agent(_)) {
961            Some("agent")
962        } else if d.disguised {
963            Some("disguised")
964        } else {
965            match (r.source, kind, d.how) {
966                // A remote video inside reaches its host as the browser
967                // would: confirmed as a link outside is.
968                (_, _, How::Inside) if kind != Kind::AppLink && (local || kind != Kind::Video) => {
969                    None
970                }
971                (Source::Declared, _, How::Reveal) => None,
972                (Source::Declared, Kind::Folder, _) => None,
973                (_, Kind::File | Kind::Image | Kind::Video, How::Outside) if local => {
974                    Some("local file")
975                }
976                (Source::Declared, _, _) => None,
977                (_, Kind::Folder, _) | (_, _, How::Reveal) => Some("local file"),
978                (_, Kind::AppLink | Kind::Mail, _) => Some("content"),
979                _ => {
980                    let trusted = t.host_ascii().is_some_and(|h| self.is_trusted(h));
981                    (!trusted).then_some("untrusted host")
982                }
983            }
984        };
985        d.confirm = why.is_some();
986        d.why = why.map(str::to_string);
987        d
988    }
989
990    /// The address `docs:<page>` opens outside, when the documentation
991    /// is online.
992    pub fn docs_url(&self, page: &str) -> Option<String> {
993        let base = self.docs_online.as_ref()?;
994        Some(format!("{base}{}", page.trim_start_matches('/')))
995    }
996}
997
998/// A link found in a short text: its label (a markdown link's) and its
999/// target.
1000#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
1001pub struct Found {
1002    pub label: Option<String>,
1003    pub target: String,
1004}
1005
1006/// The links in a short text: markdown links (`[label](target)`),
1007/// autolinks (`<https://…>`) and bare `http(s)://` addresses.
1008pub fn find(text: &str) -> Vec<Found> {
1009    let mut out = Vec::new();
1010    let mut rest = text;
1011    // Markdown links first; their targets are not found again as bare.
1012    let mut plain = String::new();
1013    while let Some(open) = rest.find('[') {
1014        let after = &rest[open + 1..];
1015        let Some(close) = after.find("](") else {
1016            break;
1017        };
1018        let target_start = &after[close + 2..];
1019        let Some(end) = target_start.find(')') else {
1020            break;
1021        };
1022        plain.push_str(&rest[..open]);
1023        let label = &after[..close];
1024        let target = target_start[..end].trim();
1025        let target = target.split_whitespace().next().unwrap_or_default();
1026        out.push(Found {
1027            label: Some(label.to_string()),
1028            target: target.trim_matches(['<', '>']).to_string(),
1029        });
1030        plain.push_str(label);
1031        rest = &target_start[end + 1..];
1032    }
1033    plain.push_str(rest);
1034    for word in plain.split(char::is_whitespace) {
1035        let w = word.trim_start_matches(['<', '(', '"', '\'']);
1036        let lower = w.to_ascii_lowercase();
1037        if lower.starts_with("https://") || lower.starts_with("http://") {
1038            let w = w.trim_end_matches(['>', ')', '.', ',', ';', ':', '!', '?', '"', '\'']);
1039            out.push(Found {
1040                label: None,
1041                target: w.to_string(),
1042            });
1043        }
1044    }
1045    out
1046}
1047
1048/// What is wrong with a link the application declares: it must parse,
1049/// use an allowed scheme, and a `command:` link must name a declared
1050/// command (`commands`). `docs` lists the `docs:` pages the application
1051/// ships, when it says (`None`: not checked).
1052pub fn check_declared(
1053    policy: &Policy,
1054    target: &str,
1055    commands: &[String],
1056    docs: Option<&[String]>,
1057) -> Result<(), String> {
1058    let t = Target::parse(target).map_err(|e| e.to_string())?;
1059    let kind = policy.classify(&t, None).map_err(|e| e.to_string())?;
1060    match kind {
1061        Kind::Command => {
1062            let (id, _) = t
1063                .command()
1064                .ok_or_else(|| format!("`{target}` names no command"))?;
1065            if !commands.contains(&id) {
1066                return Err(format!("`{target}` names `{id}`, which is not declared"));
1067            }
1068        }
1069        Kind::Doc => {
1070            let page = t.doc_page().unwrap_or_default();
1071            if let Some(pages) = docs
1072                && !pages.contains(&page)
1073            {
1074                return Err(format!("`{target}`: no `docs:` page `{page}`"));
1075            }
1076        }
1077        _ => {}
1078    }
1079    Ok(())
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084    use super::*;
1085
1086    fn decide(r: Request) -> Decision {
1087        Policy::default().decide(&r, &Caps::ALL, None)
1088    }
1089
1090    #[test]
1091    fn declared_web_and_mail_links_open_outside_without_asking() {
1092        for t in ["https://example.org/a", "mailto:someone@example.org"] {
1093            let d = decide(Request::new(t));
1094            assert_eq!(d.how, How::Outside, "{t}");
1095            assert!(!d.confirm && d.allowed(), "{t}");
1096        }
1097    }
1098
1099    #[test]
1100    fn content_links_ask_until_their_host_is_trusted() {
1101        let r = Request::new("https://example.org/report").source(Source::Content);
1102        let mut p = Policy::default();
1103        let d = p.decide(&r, &Caps::ALL, None);
1104        assert_eq!(
1105            (d.confirm, d.why.as_deref()),
1106            (true, Some("untrusted host"))
1107        );
1108        p.trust("example.org");
1109        assert!(!p.decide(&r, &Caps::ALL, None).confirm);
1110        // A subdomain is trusted with its host; another host is not.
1111        let sub = Request::new("https://docs.example.org/").source(Source::Content);
1112        assert!(!p.decide(&sub, &Caps::ALL, None).confirm);
1113        let other = Request::new("https://example.com/").source(Source::Content);
1114        assert!(p.decide(&other, &Caps::ALL, None).confirm);
1115    }
1116
1117    #[test]
1118    fn content_needs_a_click_and_agents_always_confirm() {
1119        let r = Request::new("https://example.org/")
1120            .source(Source::Content)
1121            .origin(Origin::Script("s".into()));
1122        assert_eq!(decide(r).refused, Some(Reason::NoGesture));
1123        let r = Request::new("https://example.org/")
1124            .source(Source::Agent)
1125            .origin(Origin::Agent("a".into()));
1126        let d = decide(r);
1127        assert_eq!((d.confirm, d.why.as_deref()), (true, Some("agent")));
1128    }
1129
1130    #[test]
1131    fn blocked_schemes_say_which() {
1132        for (t, s) in [
1133            ("javascript:alert(1)", "javascript"),
1134            ("data:text/html,x", "data"),
1135        ] {
1136            assert_eq!(
1137                decide(Request::new(t)).refused,
1138                Some(Reason::Scheme(s.into()))
1139            );
1140        }
1141        assert!(matches!(
1142            decide(Request::new("not a link")).refused,
1143            Some(Reason::Unparsable(_))
1144        ));
1145    }
1146
1147    #[cfg(unix)]
1148    #[test]
1149    fn local_files_are_confirmed_and_programs_refused_with_reveal_offered() {
1150        let p = Policy::default();
1151        let r = Request::new("/home/a/photo.txt");
1152        let d = p.decide(&r, &Caps::ALL, Some(&Facts::file()));
1153        assert_eq!((d.kind, d.confirm), (Kind::File, true));
1154        let d = p.decide(
1155            &Request::new("/home/a/run.sh"),
1156            &Caps::ALL,
1157            Some(&Facts::file()),
1158        );
1159        assert_eq!(d.refused, Some(Reason::Executable));
1160        assert!(d.reveal_instead);
1161        // Revealing a declared path asks nothing; a folder opens.
1162        let d = p.decide(
1163            &r.clone().how(How::Reveal),
1164            &Caps::ALL,
1165            Some(&Facts::file()),
1166        );
1167        assert_eq!((d.how, d.confirm), (How::Reveal, false));
1168        let d = p.decide(&Request::new("/home/a"), &Caps::ALL, Some(&Facts::dir()));
1169        assert_eq!((d.kind, d.confirm), (Kind::Folder, false));
1170        // Without the system opener, local files are refused.
1171        let d = p.decide(&r, &Caps::WEB, Some(&Facts::file()));
1172        assert!(matches!(d.refused, Some(Reason::Unsupported(_))));
1173        assert_eq!(
1174            p.decide(&Request::new("/dev/sda"), &Caps::ALL, None)
1175                .refused,
1176            Some(Reason::Device)
1177        );
1178    }
1179
1180    #[test]
1181    fn a_local_video_opens_inside_only_when_the_viewer_plays_video() {
1182        let t = "file:///tmp/clip.MP4";
1183        let policy = Policy::default();
1184        let web_and_files = Caps {
1185            inside: true,
1186            video: false,
1187            ..Caps::ALL
1188        };
1189        // As any local file without the video page: outside, confirmed.
1190        let d = policy.decide(&Request::new(t), &web_and_files, None);
1191        assert_eq!(
1192            (d.kind, d.how, d.confirm),
1193            (Kind::Video, How::Outside, true)
1194        );
1195        let d = policy.decide(&Request::new(t).how(How::Inside), &web_and_files, None);
1196        assert_eq!((d.how, d.confirm), (How::Outside, true));
1197        // With it: inside, as a local image; outside and Reveal as asked.
1198        let d = policy.decide(&Request::new(t), &Caps::ALL, None);
1199        assert_eq!(
1200            (d.kind, d.how, d.confirm),
1201            (Kind::Video, How::Inside, false)
1202        );
1203        let d = policy.decide(&Request::new(t).how(How::Outside), &Caps::ALL, None);
1204        assert_eq!((d.how, d.confirm), (How::Outside, true));
1205        let d = policy.decide(&Request::new(t).how(How::Reveal), &Caps::ALL, None);
1206        assert_eq!(d.how, How::Reveal);
1207        // A viewer that has no video page is not one because the opener is.
1208        let no_viewer = Caps {
1209            inside: false,
1210            ..Caps::ALL
1211        };
1212        assert_eq!(
1213            policy.decide(&Request::new(t), &no_viewer, None).how,
1214            How::Outside
1215        );
1216        // Remote video other than a YouTube video stays outside, viewer or
1217        // not.
1218        for remote in ["https://example.org/clip.mp4", "https://youtu.be/abc"] {
1219            let d = policy.decide(&Request::new(remote), &Caps::ALL, None);
1220            assert_eq!((d.kind, d.how), (Kind::Video, How::Outside), "{remote}");
1221        }
1222    }
1223
1224    #[test]
1225    fn youtube_links_name_their_video() {
1226        let id = |t: &str| Target::parse(t).unwrap().youtube_id();
1227        for t in [
1228            "https://www.youtube.com/watch?v=5TGDf7crzXI",
1229            "https://youtube.com/watch?feature=share&v=5TGDf7crzXI&t=10",
1230            "https://m.youtube.com/watch?v=5TGDf7crzXI",
1231            "https://youtu.be/5TGDf7crzXI?t=3",
1232            "https://www.youtube.com/embed/5TGDf7crzXI",
1233            "https://www.youtube-nocookie.com/embed/5TGDf7crzXI",
1234            "https://www.youtube.com/shorts/5TGDf7crzXI",
1235            "https://www.youtube.com/live/5TGDf7crzXI",
1236        ] {
1237            assert_eq!(id(t).as_deref(), Some("5TGDf7crzXI"), "{t}");
1238        }
1239        for t in [
1240            "http://www.youtube.com/watch?v=5TGDf7crzXI",
1241            "https://www.youtube.com/watch?v=x",
1242            "https://www.youtube.com/watch?v=5TGDf7crzXI%22",
1243            "https://www.youtube.com/channel/5TGDf7crzXI",
1244            "https://youtube.com.example.org/watch?v=5TGDf7crzXI",
1245            "https://notyoutube.com/watch?v=5TGDf7crzXI",
1246            "https://vimeo.com/5TGDf7crzXI",
1247            "https://youtu.be/",
1248        ] {
1249            assert_eq!(id(t), None, "{t}");
1250        }
1251    }
1252
1253    #[test]
1254    fn a_youtube_video_opens_inside_only_when_the_viewer_plays_it() {
1255        let t = "https://www.youtube.com/watch?v=5TGDf7crzXI";
1256        let policy = Policy::default();
1257        let without = Caps {
1258            web_video: false,
1259            ..Caps::ALL
1260        };
1261        let d = policy.decide(&Request::new(t), &without, None);
1262        assert_eq!((d.kind, d.how), (Kind::Video, How::Outside));
1263        let d = policy.decide(&Request::new(t), &Caps::ALL, None);
1264        assert_eq!(
1265            (d.kind, d.how, d.confirm),
1266            (Kind::Video, How::Inside, false)
1267        );
1268        // Ctrl+click still means outside.
1269        let d = policy.decide(&Request::new(t).how(How::Outside), &Caps::ALL, None);
1270        assert_eq!(d.how, How::Outside);
1271        // From content, the host is asked about as it is outside.
1272        let d = policy.decide(&Request::new(t).source(Source::Content), &Caps::ALL, None);
1273        assert_eq!((d.how, d.confirm), (How::Inside, true));
1274        // Not without a viewer, whatever the opener says.
1275        let no_viewer = Caps {
1276            inside: false,
1277            ..Caps::ALL
1278        };
1279        assert_eq!(
1280            policy.decide(&Request::new(t), &no_viewer, None).how,
1281            How::Outside
1282        );
1283    }
1284
1285    #[test]
1286    fn videos_open_outside_and_docs_inside_when_a_viewer_is_there() {
1287        let d = decide(Request::new("https://www.youtube.com/watch?v=x"));
1288        assert_eq!((d.kind, d.how), (Kind::Video, How::Outside));
1289        let d = decide(Request::new("docs:guide/start"));
1290        assert_eq!((d.kind, d.how), (Kind::Doc, How::Inside));
1291        let p = Policy::default();
1292        let d = p.decide(&Request::new("docs:guide/start"), &Caps::WEB, None);
1293        assert!(matches!(d.refused, Some(Reason::Unsupported(_))));
1294    }
1295
1296    #[test]
1297    fn command_links_run_from_declared_text_only() {
1298        let t = "command:view.zoom?%7B%22to%22%3A2%7D";
1299        let target = Target::parse(t).unwrap();
1300        assert_eq!(
1301            target.command(),
1302            Some(("view.zoom".into(), serde_json::json!({ "to": 2 })))
1303        );
1304        assert_eq!(decide(Request::new(t)).how, How::Inside);
1305        let d = decide(Request::new(t).source(Source::Content));
1306        assert_eq!(d.refused, Some(Reason::UndeclaredCommand));
1307    }
1308
1309    #[test]
1310    fn a_text_showing_another_address_is_disguised() {
1311        let t = Target::parse("https://evil.example/login").unwrap();
1312        assert!(disguised("https://bank.example", &t));
1313        assert!(disguised("bank.example/login", &t));
1314        assert!(!disguised("evil.example", &t));
1315        assert!(!disguised("Log in", &t));
1316        let d = decide(Request::new("https://evil.example/login").label("bank.example"));
1317        assert_eq!((d.confirm, d.disguised), (true, true));
1318    }
1319
1320    #[test]
1321    fn internationalised_hosts_show_their_punycode() {
1322        let t = Target::parse("https://bücher.example/").unwrap();
1323        assert!(t.is_idn());
1324        assert_eq!(t.host_ascii(), Some("xn--bcher-kva.example"));
1325        assert_eq!(
1326            t.host_shown().as_deref(),
1327            Some("bücher.example (xn--bcher-kva.example)")
1328        );
1329    }
1330
1331    #[test]
1332    fn links_are_found_in_short_texts() {
1333        let found =
1334            find("See [the guide](docs:guide) or https://example.org/a, and <https://b.example>.");
1335        let targets: Vec<&str> = found.iter().map(|f| f.target.as_str()).collect();
1336        assert_eq!(
1337            targets,
1338            ["docs:guide", "https://example.org/a", "https://b.example"]
1339        );
1340        assert_eq!(found[0].label.as_deref(), Some("the guide"));
1341    }
1342
1343    #[test]
1344    fn declared_links_are_checked() {
1345        let p = Policy::default();
1346        let cmds = vec!["view.zoom".to_string()];
1347        assert!(check_declared(&p, "https://example.org", &cmds, None).is_ok());
1348        assert!(check_declared(&p, "command:view.zoom", &cmds, None).is_ok());
1349        assert!(check_declared(&p, "command:view.nope", &cmds, None).is_err());
1350        assert!(check_declared(&p, "javascript:x", &cmds, None).is_err());
1351        let pages = vec!["intro".to_string()];
1352        assert!(check_declared(&p, "docs:intro", &cmds, Some(&pages)).is_ok());
1353        assert!(check_declared(&p, "docs:outro", &cmds, Some(&pages)).is_err());
1354    }
1355}