lean_ctx/core/hive/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.hive.worker-alias.v1";
26const ALIAS_SIGNING_SALT: &str = "leanctx.hive.alias.v1";
28
29pub const GENERAL_ROLE: &str = "general";
31const ROLE_MAX: usize = 32;
33const NAME_MAX: usize = 64;
35const RESERVED: [&str; 4] = ["hive", "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
59pub fn canonical_instance_id(instance_id: &str) -> String {
63 let hex = instance_id
64 .strip_prefix("inst_")
65 .unwrap_or(instance_id)
66 .replace('-', "")
67 .to_ascii_lowercase();
68 if hex.len() == 32 && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
69 format!(
70 "{}-{}-{}-{}-{}",
71 &hex[..8],
72 &hex[8..12],
73 &hex[12..16],
74 &hex[16..20],
75 &hex[20..]
76 )
77 } else {
78 instance_id.to_string()
79 }
80}
81
82pub fn workspace_worker_id(instance_id: &str, host_app: &str, role: &str) -> String {
85 let instance_id = canonical_instance_id(instance_id);
86 worker_id_of(blake3::hash(format!("{instance_id}|{host_app}|{role}").as_bytes()).as_bytes())
87}
88
89fn worker_id_of(digest: &[u8; 32]) -> String {
90 let mut id = String::from("wkr_");
91 id.push_str(&base32_lower(digest)[..20]);
92 id
93}
94
95fn base32_lower(bytes: &[u8]) -> String {
97 const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
98 let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
99 let (mut buffer, mut bits) = (0u32, 0u32);
100 for &byte in bytes {
101 buffer = (buffer << 8) | u32::from(byte);
102 bits += 8;
103 while bits >= 5 {
104 bits -= 5;
105 out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
106 }
107 }
108 if bits > 0 {
109 out.push(ALPHABET[((buffer << (5 - bits)) & 31) as usize] as char);
110 }
111 out
112}
113
114pub struct WorkerAliasKey(Zeroizing<[u8; 32]>);
116
117impl WorkerAliasKey {
118 pub fn of(keys: &InstanceKeys) -> Self {
119 Self(keys.derive_from_signing_seed(WORKER_ALIAS_SALT, b""))
120 }
121
122 #[cfg(test)]
123 fn from_seed(seed: &[u8; 32]) -> Self {
124 Self(super::instance_key::derive_from_seed(
125 seed,
126 WORKER_ALIAS_SALT,
127 b"",
128 ))
129 }
130
131 pub fn worker_id(&self, host_app: &str, role: &str, place_ref: &str) -> String {
133 let input = format!("{host_app}|{role}|{place_ref}");
134 worker_id_of(blake3::keyed_hash(&self.0, input.as_bytes()).as_bytes())
135 }
136
137 pub fn hlc_node(&self, place_ref: &str) -> String {
139 blake3::keyed_hash(&self.0, place_ref.as_bytes()).to_hex()[..16].to_string()
140 }
141}
142
143pub fn alias_signing_key(keys: &InstanceKeys, place_ref: &str) -> SigningKey {
146 let seed = keys.derive_from_signing_seed(ALIAS_SIGNING_SALT, place_ref.as_bytes());
147 SigningKey::from_bytes(&seed)
148}
149
150pub fn alias_hlc_node(keys: &InstanceKeys, place_ref: &str) -> String {
152 WorkerAliasKey::of(keys).hlc_node(place_ref)
153}
154
155pub fn key_id(key: &SigningKey) -> String {
157 blake3::hash(key.verifying_key().as_bytes()).to_hex()[..16].to_string()
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162pub enum NameRefusal {
163 Length,
164 Charset,
165 Confusable,
166 Reserved,
167}
168
169impl NameRefusal {
170 pub fn code(self) -> &'static str {
171 match self {
172 Self::Length => "length",
173 Self::Charset => "charset",
174 Self::Confusable => "confusable",
175 Self::Reserved => "reserved",
176 }
177 }
178
179 pub fn message(self) -> &'static str {
181 match self {
182 Self::Length | Self::Charset => {
183 "Use 1 to 64 letters, digits, spaces and . _ · - from one alphabet."
184 }
185 Self::Confusable => "This name mixes alphabets. Use one alphabet.",
186 Self::Reserved => {
187 "Names may not contain hive, thinkery, leanctx or moderator. Pick another name."
188 }
189 }
190 }
191}
192
193const SCRIPTS: [&str; 14] = [
196 "Latin",
197 "Greek",
198 "Cyrillic",
199 "Armenian",
200 "Hebrew",
201 "Arabic",
202 "Devanagari",
203 "Bengali",
204 "Thai",
205 "Georgian",
206 "Hangul",
207 "Hiragana",
208 "Katakana",
209 "Han",
210];
211
212struct NameRules {
213 charset: regex::Regex,
214 letter: regex::Regex,
215 scripts: Vec<regex::Regex>,
216}
217
218fn name_rules() -> &'static NameRules {
219 static RULES: std::sync::OnceLock<NameRules> = std::sync::OnceLock::new();
220 RULES.get_or_init(|| NameRules {
221 charset: regex::Regex::new(r"^[\p{L}\p{N} ._·-]+$").expect("static regex"),
222 letter: regex::Regex::new(r"^\p{L}$").expect("static regex"),
223 scripts: SCRIPTS
224 .iter()
225 .map(|sc| regex::Regex::new(&format!(r"^\p{{sc={sc}}}$")).expect("static regex"))
226 .collect(),
227 })
228}
229
230pub fn check_name(name: &str) -> Result<String, NameRefusal> {
233 let name: String = name.nfkc().collect();
234 let len = name.chars().count();
235 if len == 0 || len > NAME_MAX {
236 return Err(NameRefusal::Length);
237 }
238 let rules = name_rules();
239 if !rules.charset.is_match(&name) {
240 return Err(NameRefusal::Charset);
241 }
242 let mut script = None;
243 let mut buf = [0u8; 4];
244 for ch in name.chars() {
245 let text = ch.encode_utf8(&mut buf);
246 if !rules.letter.is_match(text) {
247 continue;
248 }
249 let this = rules.scripts.iter().position(|r| r.is_match(text));
250 match script {
251 None => script = Some(this),
252 Some(seen) if seen != this => return Err(NameRefusal::Confusable),
253 Some(_) => {}
254 }
255 }
256 let lower = name.to_lowercase();
257 if RESERVED.iter().any(|r| lower.contains(r)) {
258 return Err(NameRefusal::Reserved);
259 }
260 Ok(name)
261}
262
263pub fn default_name(instance_label: &str, host_display: &str, role: &str) -> String {
267 let tail = format!("{host_display} · {role}");
268 let label: String = instance_label
269 .nfkc()
270 .filter(|c| c.is_alphanumeric() || matches!(c, ' ' | '.' | '_' | '-'))
271 .collect();
272 let label = label.split_whitespace().collect::<Vec<_>>().join(" ");
273 let full = format!("{label} · {tail}");
274 if !label.is_empty() && check_name(&full).is_ok() {
275 full
276 } else {
277 tail
278 }
279}
280
281#[cfg(test)]
282mod tests;