Skip to main content

nexo_plugin_browser/
profile.rs

1//! Filesystem-safe agent_id sanitiser + per-agent profile dir
2//! resolver + deterministic ARGB color derivation for Chrome
3//! profile decoration.
4//!
5//! The standalone subprocess holds a
6//! `DashMap<String, ProfileEntry>` keyed on the sanitised
7//! `agent_id` from each [`tool.invoke`] request. This module
8//! provides the three pure helpers `main.rs` calls before
9//! lazy-booting Chrome:
10//!
11//!   * [`sanitize_agent_id`] — convert the wire-format
12//!     `agent_id` into a filesystem-safe path component.
13//!   * [`user_data_dir_for`] — `${BASE}/profiles/<agent_id>/`.
14//!   * [`profile_color_argb`] — stable ARGB int per agent for
15//!     the Chrome profile chip.
16//!
17//! The sanitiser is intentionally strict: it accepts only the
18//! same `[A-Za-z0-9_-]{1,64}` regex `nexo-plugin-manifest::id_regex`
19//! enforces for plugin / agent ids, so operators have one mental
20//! model across the framework.
21
22use std::path::{Path, PathBuf};
23
24use sha2::{Digest, Sha256};
25use thiserror::Error;
26
27const MAX_AGENT_ID_LEN: usize = 64;
28
29/// Errors returned by [`sanitize_agent_id`]. Wrapped through the
30/// caller into `ToolInvocationError::ArgumentInvalid` (see
31/// `src/main.rs::shared_plugin_for`).
32/// Canonical alias for [`ProfileIdError`]. Step 2 of the
33/// browser-multi-instance migration introduces the
34/// instance-namespace-aware name; both refer to the same enum so
35/// existing 0.2.x callers compile unchanged.
36pub type IdError = ProfileIdError;
37
38#[derive(Debug, Clone, Error, PartialEq, Eq)]
39pub enum ProfileIdError {
40    /// `agent_id` was empty or whitespace-only after trimming.
41    #[error("agent_id is empty")]
42    Empty,
43    /// `agent_id` exceeds the [`MAX_AGENT_ID_LEN`] character cap.
44    #[error("agent_id `{0}` exceeds 64 characters")]
45    TooLong(String),
46    /// `agent_id` contains a character outside the allowed set.
47    /// Path traversal (`..`, `/`), control bytes, and Unicode
48    /// punctuation are all rejected here.
49    #[error("agent_id `{0}` contains invalid characters (allowed: [A-Za-z0-9_-])")]
50    Invalid(String),
51}
52
53/// Lowercase + validate the wire-format `agent_id`. Returns the
54/// owned canonical key ready for use as a `DashMap` lookup AND
55/// as a filesystem path component.
56///
57/// Rules (regex `^[a-z0-9_-]{1,64}$` after lowercasing):
58///   * empty / whitespace-only → [`ProfileIdError::Empty`].
59///   * length > 64 → [`ProfileIdError::TooLong`].
60///   * any char outside `[A-Za-z0-9_-]` → [`ProfileIdError::Invalid`].
61pub fn sanitize_id(raw: &str) -> Result<String, IdError> {
62    let trimmed = raw.trim();
63    if trimmed.is_empty() {
64        return Err(ProfileIdError::Empty);
65    }
66    if trimmed.chars().count() > MAX_AGENT_ID_LEN {
67        return Err(ProfileIdError::TooLong(trimmed.to_string()));
68    }
69    for c in trimmed.chars() {
70        if !(c.is_ascii_alphanumeric() || c == '_' || c == '-') {
71            return Err(ProfileIdError::Invalid(trimmed.to_string()));
72        }
73    }
74    Ok(trimmed.to_ascii_lowercase())
75}
76
77/// Deprecated alias of [`sanitize_id`]. Kept for 0.2.x callers.
78#[deprecated(since = "0.3.0", note = "use sanitize_id (namespace-neutral name)")]
79pub fn sanitize_agent_id(raw: &str) -> Result<String, ProfileIdError> {
80    sanitize_id(raw)
81}
82
83/// Compose the per-agent Chrome `user_data_dir`:
84/// `${base}/profiles/<agent_id>/`.
85///
86/// Pure path-join — no filesystem IO. The caller (Chrome
87/// launcher) creates the directory lazily during the boot
88/// sequence; subsequent boots reuse the existing tree (which is
89/// how Chrome persists cookies / localStorage between runs).
90///
91/// `agent_id` MUST already be sanitised via [`sanitize_agent_id`];
92/// this function is a thin join, not a validator. Debug builds
93/// assert the invariant.
94pub fn user_data_dir_for(base: &Path, agent_id: &str) -> PathBuf {
95    debug_assert!(
96        sanitize_id(agent_id).is_ok(),
97        "user_data_dir_for called with un-sanitised agent_id `{agent_id}`"
98    );
99    base.join("profiles").join(agent_id)
100}
101
102/// Stable ARGB int derived from `sha256(agent_id)`'s first 3
103/// bytes (used as RGB) plus a forced `0xFF` alpha. Used by
104/// [`crate::profile_decoration::decorate_profile_dir`] to
105/// stamp the Chrome profile chip with a per-agent color so
106/// operators eyeballing N parallel Chromes can tell them apart
107/// at a glance.
108pub fn profile_color_argb(agent_id: &str) -> i32 {
109    let digest = Sha256::digest(agent_id.as_bytes());
110    let r = digest[0] as u32;
111    let g = digest[1] as u32;
112    let b = digest[2] as u32;
113    let argb_u32 = (0xFFu32 << 24) | (r << 16) | (g << 8) | b;
114    argb_u32 as i32
115}
116
117#[cfg(test)]
118#[allow(deprecated)] // existing tests call the 0.2.x alias; 1 new test below targets `sanitize_id`.
119mod tests {
120    use super::*;
121
122    #[test]
123    fn sanitize_id_is_canonical_entry_point() {
124        // Canonical 0.3.0 name. Behaviour-identical to the
125        // deprecated `sanitize_agent_id` alias; this test pins
126        // the public name so callers can migrate.
127        assert_eq!(sanitize_id("Ana").unwrap(), "ana");
128        assert_eq!(sanitize_id("").unwrap_err(), ProfileIdError::Empty);
129    }
130
131    // ── sanitize_agent_id ────────────────────────────────────
132
133    #[test]
134    fn sanitize_lowercases_and_returns_owned() {
135        assert_eq!(sanitize_agent_id("Ana").unwrap(), "ana");
136    }
137
138    #[test]
139    fn sanitize_accepts_underscores_and_hyphens() {
140        assert_eq!(sanitize_agent_id("agent_x-1").unwrap(), "agent_x-1");
141    }
142
143    #[test]
144    fn sanitize_accepts_max_length_64_chars() {
145        let s = "a".repeat(64);
146        assert_eq!(sanitize_agent_id(&s).unwrap(), s);
147    }
148
149    #[test]
150    fn sanitize_trims_surrounding_whitespace() {
151        assert_eq!(sanitize_agent_id("  ana  ").unwrap(), "ana");
152    }
153
154    #[test]
155    fn sanitize_rejects_empty() {
156        assert_eq!(sanitize_agent_id("").unwrap_err(), ProfileIdError::Empty);
157    }
158
159    #[test]
160    fn sanitize_rejects_whitespace_only() {
161        assert_eq!(
162            sanitize_agent_id("   ").unwrap_err(),
163            ProfileIdError::Empty
164        );
165    }
166
167    #[test]
168    fn sanitize_rejects_too_long_65_chars() {
169        let s = "a".repeat(65);
170        match sanitize_agent_id(&s).unwrap_err() {
171            ProfileIdError::TooLong(got) => assert_eq!(got, s),
172            other => panic!("expected TooLong, got {other:?}"),
173        }
174    }
175
176    #[test]
177    fn sanitize_rejects_path_traversal_dot_dot() {
178        match sanitize_agent_id("..").unwrap_err() {
179            ProfileIdError::Invalid(got) => assert_eq!(got, ".."),
180            other => panic!("expected Invalid, got {other:?}"),
181        }
182    }
183
184    #[test]
185    fn sanitize_rejects_forward_slash() {
186        match sanitize_agent_id("a/b").unwrap_err() {
187            ProfileIdError::Invalid(got) => assert_eq!(got, "a/b"),
188            other => panic!("expected Invalid, got {other:?}"),
189        }
190    }
191
192    #[test]
193    fn sanitize_rejects_control_chars() {
194        match sanitize_agent_id("\x01ana").unwrap_err() {
195            ProfileIdError::Invalid(_) => {}
196            other => panic!("expected Invalid, got {other:?}"),
197        }
198    }
199
200    #[test]
201    fn sanitize_rejects_unicode_punctuation() {
202        match sanitize_agent_id("ana.es").unwrap_err() {
203            ProfileIdError::Invalid(got) => assert_eq!(got, "ana.es"),
204            other => panic!("expected Invalid, got {other:?}"),
205        }
206    }
207
208    #[test]
209    fn sanitize_rejects_non_ascii_letters() {
210        // Sanitiser is intentionally ASCII-only — Chrome profile
211        // dirs should be portable across locales / filesystem
212        // encodings. Operators with non-ASCII agent ids must
213        // pick an ASCII alias.
214        match sanitize_agent_id("ana-ñ").unwrap_err() {
215            ProfileIdError::Invalid(_) => {}
216            other => panic!("expected Invalid, got {other:?}"),
217        }
218    }
219
220    // ── user_data_dir_for ───────────────────────────────────
221
222    #[test]
223    fn user_data_dir_for_joins_profiles_subdir() {
224        let dir = user_data_dir_for(Path::new("/tmp/state"), "ana");
225        assert_eq!(dir, PathBuf::from("/tmp/state/profiles/ana"));
226    }
227
228    #[test]
229    fn user_data_dir_for_handles_relative_base() {
230        let dir = user_data_dir_for(Path::new("./.profile"), "x");
231        assert_eq!(dir, PathBuf::from("./.profile/profiles/x"));
232    }
233
234    // ── profile_color_argb ──────────────────────────────────
235
236    #[test]
237    fn profile_color_argb_deterministic_across_calls() {
238        assert_eq!(profile_color_argb("ana"), profile_color_argb("ana"));
239        assert_eq!(profile_color_argb("juan"), profile_color_argb("juan"));
240    }
241
242    #[test]
243    fn profile_color_argb_alpha_byte_is_ff() {
244        let argb = profile_color_argb("ana") as u32;
245        let alpha = (argb >> 24) & 0xFF;
246        assert_eq!(alpha, 0xFF, "alpha must be 0xFF, got 0x{:02x}", alpha);
247    }
248
249    #[test]
250    fn profile_color_argb_distinct_for_distinct_agents_probabilistic() {
251        // 3-byte prefix collisions are 1-in-2^24; for the small
252        // sample below we expect distinct outputs.
253        let agents = ["ana", "juan", "marketing", "tester", "default"];
254        let mut seen = std::collections::HashSet::new();
255        for agent in agents {
256            let argb = profile_color_argb(agent);
257            assert!(
258                seen.insert(argb),
259                "color collision for `{agent}` (0x{:08x}) within sample",
260                argb as u32
261            );
262        }
263    }
264}