lean_ctx_cloud/workers/
mod.rs1pub mod attach;
13pub mod card;
14pub mod keys;
15pub mod register;
16pub mod roster;
17
18use ed25519_dalek::SigningKey;
19use unicode_normalization::UnicodeNormalization as _;
20use zeroize::Zeroizing;
21
22use super::instance_key::InstanceKeys;
23
24const WORKER_ALIAS_SALT: &str = "leanctx.cloud.worker-alias.v1";
26const ALIAS_SIGNING_SALT: &str = "leanctx.cloud.alias.v1";
28
29pub const GENERAL_ROLE: &str = "general";
31const ROLE_MAX: usize = 32;
33const NAME_MAX: usize = 64;
35const RESERVED: [&str; 4] = ["cloud", "thinkery", "leanctx", "moderator"];
37
38pub fn normalize_role(role: &str) -> String {
41 let mut out = String::new();
42 for c in role.to_lowercase().chars() {
43 let c = if c.is_ascii_lowercase() || c.is_ascii_digit() {
44 c
45 } else {
46 '-'
47 };
48 if !(c == '-' && out.ends_with('-')) {
49 out.push(c);
50 }
51 }
52 let cut: String = out.trim_matches('-').chars().take(ROLE_MAX).collect();
53 match cut.trim_end_matches('-') {
54 "" => GENERAL_ROLE.to_string(),
55 kept => kept.to_string(),
56 }
57}
58
59const SESSION_TAG_LEN: usize = 8;
61const SESSION_TAG_DOMAIN: &str = "leanctx.cloud.session-agent.v1|";
63
64pub fn session_role(role: &str, app_session: Option<&str>) -> String {
76 let role = normalize_role(role);
77 let Some(session) = app_session.map(str::trim).filter(|s| !s.is_empty()) else {
78 return role;
79 };
80 let digest = blake3::hash(format!("{SESSION_TAG_DOMAIN}{session}").as_bytes());
81 let tag = &base32_lower(digest.as_bytes())[..SESSION_TAG_LEN];
82 let base: String = role.chars().take(ROLE_MAX - 2 - SESSION_TAG_LEN).collect();
83 format!("{}-s{tag}", base.trim_end_matches('-'))
84}
85
86pub fn canonical_instance_id(instance_id: &str) -> String {
90 let hex = instance_id
91 .strip_prefix("inst_")
92 .unwrap_or(instance_id)
93 .replace('-', "")
94 .to_ascii_lowercase();
95 if hex.len() == 32 && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
96 format!(
97 "{}-{}-{}-{}-{}",
98 &hex[..8],
99 &hex[8..12],
100 &hex[12..16],
101 &hex[16..20],
102 &hex[20..]
103 )
104 } else {
105 instance_id.to_string()
106 }
107}
108
109pub fn workspace_worker_id(instance_id: &str, host_app: &str, role: &str) -> String {
112 let instance_id = canonical_instance_id(instance_id);
113 worker_id_of(blake3::hash(format!("{instance_id}|{host_app}|{role}").as_bytes()).as_bytes())
114}
115
116fn worker_id_of(digest: &[u8; 32]) -> String {
117 let mut id = String::from("wkr_");
118 id.push_str(&base32_lower(digest)[..20]);
119 id
120}
121
122fn base32_lower(bytes: &[u8]) -> String {
124 const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
125 let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
126 let (mut buffer, mut bits) = (0u32, 0u32);
127 for &byte in bytes {
128 buffer = (buffer << 8) | u32::from(byte);
129 bits += 8;
130 while bits >= 5 {
131 bits -= 5;
132 out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
133 }
134 }
135 if bits > 0 {
136 out.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char);
137 }
138 out
139}
140
141pub struct WorkerAliasKey(Zeroizing<[u8; 32]>);
143
144impl WorkerAliasKey {
145 pub fn of(keys: &InstanceKeys) -> Self {
146 Self(keys.derive_from_signing_seed(WORKER_ALIAS_SALT, b""))
147 }
148
149 #[cfg(test)]
150 fn from_seed(seed: &[u8; 32]) -> Self {
151 Self(super::instance_key::derive_from_seed(
152 seed,
153 WORKER_ALIAS_SALT,
154 b"",
155 ))
156 }
157
158 pub fn worker_id(&self, host_app: &str, role: &str, place_ref: &str) -> String {
160 let input = format!("{host_app}|{role}|{place_ref}");
161 worker_id_of(blake3::keyed_hash(&self.0, input.as_bytes()).as_bytes())
162 }
163
164 pub fn hlc_node(&self, place_ref: &str) -> String {
166 blake3::keyed_hash(&self.0, place_ref.as_bytes()).to_hex()[..16].to_string()
167 }
168}
169
170pub fn alias_signing_key(keys: &InstanceKeys, place_ref: &str) -> SigningKey {
173 let seed = keys.derive_from_signing_seed(ALIAS_SIGNING_SALT, place_ref.as_bytes());
174 SigningKey::from_bytes(&seed)
175}
176
177pub fn alias_hlc_node(keys: &InstanceKeys, place_ref: &str) -> String {
179 WorkerAliasKey::of(keys).hlc_node(place_ref)
180}
181
182pub fn key_id(key: &SigningKey) -> String {
184 blake3::hash(key.verifying_key().as_bytes()).to_hex()[..16].to_string()
185}
186
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub enum NameRefusal {
190 Length,
191 Charset,
192 Confusable,
193 Reserved,
194}
195
196impl NameRefusal {
197 pub fn code(self) -> &'static str {
198 match self {
199 Self::Length => "length",
200 Self::Charset => "charset",
201 Self::Confusable => "confusable",
202 Self::Reserved => "reserved",
203 }
204 }
205
206 pub fn message(self) -> &'static str {
208 match self {
209 Self::Length | Self::Charset => {
210 "Use 1 to 64 letters, digits, spaces and . _ · - from one alphabet."
211 }
212 Self::Confusable => "This name mixes alphabets. Use one alphabet.",
213 Self::Reserved => {
214 "Names may not contain cloud, thinkery, leanctx or moderator. Pick another name."
215 }
216 }
217 }
218}
219
220const SCRIPTS: [&str; 14] = [
223 "Latin",
224 "Greek",
225 "Cyrillic",
226 "Armenian",
227 "Hebrew",
228 "Arabic",
229 "Devanagari",
230 "Bengali",
231 "Thai",
232 "Georgian",
233 "Hangul",
234 "Hiragana",
235 "Katakana",
236 "Han",
237];
238
239struct NameRules {
240 charset: regex::Regex,
241 letter: regex::Regex,
242 scripts: Vec<regex::Regex>,
243}
244
245fn name_rules() -> &'static NameRules {
246 static RULES: std::sync::OnceLock<NameRules> = std::sync::OnceLock::new();
247 RULES.get_or_init(|| NameRules {
248 charset: regex::Regex::new(r"^[\p{L}\p{N} ._·-]+$").expect("static regex"),
249 letter: regex::Regex::new(r"^\p{L}$").expect("static regex"),
250 scripts: SCRIPTS
251 .iter()
252 .map(|sc| regex::Regex::new(&format!(r"^\p{{sc={sc}}}$")).expect("static regex"))
253 .collect(),
254 })
255}
256
257pub fn check_name(name: &str) -> Result<String, NameRefusal> {
260 let name: String = name.nfkc().collect();
261 let len = name.chars().count();
262 if len == 0 || len > NAME_MAX {
263 return Err(NameRefusal::Length);
264 }
265 let rules = name_rules();
266 if !rules.charset.is_match(&name) {
267 return Err(NameRefusal::Charset);
268 }
269 let mut script = None;
270 let mut buf = [0u8; 4];
271 for ch in name.chars() {
272 let text = ch.encode_utf8(&mut buf);
273 if !rules.letter.is_match(text) {
274 continue;
275 }
276 let this = rules.scripts.iter().position(|r| r.is_match(text));
277 match script {
278 None => script = Some(this),
279 Some(seen) if seen != this => return Err(NameRefusal::Confusable),
280 Some(_) => {}
281 }
282 }
283 let lower = name.to_lowercase();
284 if RESERVED.iter().any(|r| lower.contains(r)) {
285 return Err(NameRefusal::Reserved);
286 }
287 Ok(name)
288}
289
290pub fn default_name(instance_label: &str, host_display: &str, role: &str) -> String {
294 let tail = format!("{host_display} · {role}");
295 let label: String = instance_label
296 .nfkc()
297 .filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '.' | '_' | '-'))
298 .collect();
299 let label = label.split_whitespace().collect::<Vec<_>>().join(" ");
300 let full = format!("{label} · {tail}");
301 if !label.is_empty() && check_name(&full).is_ok() {
302 full
303 } else {
304 tail
305 }
306}
307
308#[cfg(test)]
309mod tests;