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