nexo_plugin_browser/
profile.rs1use std::path::{Path, PathBuf};
23
24use sha2::{Digest, Sha256};
25use thiserror::Error;
26
27const MAX_AGENT_ID_LEN: usize = 64;
28
29pub type IdError = ProfileIdError;
37
38#[derive(Debug, Clone, Error, PartialEq, Eq)]
39pub enum ProfileIdError {
40 #[error("agent_id is empty")]
42 Empty,
43 #[error("agent_id `{0}` exceeds 64 characters")]
45 TooLong(String),
46 #[error("agent_id `{0}` contains invalid characters (allowed: [A-Za-z0-9_-])")]
50 Invalid(String),
51}
52
53pub 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(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
83pub 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
102pub 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)] mod tests {
120 use super::*;
121
122 #[test]
123 fn sanitize_id_is_canonical_entry_point() {
124 assert_eq!(sanitize_id("Ana").unwrap(), "ana");
128 assert_eq!(sanitize_id("").unwrap_err(), ProfileIdError::Empty);
129 }
130
131 #[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 match sanitize_agent_id("ana-ñ").unwrap_err() {
215 ProfileIdError::Invalid(_) => {}
216 other => panic!("expected Invalid, got {other:?}"),
217 }
218 }
219
220 #[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 #[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 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}