Skip to main content

agent_hub_runtime/core/preview/
documents.rs

1//! Authorized document handles share the existing file reader and atomic save boundary.
2use super::super::{error::AppError, project_file_edit, project_worktrees};
3use serde::Serialize;
4use sha2::{Digest, Sha256};
5use std::{
6    collections::HashMap,
7    io::Read,
8    path::{Path, PathBuf},
9    sync::Mutex,
10};
11#[derive(Clone, Serialize)]
12pub struct Document {
13    pub id: String,
14    pub title: String,
15    pub relative_path: String,
16    pub path: PathBuf,
17    pub kind: String,
18    pub content: String,
19    pub revision: String,
20}
21pub struct DocumentLink {
22    pub relative: String,
23    pub suffix: String,
24}
25#[derive(Clone)]
26struct Grant {
27    root: PathBuf,
28    relative: String,
29}
30#[derive(Default)]
31pub struct Documents {
32    grants: Mutex<HashMap<String, Grant>>,
33}
34
35/// Resolve an explicit document path; only CLI callers supply a working directory.
36pub fn resolve_explicit_path(
37    input: &str,
38    working_directory: Option<&Path>,
39) -> Result<PathBuf, AppError> {
40    let path = if let Some(relative) = input.strip_prefix("~/") {
41        dirs::home_dir()
42            .ok_or_else(|| AppError::internal("Cannot determine home directory"))?
43            .join(relative)
44    } else {
45        PathBuf::from(input)
46    };
47    let path = match working_directory {
48        Some(directory) if path.is_relative() => directory.join(path),
49        _ => path,
50    };
51    if !path.is_absolute() {
52        return Err(AppError::invalid_input(
53            "Document path must be absolute or start with ~/",
54        ));
55    }
56    Ok(path)
57}
58pub(super) fn resource_path(relative: &str) -> String {
59    relative
60        .split('/')
61        .map(|part| urlencoding::encode(part).into_owned())
62        .collect::<Vec<_>>()
63        .join("/")
64}
65// Explicit selection authorizes hidden ancestors of this document, not unrelated
66// hidden directories or dotfiles referenced by a page. Check canonical paths too.
67fn resource_path_allowed(relative: &Path, selected: &str) -> bool {
68    let parent = Path::new(selected)
69        .parent()
70        .unwrap_or_else(|| Path::new(""));
71    let mut prefix = PathBuf::new();
72    for component in relative.components() {
73        let name = component.as_os_str().to_string_lossy();
74        prefix.push(component.as_os_str());
75        if name.contains(':')
76            || (name.starts_with('.')
77                && !(parent.starts_with(&prefix) && relative.starts_with(parent)))
78        {
79            return false;
80        }
81    }
82    true
83}
84
85fn revision(text: &str) -> String {
86    hex::encode(Sha256::digest(text.as_bytes()))
87}
88fn resource_revision(path: &Path) -> Result<String, AppError> {
89    let mut file = std::fs::File::open(path)?.take(super::resource_bridge::LIMIT + 1);
90    let mut hasher = Sha256::new();
91    let mut count = 0u64;
92    let mut buffer = [0u8; 8192];
93    loop {
94        let read = file.read(&mut buffer)?;
95        if read == 0 {
96            break;
97        }
98        count += read as u64;
99        if count > super::resource_bridge::LIMIT {
100            return Err(AppError::invalid_input(
101                "Preview resource exceeds the 16 MiB limit",
102            ));
103        }
104        hasher.update(&buffer[..read]);
105    }
106    Ok(hex::encode(hasher.finalize()))
107}
108fn kind(path: &Path) -> Result<&'static str, AppError> {
109    super::file_types::kind(path)
110        .ok_or_else(|| AppError::invalid_input("Unsupported browser preview file type"))
111}
112impl Documents {
113    /// Call only after native selection, explicit local path submission, or an authorized project request.
114    pub fn open(&self, path: &Path) -> Result<Document, AppError> {
115        let path = path.canonicalize()?;
116        let root = path
117            .parent()
118            .ok_or_else(|| AppError::invalid_input("Document has no parent"))?;
119        let relative = path
120            .file_name()
121            .ok_or_else(|| AppError::invalid_input("Invalid document"))?
122            .to_string_lossy();
123        self.open_at(root, &relative)
124    }
125    pub fn open_at(&self, root: &Path, relative: &str) -> Result<Document, AppError> {
126        let root = root.canonicalize()?;
127        let path = project_worktrees::file_path(&root, relative).map_err(AppError::io)?;
128        let kind = kind(&path)?;
129        // Resource documents are read-only handles: bytes stay in the capability bridge,
130        // never pass through the text editor or UTF-8 conversion.
131        let content = if kind == "resource" {
132            if !path.is_file() || std::fs::metadata(&path)?.len() > super::resource_bridge::LIMIT {
133                return Err(AppError::invalid_input(
134                    "Preview resource exceeds the 16 MiB limit",
135                ));
136            }
137            String::new()
138        } else {
139            project_worktrees::read_file(&root, relative).map_err(AppError::io)?
140        };
141        let id = uuid::Uuid::new_v4().to_string();
142        let relative = relative.replace('\\', "/");
143        let document = Document {
144            id: id.clone(),
145            title: path
146                .file_name()
147                .unwrap_or_default()
148                .to_string_lossy()
149                .into_owned(),
150            path: path.canonicalize()?,
151            relative_path: relative.clone(),
152            kind: kind.into(),
153            revision: if kind == "resource" {
154                resource_revision(&path)?
155            } else {
156                revision(&content)
157            },
158            content,
159        };
160        let mut grants = self
161            .grants
162            .lock()
163            .map_err(|_| AppError::internal("Document state unavailable"))?;
164        if grants.len() >= 100 {
165            return Err(AppError::invalid_input("Close unused documents first"));
166        }
167        grants.insert(id.clone(), Grant { root, relative });
168        drop(grants);
169        if kind == "resource" {
170            if let Err(error) = self.resource(&id, &document.relative_path) {
171                self.close(&id);
172                return Err(error);
173            }
174        }
175        Ok(document)
176    }
177    pub fn open_link(&self, id: &str, href: &str) -> Result<Document, AppError> {
178        let grant = self.grant(id)?;
179        let relative = self.link_relative(id, href)?;
180        self.open_at(&grant.root, &relative)
181    }
182    pub fn link_relative(&self, id: &str, href: &str) -> Result<String, AppError> {
183        Ok(self.resolve_link(id, href)?.relative)
184    }
185    pub fn resolve_link(&self, id: &str, href: &str) -> Result<DocumentLink, AppError> {
186        if href.len() > 8192 {
187            return Err(AppError::invalid_input(
188                "Document link exceeds the supported limit",
189            ));
190        }
191        let grant = self.grant(id)?;
192        let mut base = reqwest::Url::parse("http://resources.invalid/").map_err(AppError::io)?;
193        base.set_path(&format!("/{}", resource_path(&grant.relative)));
194        let target = base
195            .join(href)
196            .map_err(|error| AppError::invalid_input(error.to_string()))?;
197        if target.host_str() != Some("resources.invalid") || target.scheme() != "http" {
198            return Err(AppError::invalid_input("Not a local document link"));
199        }
200        let relative =
201            urlencoding::decode(target.path().trim_start_matches('/')).map_err(AppError::io)?;
202        let _ = self.resource(id, &relative)?;
203        let suffix = format!(
204            "{}{}",
205            target
206                .query()
207                .map(|query| format!("?{query}"))
208                .unwrap_or_default(),
209            target
210                .fragment()
211                .map(|fragment| format!("#{fragment}"))
212                .unwrap_or_default()
213        );
214        Ok(DocumentLink {
215            relative: relative.into_owned(),
216            suffix,
217        })
218    }
219    /// Resolve an authorized browser file without publishing a resource-server URL.
220    pub fn file_link(&self, id: &str, href: &str) -> Result<String, AppError> {
221        let link = self.resolve_link(id, href)?;
222        let path = self.resource(id, &link.relative)?;
223        let mime = super::file_types::mime(&path).unwrap_or_default();
224        if !matches!(kind(&path)?, "html" | "markdown")
225            && !mime.starts_with("image/")
226            && !mime.starts_with("audio/")
227            && !mime.starts_with("video/")
228            && !matches!(mime, "application/pdf" | "application/xhtml+xml")
229        {
230            return Err(AppError::invalid_input(
231                "File type cannot be opened as a browser document",
232            ));
233        }
234        let url = reqwest::Url::from_file_path(path)
235            .map_err(|_| AppError::invalid_input("Invalid local document path"))?;
236        Ok(format!("{url}{}", link.suffix))
237    }
238    pub(super) fn authorize_rendered(&self, path: &Path) -> Result<String, AppError> {
239        let root = path
240            .parent()
241            .ok_or_else(|| AppError::invalid_input("Invalid rendered document"))?
242            .canonicalize()?;
243        let relative = path
244            .file_name()
245            .ok_or_else(|| AppError::invalid_input("Invalid rendered document"))?
246            .to_string_lossy()
247            .into_owned();
248        let id = uuid::Uuid::new_v4().to_string();
249        let mut grants = self
250            .grants
251            .lock()
252            .map_err(|_| AppError::internal("Document state unavailable"))?;
253        if grants.len() >= 100 {
254            return Err(AppError::invalid_input("Close unused documents first"));
255        }
256        grants.insert(id.clone(), Grant { root, relative });
257        Ok(id)
258    }
259    pub fn read(&self, id: &str) -> Result<Document, AppError> {
260        let grant = self.grant(id)?;
261        let content = if kind(Path::new(&grant.relative))? == "resource" {
262            let _ = self.resource(id, &grant.relative)?;
263            String::new()
264        } else {
265            project_worktrees::read_file(&grant.root, &grant.relative).map_err(AppError::io)?
266        };
267        Ok(Document {
268            id: id.into(),
269            title: Path::new(&grant.relative)
270                .file_name()
271                .unwrap_or_default()
272                .to_string_lossy()
273                .into_owned(),
274            kind: kind(Path::new(&grant.relative))?.into(),
275            path: project_worktrees::file_path(&grant.root, &grant.relative)
276                .map_err(AppError::io)?
277                .canonicalize()?,
278            relative_path: grant.relative.clone(),
279            revision: if kind(Path::new(&grant.relative))? == "resource" {
280                resource_revision(&self.resource(id, &grant.relative)?)?
281            } else {
282                revision(&content)
283            },
284            content,
285        })
286    }
287    pub fn save(
288        &self,
289        id: &str,
290        content: &str,
291        expected_revision: &str,
292    ) -> Result<Document, AppError> {
293        let grant = self.grant(id)?;
294        if kind(Path::new(&grant.relative))? == "resource" {
295            return Err(AppError::invalid_input("Browser resources are read-only"));
296        }
297        let current =
298            project_worktrees::read_file(&grant.root, &grant.relative).map_err(AppError::io)?;
299        if revision(&current) != expected_revision {
300            return Err(AppError::invalid_input("PREVIEW_DOCUMENT_CONFLICT"));
301        }
302        project_file_edit::save(&grant.root, &grant.relative, &current, content)
303            .map_err(AppError::io)?;
304        self.read(id)
305    }
306    pub fn resource(&self, id: &str, relative: &str) -> Result<PathBuf, AppError> {
307        let grant = self.grant(id)?;
308        super::super::path_guard::ensure_safe_skill_relative_path(relative)?;
309        if !resource_path_allowed(Path::new(relative), &grant.relative) {
310            return Err(AppError::invalid_input("Hidden resource is not accessible"));
311        }
312        let path = grant.root.join(relative).canonicalize()?;
313        if !path.starts_with(&grant.root)
314            || path
315                .strip_prefix(&grant.root)
316                .is_ok_and(|relative| !resource_path_allowed(relative, &grant.relative))
317            || !path.is_file()
318            || std::fs::metadata(&path)?.len() > super::resource_bridge::LIMIT
319        {
320            return Err(AppError::invalid_input(
321                "Resource is outside the authorized directory or too large",
322            ));
323        }
324        Ok(path)
325    }
326    pub fn close(&self, id: &str) {
327        if let Ok(mut grants) = self.grants.lock() {
328            grants.remove(id);
329        }
330    }
331    fn grant(&self, id: &str) -> Result<Grant, AppError> {
332        self.grants
333            .lock()
334            .map_err(|_| AppError::internal("Document state unavailable"))?
335            .get(id)
336            .cloned()
337            .ok_or_else(|| AppError::not_found("Document authorization expired; reopen the file"))
338    }
339}
340#[cfg(test)]
341#[path = "documents/tests.rs"]
342mod tests;