Skip to main content

ask/store/
paths.rs

1//! Store path resolution + containment guards — Rust port of the path helpers in
2//! `packages/cli/src/store/index.ts`.
3
4use std::path::{Component, Path, PathBuf};
5
6use sha2::{Digest, Sha256};
7
8/// Resolve the global ASK home directory. Precedence: `ASK_HOME` (tilde-expanded,
9/// absolutized) → `~/.ask`.
10pub fn resolve_ask_home() -> PathBuf {
11    if let Some(env_val) = std::env::var_os("ASK_HOME").filter(|v| !v.is_empty()) {
12        let raw = env_val.to_string_lossy();
13        let expanded: PathBuf = if let Some(rest) = raw.strip_prefix("~/") {
14            home_dir().join(rest)
15        } else {
16            PathBuf::from(raw.as_ref())
17        };
18        return absolutize(&expanded);
19    }
20    home_dir().join(".ask")
21}
22
23/// Best-effort home directory (`$HOME` on unix, `%USERPROFILE%` on Windows).
24pub(crate) fn home_dir() -> PathBuf {
25    #[cfg(windows)]
26    let key = "USERPROFILE";
27    #[cfg(not(windows))]
28    let key = "HOME";
29    std::env::var_os(key)
30        .map(PathBuf::from)
31        .unwrap_or_else(|| PathBuf::from("."))
32}
33
34/// Lexically clean a path (resolve `.`/`..` without touching the filesystem),
35/// then make it absolute against the current dir if it is relative. Mirrors the
36/// normalization `path.resolve` performs before containment checks.
37fn absolutize(p: &Path) -> PathBuf {
38    let base = if p.is_absolute() {
39        p.to_path_buf()
40    } else {
41        std::env::current_dir()
42            .unwrap_or_else(|_| PathBuf::from("."))
43            .join(p)
44    };
45    lexical_clean(&base)
46}
47
48/// Go-style lexical `Clean`: collapse `.` and `..` segments without resolving
49/// symlinks or hitting the filesystem.
50pub fn lexical_clean(p: &Path) -> PathBuf {
51    let mut out: Vec<Component> = Vec::new();
52    for comp in p.components() {
53        match comp {
54            Component::CurDir => {}
55            Component::ParentDir => match out.last() {
56                Some(Component::Normal(_)) => {
57                    out.pop();
58                }
59                Some(Component::RootDir) | Some(Component::Prefix(_)) => {}
60                _ => out.push(comp),
61            },
62            other => out.push(other),
63        }
64    }
65    out.iter().map(|c| c.as_os_str()).collect()
66}
67
68/// Assert `candidate` resolves inside `parent`; returns the cleaned candidate.
69/// Prevents path traversal via `..` or absolute paths in user-controlled inputs.
70pub fn assert_contained(parent: &Path, candidate: &Path) -> anyhow::Result<PathBuf> {
71    let rp = absolutize(parent);
72    let rc = absolutize(candidate);
73    if rc == rp || rc.starts_with(&rp) {
74        Ok(rc)
75    } else {
76        anyhow::bail!(
77            "Unsafe path: {} is outside {}",
78            candidate.display(),
79            parent.display()
80        );
81    }
82}
83
84/// Reject a path segment containing `..`, `/`, `\`, or empty — segment-level
85/// traversal that [`assert_contained`] alone cannot catch.
86pub fn assert_safe_segment(name: &str, value: &str) -> anyhow::Result<()> {
87    if value.is_empty() || value.contains("..") || value.contains('/') || value.contains('\\') {
88        anyhow::bail!("Unsafe path: {name} '{value}' contains path traversal characters");
89    }
90    Ok(())
91}
92
93pub fn npm_store_path(ask_home: &Path, pkg: &str, version: &str) -> anyhow::Result<PathBuf> {
94    let candidate = ask_home.join("npm").join(format!("{pkg}@{version}"));
95    assert_contained(ask_home, &candidate)
96}
97
98/// The PM-style nested layout for a github entry:
99/// `<askHome>/github/<host>/<owner>/<repo>/<tag>/`.
100pub fn github_store_path(
101    ask_home: &Path,
102    host: &str,
103    owner: &str,
104    repo: &str,
105    tag: &str,
106) -> anyhow::Result<PathBuf> {
107    assert_safe_segment("host", host)?;
108    assert_safe_segment("owner", owner)?;
109    assert_safe_segment("repo", repo)?;
110    assert_safe_segment("tag", tag)?;
111    let github_root = ask_home.join("github");
112    let candidate = github_root.join(host).join(owner).join(repo).join(tag);
113    assert_contained(&github_root, &candidate)
114}
115
116pub fn web_store_path(ask_home: &Path, url: &str) -> PathBuf {
117    ask_home.join("web").join(hash_url(url))
118}
119
120pub fn llms_txt_store_path(ask_home: &Path, url: &str, version: &str) -> PathBuf {
121    ask_home
122        .join("llms-txt")
123        .join(format!("{}@{version}", hash_url(url)))
124}
125
126fn hash_url(url: &str) -> String {
127    let mut hasher = Sha256::new();
128    hasher.update(normalize_url(url).as_bytes());
129    format!("{:x}", hasher.finalize())
130}
131
132/// Normalize a URL for hashing: strip trailing slashes, lowercase the
133/// scheme + host (the path stays case-sensitive per RFC 3986). Non-parseable
134/// strings are lowercased wholesale.
135pub fn normalize_url(url: &str) -> String {
136    let stripped = url.trim_end_matches('/');
137    // Minimal scheme://host split — enough to lowercase scheme+authority
138    // without a URL-parsing dependency.
139    if let Some(scheme_end) = stripped.find("://") {
140        let scheme = &stripped[..scheme_end];
141        let rest = &stripped[scheme_end + 3..];
142        // The authority ends at the FIRST of `/`, `?`, or `#`. Splitting only on
143        // `/` lets a URL with a query/fragment but no path (`host?Query`) fold the
144        // query/fragment into the authority and lowercase it — collapsing distinct
145        // URLs to the same store key. TS normalizeUrl lowercases only host+scheme
146        // and preserves path/query/fragment case; mirror that here.
147        let split_at = rest.find(['/', '?', '#']).unwrap_or(rest.len());
148        let authority = &rest[..split_at];
149        let suffix = &rest[split_at..];
150        format!(
151            "{}://{}{}",
152            scheme.to_lowercase(),
153            authority.to_lowercase(),
154            suffix
155        )
156    } else {
157        stripped.to_lowercase()
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn ask_home_env_and_default() {
167        // Absolute ASK_HOME is used verbatim (cleaned).
168        temp_env("ASK_HOME", Some("/tmp/custom/ask"), || {
169            assert_eq!(resolve_ask_home(), PathBuf::from("/tmp/custom/ask"));
170        });
171        temp_env("ASK_HOME", None, || {
172            assert!(resolve_ask_home().ends_with(".ask"));
173        });
174    }
175
176    #[test]
177    fn npm_and_github_paths() {
178        let home = Path::new("/store");
179        assert_eq!(
180            npm_store_path(home, "next", "15.0.3").unwrap(),
181            PathBuf::from("/store/npm/next@15.0.3")
182        );
183        assert_eq!(
184            github_store_path(home, "github.com", "vercel", "next.js", "v15.0.3").unwrap(),
185            PathBuf::from("/store/github/github.com/vercel/next.js/v15.0.3")
186        );
187    }
188
189    #[test]
190    fn github_path_rejects_traversal_segments() {
191        let home = Path::new("/store");
192        assert!(github_store_path(home, "github.com", "..", "repo", "v1").is_err());
193        assert!(github_store_path(home, "github.com", "o", "re/po", "v1").is_err());
194        assert!(github_store_path(home, "github.com", "o", "repo", "").is_err());
195    }
196
197    #[test]
198    fn assert_contained_blocks_escape() {
199        let parent = Path::new("/store/github");
200        assert!(assert_contained(parent, Path::new("/store/github/a/b")).is_ok());
201        assert!(assert_contained(parent, Path::new("/store/github/../../etc")).is_err());
202        assert!(assert_contained(parent, Path::new("/etc/passwd")).is_err());
203    }
204
205    #[test]
206    fn normalize_url_lowercases_scheme_host_only() {
207        assert_eq!(
208            normalize_url("HTTPS://Example.COM/Docs/"),
209            "https://example.com/Docs"
210        );
211        assert_eq!(normalize_url("https://X.io///"), "https://x.io");
212        // Path case is preserved.
213        assert_eq!(
214            normalize_url("https://x.io/CaseSensitive"),
215            "https://x.io/CaseSensitive"
216        );
217    }
218
219    #[test]
220    fn llms_txt_and_web_paths_hash_normalized_url() {
221        let home = Path::new("/store");
222        // Trailing slash + host case fold to the same hash.
223        let a = llms_txt_store_path(home, "https://X.io/llms.txt", "1");
224        let b = llms_txt_store_path(home, "https://x.io/llms.txt/", "1");
225        assert_eq!(a, b);
226        assert!(web_store_path(home, "https://x.io").starts_with("/store/web/"));
227    }
228
229    fn temp_env(key: &str, value: Option<&str>, f: impl FnOnce()) {
230        let prev = std::env::var_os(key);
231        match value {
232            Some(v) => std::env::set_var(key, v),
233            None => std::env::remove_var(key),
234        }
235        f();
236        match prev {
237            Some(v) => std::env::set_var(key, v),
238            None => std::env::remove_var(key),
239        }
240    }
241}