Skip to main content

tilo_actions/remote/
content_link.rs

1//! Content links: an address a browser fetches a workspace's files from
2//! itself, over plain HTTPS, rather than through the page.
3//!
4//! A page asks for one over its session ([`super::RemoteActionMessage::ContentLinkRequest`])
5//! naming the files and the name they are saved under; the provider answers with
6//! a path on its own web origin, good for a few minutes, where it serves
7//! those bytes straight from its store. Two things need that:
8//!
9//! - dragging a file out of the page onto the computer's desktop or file
10//!   manager: the browser fetches the address the drag names with its own
11//!   download manager, outside the page, so the bytes must be at an address
12//!   the network answers;
13//! - saving a file of any size: the page streams the response into the file
14//!   the person chose, or lets the browser download it, so a gigabyte never
15//!   sits in the page's memory.
16//!
17//! Several files, or a folder, are served as one zip of them.
18//!
19//! The link is a capability: whoever holds the address reads what it names
20//! until it expires. A provider mints one only for a caller who may read the
21//! workspace, names only content of that workspace, and lets it go after
22//! [`CONTENT_LINK_TTL_SECS`].
23
24/// What a provider that serves no content links answers.
25pub const CONTENT_LINKS_UNAVAILABLE: &str = "links to content are not available here";
26
27/// How long a content link stays good, in seconds: long enough for a drag
28/// that hovers, or a Save dialog someone thinks about, and short enough that
29/// an address left in a browser's download list no longer reads anything.
30pub const CONTENT_LINK_TTL_SECS: u64 = 15 * 60;
31
32/// The most files one link names: a folder past this is saved in parts.
33pub const MAX_CONTENT_LINK_FILES: usize = 65_535;
34
35/// One file a link serves: where it goes in what is saved, and its content.
36#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct ContentLinkFile {
39    /// Its path in a zip (`Plans/2026/budget.csv`, `/`-separated); for a link
40    /// to one file, its name.
41    pub path: String,
42    /// The hash of its content in the workspace's store, as a Files node
43    /// names it: the whole file, or the manifest of its chunks.
44    pub hash: String,
45}
46
47/// Whether `hash` is a content hash a link may name: 64 hex digits.
48fn is_hash(hash: &str) -> bool {
49    hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit())
50}
51
52/// What a link is asked for.
53#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
54#[serde(deny_unknown_fields)]
55pub struct ContentLinkAsk {
56    /// The name the browser saves it under: the file's own, or the folder's
57    /// with `.zip`.
58    pub name: String,
59    /// The files it serves. One file with `zip` false is served as itself.
60    pub files: Vec<ContentLinkFile>,
61    /// Serve the files as one zip, even a single one: a folder.
62    pub zip: bool,
63}
64
65impl ContentLinkAsk {
66    /// Why this ask is not one a provider mints a link for, if it is not.
67    ///
68    /// # Errors
69    ///
70    /// No name, no files, more than one file not zipped, too many files, or
71    /// a path a zip may not hold.
72    pub fn check(&self) -> Result<(), String> {
73        if self.name.trim().is_empty() || self.name.contains(['/', '\\', '\0']) {
74            return Err(format!("{:?} is no name to save under", self.name));
75        }
76        if !self.zip && self.files.len() != 1 {
77            return Err("a link to more than one file is a zip".into());
78        }
79        if self.files.len() > MAX_CONTENT_LINK_FILES {
80            return Err(format!(
81                "a link names at most {MAX_CONTENT_LINK_FILES} files"
82            ));
83        }
84        for file in &self.files {
85            let safe = !file.path.is_empty()
86                && !file.path.starts_with('/')
87                && !file.path.contains(['\\', '\0'])
88                && file
89                    .path
90                    .split('/')
91                    .all(|part| !part.is_empty() && part != "." && part != "..");
92            if !safe {
93                return Err(format!("{:?} is no path in a zip", file.path));
94            }
95            if !is_hash(&file.hash) {
96                return Err(format!("{:?} is no content hash", file.hash));
97            }
98        }
99        Ok(())
100    }
101}
102
103/// The link a provider minted.
104#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
105#[serde(deny_unknown_fields)]
106pub struct ContentLink {
107    /// Its path on the provider's web origin (`/api/content/<token>/<name>`).
108    pub path: String,
109    /// How many seconds from the answer it stays good.
110    pub expires_in_secs: u64,
111}
112
113/// The media type a browser shows `name` as in a tab of its own, when it is
114/// one it plays or shows safely: films, sound, pictures and plain text.
115/// Nothing executable (HTML, SVG, scripts) is ever shown from a link, nor a
116/// PDF, which a browser will not show sandboxed; those are saved.
117#[must_use]
118pub fn viewable(name: &str) -> Option<&'static str> {
119    let (_, extension) = name.rsplit_once('.')?;
120    Some(match extension.to_ascii_lowercase().as_str() {
121        "mp4" | "m4v" => "video/mp4",
122        "mov" => "video/quicktime",
123        "webm" => "video/webm",
124        "ogv" => "video/ogg",
125        "mp3" => "audio/mpeg",
126        "m4a" => "audio/mp4",
127        "wav" => "audio/wav",
128        "ogg" | "oga" | "opus" => "audio/ogg",
129        "flac" => "audio/flac",
130        "png" => "image/png",
131        "jpg" | "jpeg" => "image/jpeg",
132        "gif" => "image/gif",
133        "webp" => "image/webp",
134        "avif" => "image/avif",
135        "txt" => "text/plain; charset=utf-8",
136        _ => return None,
137    })
138}
139
140#[cfg(test)]
141mod tests {
142
143    use super::*;
144
145    fn file(path: &str) -> ContentLinkFile {
146        ContentLinkFile {
147            path: path.into(),
148            hash: "ab".repeat(32),
149        }
150    }
151
152    #[test]
153    fn a_link_names_a_file_or_a_zip_of_safe_paths() {
154        let one = ContentLinkAsk {
155            name: "plan.md".into(),
156            files: vec![file("plan.md")],
157            zip: false,
158        };
159        assert!(one.check().is_ok());
160        let folder = ContentLinkAsk {
161            name: "Plans.zip".into(),
162            files: vec![file("Plans/a.md"), file("Plans/2026/b.csv")],
163            zip: true,
164        };
165        assert!(folder.check().is_ok());
166        let empty_folder = ContentLinkAsk {
167            files: Vec::new(),
168            ..folder.clone()
169        };
170        assert!(
171            empty_folder.check().is_ok(),
172            "an empty folder is an empty zip"
173        );
174
175        let two_unzipped = ContentLinkAsk {
176            zip: false,
177            ..folder.clone()
178        };
179        assert!(two_unzipped.check().is_err());
180        for path in ["../etc/passwd", "/abs", "a//b", "a/./b", "a\\b", ""] {
181            let bad = ContentLinkAsk {
182                files: vec![file(path)],
183                ..folder.clone()
184            };
185            assert!(bad.check().is_err(), "{path:?}");
186        }
187        let unnamed = ContentLinkAsk {
188            name: "a/b.zip".into(),
189            ..folder.clone()
190        };
191        assert!(unnamed.check().is_err());
192        let not_a_hash = ContentLinkAsk {
193            files: vec![ContentLinkFile {
194                path: "a".into(),
195                hash: "tilo.content:xyz".into(),
196            }],
197            ..folder
198        };
199        assert!(not_a_hash.check().is_err());
200    }
201}